code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def destroy(self, request, *args, **kwargs): """Check user permissions before deleting an attachment.""" attachment = self.get_object() if not attachment.check_permission('delete', request.user): raise PermissionDenied( _('User does not have permission to delete this...
Check user permissions before deleting an attachment.
destroy
python
inventree/InvenTree
src/backend/InvenTree/common/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/api.py
MIT
def ready(self): """Initialize restart flag clearance on startup.""" if InvenTree.ready.isRunningMigrations(): return self.clear_restart_flag() self.override_global_settings()
Initialize restart flag clearance on startup.
ready
python
inventree/InvenTree
src/backend/InvenTree/common/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/apps.py
MIT
def override_global_settings(self): """Update global settings based on environment variables.""" overrides = global_setting_overrides() if not overrides: return for key, value in overrides.items(): try: current_value = get_global_setting(key, cre...
Update global settings based on environment variables.
override_global_settings
python
inventree/InvenTree
src/backend/InvenTree/common/apps.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/apps.py
MIT
def currency_code_default(): """Returns the default currency code (or USD if not specified).""" from common.settings import get_global_setting try: code = get_global_setting('INVENTREE_DEFAULT_CURRENCY', create=True, cache=True) except Exception: # pragma: no cover # Database may not y...
Returns the default currency code (or USD if not specified).
currency_code_default
python
inventree/InvenTree
src/backend/InvenTree/common/currency.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/currency.py
MIT
def after_change_currency(setting) -> None: """Callback function when base currency is changed. - Update exchange rates - Recalculate prices for all parts """ import InvenTree.ready import InvenTree.tasks if InvenTree.ready.isImportingData(): return if not InvenTree.ready.canA...
Callback function when base currency is changed. - Update exchange rates - Recalculate prices for all parts
after_change_currency
python
inventree/InvenTree
src/backend/InvenTree/common/currency.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/currency.py
MIT
def currency_exchange_plugins() -> Optional[list]: """Return a list of plugin choices which can be used for currency exchange.""" try: from plugin import PluginMixinEnum, registry plugs = registry.with_mixin(PluginMixinEnum.CURRENCY_EXCHANGE, active=True) except Exception: plugs = [...
Return a list of plugin choices which can be used for currency exchange.
currency_exchange_plugins
python
inventree/InvenTree
src/backend/InvenTree/common/currency.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/currency.py
MIT
def get_price( instance, quantity, moq=True, multiples=True, currency=None, break_name: str = 'price_breaks', ): """Calculate the price based on quantity price breaks. - Don't forget to add in flat-fee cost (base_cost field) - If MOQ (minimum order quantity) is required, bump quanti...
Calculate the price based on quantity price breaks. - Don't forget to add in flat-fee cost (base_cost field) - If MOQ (minimum order quantity) is required, bump quantity - If order multiples are to be observed, then we need to calculate based on that, too
get_price
python
inventree/InvenTree
src/backend/InvenTree/common/currency.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/currency.py
MIT
def get_icon_packs(): """Return a dictionary of available icon packs including their icons.""" global _icon_packs if _icon_packs is None: tabler_icons_path = Path(__file__).parent.parent.joinpath( 'InvenTree/static/tabler-icons/icons.json' ) with open(tabler_icons_path, ...
Return a dictionary of available icon packs including their icons.
get_icon_packs
python
inventree/InvenTree
src/backend/InvenTree/common/icons.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/icons.py
MIT
def validate_icon(icon: str): """Validate an icon string in the format pack:name:variant.""" try: pack, name, variant = icon.split(':') except ValueError: raise ValidationError( f'Invalid icon format: {icon}, expected: pack:name:variant' ) packs = get_icon_packs() ...
Validate an icon string in the format pack:name:variant.
validate_icon
python
inventree/InvenTree
src/backend/InvenTree/common/icons.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/icons.py
MIT
def choices(self): """Return a list of choices for the enum class.""" fnc = getattr(self, 'choice_fnc', None) if fnc: return fnc() return []
Return a list of choices for the enum class.
choices
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save(self, *args, **kwargs): """Enforce validation and clean before saving.""" self.key = str(self.key).upper() do_cache = kwargs.pop('cache', True) self.clean() self.validate_unique() # Execute before_save action self._call_settings_function('before_save',...
Enforce validation and clean before saving.
save
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def build_default_values(cls, **kwargs): """Ensure that all values defined in SETTINGS are present in the database. If a particular setting is not present, create it with the default value """ try: existing_keys = cls.objects.filter(**kwargs).values_list('key', flat=True) ...
Ensure that all values defined in SETTINGS are present in the database. If a particular setting is not present, create it with the default value
build_default_values
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def _call_settings_function(self, reference: str, args, kwargs): """Call a function associated with a particular setting. Args: reference (str): The name of the function to call args: Positional arguments to pass to the function kwargs: Keyword arguments to pass to t...
Call a function associated with a particular setting. Args: reference (str): The name of the function to call args: Positional arguments to pass to the function kwargs: Keyword arguments to pass to the function
_call_settings_function
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def cache_key(self): """Generate a unique cache key for this settings object.""" return self.__class__.create_cache_key( self.key, **self.get_filters_for_instance() )
Generate a unique cache key for this settings object.
cache_key
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save_to_cache(self): """Save this setting object to cache.""" key = self.cache_key # skip saving to cache if no pk is set if self.pk is None: return logger.debug("Saving setting '%s' to cache", key) try: cache.set(key, self, timeout=3600) ...
Save this setting object to cache.
save_to_cache
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def create_cache_key(cls, setting_key, **kwargs): """Create a unique cache key for a particular setting object. The cache key uses the following elements to ensure the key is 'unique': - The name of the class - The unique KEY string - Any key:value kwargs associated with the par...
Create a unique cache key for a particular setting object. The cache key uses the following elements to ensure the key is 'unique': - The name of the class - The unique KEY string - Any key:value kwargs associated with the particular setting type (e.g. user-id)
create_cache_key
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_filters(cls, **kwargs): """Enable to filter by other kwargs defined in cls.extra_unique_fields.""" return { key: value for key, value in kwargs.items() if key in cls.extra_unique_fields }
Enable to filter by other kwargs defined in cls.extra_unique_fields.
get_filters
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_filters_for_instance(self): """Enable to filter by other fields defined in self.extra_unique_fields.""" return { key: getattr(self, key, None) for key in self.extra_unique_fields if hasattr(self, key) }
Enable to filter by other fields defined in self.extra_unique_fields.
get_filters_for_instance
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def all_settings( cls, *, exclude_hidden=False, settings_definition: Union[dict[str, SettingsKeyType], None] = None, **kwargs, ): """Return a list of "all" defined settings. This performs a single database lookup, and then any settings which are not *...
Return a list of "all" defined settings. This performs a single database lookup, and then any settings which are not *in* the database are assigned their default values
all_settings
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def allValues( cls, *, exclude_hidden=False, settings_definition: Union[dict[str, SettingsKeyType], None] = None, **kwargs, ): """Return a dict of "all" defined global settings. This performs a single database lookup, and then any settings which are n...
Return a dict of "all" defined global settings. This performs a single database lookup, and then any settings which are not *in* the database are assigned their default values
allValues
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def check_all_settings( cls, *, exclude_hidden=False, settings_definition: Union[dict[str, SettingsKeyType], None] = None, **kwargs, ): """Check if all required settings are set by definition. Returns: is_valid: Are all required settings defined ...
Check if all required settings are set by definition. Returns: is_valid: Are all required settings defined missing_settings: List of all settings that are missing (empty if is_valid is 'True')
check_all_settings
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_definition(cls, key, **kwargs): """Return the 'definition' of a particular settings value, as a dict object. - The 'settings' dict can be passed as a kwarg - If not passed, look for cls.SETTINGS - Returns an empty dict if the key is not found """ settings...
Return the 'definition' of a particular settings value, as a dict object. - The 'settings' dict can be passed as a kwarg - If not passed, look for cls.SETTINGS - Returns an empty dict if the key is not found
get_setting_definition
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_name(cls, key, **kwargs): """Return the name of a particular setting. If it does not exist, return an empty string. """ setting = cls.get_setting_definition(key, **kwargs) return setting.get('name', '')
Return the name of a particular setting. If it does not exist, return an empty string.
get_setting_name
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_description(cls, key, **kwargs): """Return the description for a particular setting. If it does not exist, return an empty string. """ setting = cls.get_setting_definition(key, **kwargs) return setting.get('description', '')
Return the description for a particular setting. If it does not exist, return an empty string.
get_setting_description
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_units(cls, key, **kwargs): """Return the units for a particular setting. If it does not exist, return an empty string. """ setting = cls.get_setting_definition(key, **kwargs) return setting.get('units', '')
Return the units for a particular setting. If it does not exist, return an empty string.
get_setting_units
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_validator(cls, key, **kwargs): """Return the validator for a particular setting. If it does not exist, return None """ setting = cls.get_setting_definition(key, **kwargs) return setting.get('validator', None)
Return the validator for a particular setting. If it does not exist, return None
get_setting_validator
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_default(cls, key, **kwargs): """Return the default value for a particular setting. If it does not exist, return an empty string """ setting = cls.get_setting_definition(key, **kwargs) default = setting.get('default', '') if callable(default): ...
Return the default value for a particular setting. If it does not exist, return an empty string
get_setting_default
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_choices(cls, key, **kwargs): """Return the validator choices available for a particular setting.""" setting = cls.get_setting_definition(key, **kwargs) choices = setting.get('choices', None) if callable(choices): # Evaluate the function (we expect it will re...
Return the validator choices available for a particular setting.
get_setting_choices
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_object(cls, key, **kwargs): """Return an InvenTreeSetting object matching the given key. - Key is case-insensitive - Returns None if no match is made As settings are accessed frequently, this function will attempt to access the cache first: 1. Check the ephemer...
Return an InvenTreeSetting object matching the given key. - Key is case-insensitive - Returns None if no match is made As settings are accessed frequently, this function will attempt to access the cache first: 1. Check the ephemeral request cache 2. Check the global cache ...
get_setting_object
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting(cls, key, backup_value=None, **kwargs): """Get the value of a particular setting. If it does not exist, return the backup value (default = None) """ if ( cls.CHECK_SETTING_KEY and key not in cls.SETTINGS and not key.startswith('_') ...
Get the value of a particular setting. If it does not exist, return the backup value (default = None)
get_setting
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def set_setting(cls, key, value, change_user=None, create=True, **kwargs): """Set the value of a particular setting. If it does not exist, option to create it. Args: key: settings key value: New value change_user: User object (must be staff member to update a core se...
Set the value of a particular setting. If it does not exist, option to create it. Args: key: settings key value: New value change_user: User object (must be staff member to update a core setting) create: If True, create a new setting if the specified key does not...
set_setting
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def clean(self): """If a validator (or multiple validators) are defined for a particular setting key, run them against the 'value' field.""" super().clean() # Encode as native values if self.is_int(): self.value = self.as_int() elif self.is_bool(): self....
If a validator (or multiple validators) are defined for a particular setting key, run them against the 'value' field.
clean
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def run_validator(self, validator): """Run a validator against the 'value' field for this InvenTreeSetting object.""" if validator is None: return value = self.value # Boolean validator if validator is bool: # Value must "look like" a boolean value ...
Run a validator against the 'value' field for this InvenTreeSetting object.
run_validator
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validate_unique(self, exclude=None): """Ensure that the key:value pair is unique. In addition to the base validators, this ensures that the 'key' is unique, using a case-insensitive comparison. Note that sub-classes (UserSetting, PluginSetting) use other filters to determine if the setting ...
Ensure that the key:value pair is unique. In addition to the base validators, this ensures that the 'key' is unique, using a case-insensitive comparison. Note that sub-classes (UserSetting, PluginSetting) use other filters to determine if the setting is 'unique' or not
validate_unique
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def choices(self): """Return the available choices for this setting (or None if no choices are defined).""" return self.__class__.get_setting_choices( self.key, **self.get_filters_for_instance() )
Return the available choices for this setting (or None if no choices are defined).
choices
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def valid_options(self): """Return a list of valid options for this setting.""" choices = self.choices() if not choices: return None return [opt[0] for opt in choices]
Return a list of valid options for this setting.
valid_options
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_choice(self): """Check if this setting is a "choice" field.""" return ( self.__class__.get_setting_choices( self.key, **self.get_filters_for_instance() ) is not None )
Check if this setting is a "choice" field.
is_choice
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def as_choice(self): """Render this setting as the "display" value of a choice field. E.g. if the choices are: [('A4', 'A4 paper'), ('A3', 'A3 paper')], and the value is 'A4', then display 'A4 paper' """ choices = self.get_setting_choices(self.key, **self.get_fil...
Render this setting as the "display" value of a choice field. E.g. if the choices are: [('A4', 'A4 paper'), ('A3', 'A3 paper')], and the value is 'A4', then display 'A4 paper'
as_choice
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def model_name(self) -> str: """Return the model name associated with this setting.""" setting = self.get_setting_definition( self.key, **self.get_filters_for_instance() ) return setting.get('model', None)
Return the model name associated with this setting.
model_name
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def model_filters(self) -> dict: """Return the model filters associated with this setting.""" setting = self.get_setting_definition( self.key, **self.get_filters_for_instance() ) filters = setting.get('model_filters', None) if filters is not None and type(filters) i...
Return the model filters associated with this setting.
model_filters
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def model_class(self): """Return the model class associated with this setting. If (and only if): - It has a defined 'model' parameter - The 'model' parameter is of the form app.model - The 'model' parameter has matches a known app model """ model_name = self.mode...
Return the model class associated with this setting. If (and only if): - It has a defined 'model' parameter - The 'model' parameter is of the form app.model - The 'model' parameter has matches a known app model
model_class
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def api_url(self): """Return the API url associated with the linked model, if provided, and valid!""" model_class = self.model_class() if model_class: # If a valid class has been found, see if it has registered an API URL try: return model_class.get_api_u...
Return the API url associated with the linked model, if provided, and valid!
api_url
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_bool(self): """Check if this setting is required to be a boolean value.""" validator = self.__class__.get_setting_validator( self.key, **self.get_filters_for_instance() ) return self.__class__.validator_is_bool(validator)
Check if this setting is required to be a boolean value.
is_bool
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def setting_type(self): """Return the field type identifier for this setting object.""" if self.is_bool(): return 'boolean' elif self.is_int(): return 'integer' elif self.is_model(): return 'related field' return 'string'
Return the field type identifier for this setting object.
setting_type
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validator_is_bool(cls, validator): """Return if validator is for bool.""" if validator == bool: return True if type(validator) in [list, tuple]: for v in validator: if v == bool: return True return False
Return if validator is for bool.
validator_is_bool
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_float(self): """Check if the setting is required to be a float value.""" validator = self.__class__.get_setting_validator( self.key, **self.get_filters_for_instance() ) return self.__class__.validator_is_float(validator)
Check if the setting is required to be a float value.
is_float
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validator_is_float(cls, validator): """Return if validator is for float.""" if validator == float: return True if type(validator) in [list, tuple]: for v in validator: if v == float: return True return False
Return if validator is for float.
validator_is_float
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def as_float(self): """Return the value of this setting converted to a float value. If an error occurs, return the default value """ try: value = float(self.value) except (ValueError, TypeError): value = self.default_value return value
Return the value of this setting converted to a float value. If an error occurs, return the default value
as_float
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_int(self): """Check if the setting is required to be an integer value.""" validator = self.__class__.get_setting_validator( self.key, **self.get_filters_for_instance() ) return self.__class__.validator_is_int(validator)
Check if the setting is required to be an integer value.
is_int
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validator_is_int(cls, validator): """Return if validator is for int.""" if validator == int: return True if type(validator) in [list, tuple]: for v in validator: if v == int: return True return False
Return if validator is for int.
validator_is_int
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def as_int(self): """Return the value of this setting converted to a boolean value. If an error occurs, return the default value """ try: value = int(self.value) except (ValueError, TypeError): value = self.default_value return value
Return the value of this setting converted to a boolean value. If an error occurs, return the default value
as_int
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_protected(cls, key, **kwargs): """Check if the setting value is protected.""" setting = cls.get_setting_definition(key, **cls.get_filters(**kwargs)) return setting.get('protected', False)
Check if the setting value is protected.
is_protected
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def is_required(cls, key, **kwargs): """Check if this setting value is required.""" setting = cls.get_setting_definition(key, **cls.get_filters(**kwargs)) return setting.get('required', False)
Check if this setting value is required.
is_required
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save(self, *args, **kwargs): """When saving a global setting, check to see if it requires a server restart. If so, set the "SERVER_RESTART_REQUIRED" setting to True """ overrides = global_setting_overrides() # If an override is specified for this setting, use that value ...
When saving a global setting, check to see if it requires a server restart. If so, set the "SERVER_RESTART_REQUIRED" setting to True
save
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_setting_default(cls, key, **kwargs): """Return the default value a particular setting.""" overrides = global_setting_overrides() if key in overrides: # If an override is specified for this setting, use that value return overrides[key] return super().get_...
Return the default value a particular setting.
get_setting_default
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def requires_restart(self): """Return True if this setting requires a server restart after changing.""" options = InvenTreeSetting.SETTINGS.get(self.key, None) if options: return options.get('requires_restart', False) return False
Return True if this setting requires a server restart after changing.
requires_restart
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def convert_to(self, currency_code): """Convert the unit-price at this price break to the specified currency code. Args: currency_code: The currency code to convert to (e.g "USD" or "AUD") """ try: converted = convert_money(self.price, currency_code) exce...
Convert the unit-price at this price break to the specified currency code. Args: currency_code: The currency code to convert to (e.g "USD" or "AUD")
convert_to
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def process_webhook(self): """Process the webhook incoming. This does not deal with the data itself - that happens in process_payload. Do not touch or pickle data here - it was not verified to be safe. """ if self.token: self.verify = VerificationMethod.TOKEN ...
Process the webhook incoming. This does not deal with the data itself - that happens in process_payload. Do not touch or pickle data here - it was not verified to be safe.
process_webhook
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validate_token(self, payload, headers, request): """Make sure that the provided token (if any) confirms to the setting for this endpoint. This can be overridden to create your own token validation method. """ token = headers.get(self.TOKEN_NAME, '') # no token if se...
Make sure that the provided token (if any) confirms to the setting for this endpoint. This can be overridden to create your own token validation method.
validate_token
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save_data(self, payload=None, headers=None, request=None): """Safes payload to database. Args: payload (optional): Payload that was send along. Defaults to None. headers (optional): Headers that were send along. Defaults to None. request (optional): Original req...
Safes payload to database. Args: payload (optional): Payload that was send along. Defaults to None. headers (optional): Headers that were send along. Defaults to None. request (optional): Original request object. Defaults to None.
save_data
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def check_recent(cls, key: str, uid: int, delta: timedelta): """Test if a particular notification has been sent in the specified time period.""" since = InvenTree.helpers.current_date() - delta entries = cls.objects.filter(key=key, uid=uid, updated__gte=since) return entries.exists()
Test if a particular notification has been sent in the specified time period.
check_recent
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def age(self) -> int: """Age of the message in seconds.""" # Add timezone information if TZ is enabled (in production mode mostly) delta = now() - ( self.creation.replace(tzinfo=timezone.utc) if django_settings.USE_TZ else self.creation ) retur...
Age of the message in seconds.
age
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def rename_notes_image(instance, filename): """Function for renaming uploading image file. Will store in the 'notes' directory.""" fname = os.path.basename(filename) return os.path.join('notes', fname)
Function for renaming uploading image file. Will store in the 'notes' directory.
rename_notes_image
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def fmt_string(self): """Construct a unit definition string e.g. 'dog_year = 52 * day = dy'.""" fmt = f'{self.name} = {self.definition}' if self.symbol: fmt += f' = {self.symbol}' return fmt
Construct a unit definition string e.g. 'dog_year = 52 * day = dy'.
fmt_string
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def validate_unique(self, exclude=None) -> None: """Ensure that the custom unit is unique.""" super().validate_unique(exclude) if self.symbol and ( CustomUnit.objects.filter(symbol=self.symbol).exclude(pk=self.pk).exists() ): raise ValidationError({'symbol': _('U...
Ensure that the custom unit is unique.
validate_unique
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def clean(self): """Validate that the provided custom unit is indeed valid.""" super().clean() from InvenTree.conversion import get_unit_registry registry = get_unit_registry() # Check that the 'name' field is valid self.name = self.name.strip() # Cannot be ze...
Validate that the provided custom unit is indeed valid.
clean
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def after_custom_unit_updated(sender, instance, **kwargs): """Callback when a custom unit is updated or deleted.""" # Force reload of the unit registry from InvenTree.conversion import reload_unit_registry reload_unit_registry()
Callback when a custom unit is updated or deleted.
after_custom_unit_updated
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def rename_attachment(instance, filename: str): """Callback function to rename an uploaded attachment file. Args: instance (Attachment): The Attachment instance for which the file is being renamed. filename (str): The original filename of the uploaded file. Returns: str: The new fi...
Callback function to rename an uploaded attachment file. Args: instance (Attachment): The Attachment instance for which the file is being renamed. filename (str): The original filename of the uploaded file. Returns: str: The new filename for the uploaded file, e.g. 'attachments/<model_...
rename_attachment
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save(self, *args, **kwargs): """Custom 'save' method for the Attachment model. - Record the file size of the uploaded attachment (if applicable) - Ensure that the 'content_type' and 'object_id' fields are set - Run extra validations """ # Either 'attachment' or 'link...
Custom 'save' method for the Attachment model. - Record the file size of the uploaded attachment (if applicable) - Ensure that the 'content_type' and 'object_id' fields are set - Run extra validations
save
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def fully_qualified_url(self): """Return a 'fully qualified' URL for this attachment. - If the attachment is a link to an external resource, return the link - If the attachment is an uploaded file, return the fully qualified media URL """ if self.link: return self.li...
Return a 'fully qualified' URL for this attachment. - If the attachment is a link to an external resource, return the link - If the attachment is an uploaded file, return the fully qualified media URL
fully_qualified_url
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def check_permission(self, permission, user): """Check if the user has the required permission for this attachment.""" from InvenTree.models import InvenTreeAttachmentMixin model_class = common.validators.attachment_model_class_from_label( self.model_type ) if not i...
Check if the user has the required permission for this attachment.
check_permission
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def save(self, *args, **kwargs) -> None: """Ensure that the custom state is valid before saving.""" self.clean() return super().save(*args, **kwargs)
Ensure that the custom state is valid before saving.
save
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_status_class(self): """Return the appropriate status class for this custom state.""" from generic.states import StatusCode from InvenTree.helpers import inheritors if not self.reference_status: return None # Return the first class that matches the reference ...
Return the appropriate status class for this custom state.
get_status_class
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def __str__(self): """Return string representation of the selection list.""" if not self.active: return f'{self.name} (Inactive)' return self.name
Return string representation of the selection list.
__str__
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def get_choices(self): """Return the choices for the selection list.""" choices = self.entries.filter(active=True) return [c.value for c in choices]
Return the choices for the selection list.
get_choices
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def __str__(self): """Return string representation of the selection list entry.""" if not self.active: return f'{self.label} (Inactive)' return self.label
Return string representation of the selection list entry.
__str__
python
inventree/InvenTree
src/backend/InvenTree/common/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/models.py
MIT
def __init__(self, obj: Model, category: str, targets: list, context) -> None: """Check that the method is read. This checks that: - All needed functions are implemented - The method is not disabled via plugin - All needed context values were provided """ # Check...
Check that the method is read. This checks that: - All needed functions are implemented - The method is not disabled via plugin - All needed context values were provided
__init__
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def check_context(self, context): """Check that all values defined in the methods CONTEXT were provided in the current context.""" def check(ref, obj): # the obj is not accessible so we are on the end if not isinstance(obj, (list, dict, tuple)): return ref ...
Check that all values defined in the methods CONTEXT were provided in the current context.
check_context
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def global_setting_disable(self): """Check if the method is defined in a plugin and has a global setting.""" # Check if plugin has a setting if not self.GLOBAL_SETTING: return False # Check if plugin is set plg_cls = self.get_plugin() if not plg_cls: ...
Check if the method is defined in a plugin and has a global setting.
global_setting_disable
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def usersetting(self, target): """Returns setting for this method for a given user.""" return NotificationUserSetting.get_setting( f'NOTIFICATION_METHOD_{self.METHOD_NAME.upper()}', user=target, method=self.METHOD_NAME, )
Returns setting for this method for a given user.
usersetting
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def methods(self): """Return all available methods. This is cached, and stored internally. """ if self.methods_list is None: self.collect() return self.methods_list
Return all available methods. This is cached, and stored internally.
methods
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def collect(self, selected_classes=None): """Collect all classes in the environment that are notification methods. Can be filtered to only include provided classes for testing. Args: selected_classes (class, optional): References to the classes that should be registered. Defaults t...
Collect all classes in the environment that are notification methods. Can be filtered to only include provided classes for testing. Args: selected_classes (class, optional): References to the classes that should be registered. Defaults to None.
collect
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def get_usersettings(self, user) -> list: """Returns all user settings for a specific user. This is needed to show them in the settings UI. Args: user (User): User that should be used as a filter. Returns: list: All applicablae notification settings. ""...
Returns all user settings for a specific user. This is needed to show them in the settings UI. Args: user (User): User that should be used as a filter. Returns: list: All applicablae notification settings.
get_usersettings
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def trigger_notification( obj: Model, category: Optional[str] = None, obj_ref: str = 'pk', **kwargs ): """Send out a notification. Args: obj: The object (model instance) that is triggering the notification category: The category (label) for the notification obj_ref: The reference to...
Send out a notification. Args: obj: The object (model instance) that is triggering the notification category: The category (label) for the notification obj_ref: The reference to the object that should be used for the notification kwargs: Additional arguments to pass to the notificat...
trigger_notification
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def trigger_superuser_notification(plugin: PluginConfig, msg: str): """Trigger a notification to all superusers. Args: plugin (PluginConfig): Plugin that is raising the notification msg (str): Detailed message that should be attached """ users = get_user_model().objects.filter(is_superu...
Trigger a notification to all superusers. Args: plugin (PluginConfig): Plugin that is raising the notification msg (str): Detailed message that should be attached
trigger_superuser_notification
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def deliver_notification( cls: NotificationMethod, obj: Model, category: str, targets: list, context: dict ): """Send notification with the provided class. Arguments: cls: The class that should be used to send the notification obj: The object (model instance) that triggered the notification...
Send notification with the provided class. Arguments: cls: The class that should be used to send the notification obj: The object (model instance) that triggered the notification category: The category (label) for the notification targets: List of users that should receive the notif...
deliver_notification
python
inventree/InvenTree
src/backend/InvenTree/common/notifications.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/notifications.py
MIT
def to_representation(self, instance) -> str: """Return the value of the setting. Protected settings are returned as '***' """ if instance.protected: return '***' elif instance.value is None: return '' else: return str(instance.value)
Return the value of the setting. Protected settings are returned as '***'
to_representation
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def to_internal_value(self, data) -> str: """Return the internal value of the setting.""" if data is None: return '' else: return str(data)
Return the internal value of the setting.
to_internal_value
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def validate_value(self, value): """Validate the value of the setting.""" if value is None: return '' return str(value)
Validate the value of the setting.
validate_value
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def get_choices(self, obj) -> list: """Returns the choices available for a given item.""" results = [] choices = obj.choices() if choices: for choice in choices: results.append({'value': choice[0], 'display_name': choice[1]}) return results
Returns the choices available for a given item.
get_choices
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def get_read_only(self, obj) -> bool: """Return True if the setting 'read_only' (cannot be edited). A setting may be "read-only" if: - It is overridden by an environment variable. """ from common.settings import global_setting_overrides overrides = global_setting_overr...
Return True if the setting 'read_only' (cannot be edited). A setting may be "read-only" if: - It is overridden by an environment variable.
get_read_only
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def __init__(self, *args, **kwargs): """Init overrides the Meta class to make it dynamic.""" class CustomMeta: """Scaffold for custom Meta class.""" fields = [ 'pk', 'key', 'value', 'name', 'descrip...
Init overrides the Meta class to make it dynamic.
__init__
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def get_target(self, obj) -> dict: """Function to resolve generic object reference to target.""" target = get_objectreference(obj, 'target_content_type', 'target_object_id') if target and 'link' not in target: # Check if object has an absolute_url function if hasattr(obj...
Function to resolve generic object reference to target.
get_target
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def to_representation(self, instance): """Return the configuration data as a dictionary.""" if not isinstance(instance, str): instance = list(instance.keys())[0] return {'key': instance, **self.instance[instance]}
Return the configuration data as a dictionary.
to_representation
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def annotate_queryset(queryset): """Add custom annotations to the queryset. - last_run: The last time the task was run - success: The outcome status of the last run """ task = django_q.models.Task.objects.filter(id=OuterRef('task')) queryset = queryset.annotate( ...
Add custom annotations to the queryset. - last_run: The last time the task was run - success: The outcome status of the last run
annotate_queryset
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def __init__(self, *args, **kwargs): """Override the model_type field to provide dynamic choices.""" super().__init__(*args, **kwargs) if len(self.fields['model_type'].choices) == 0: self.fields[ 'model_type' ].choices = common.validators.attachment_model...
Override the model_type field to provide dynamic choices.
__init__
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def save(self, **kwargs): """Override the save method to handle the model_type field.""" from InvenTree.models import InvenTreeAttachmentMixin from users.permissions import check_user_permission model_type = self.validated_data.get('model_type', None) if model_type is None and ...
Override the save method to handle the model_type field.
save
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def validate(self, attrs): """Ensure that the selection list is not locked.""" ret = super().validate(attrs) if self.instance and self.instance.list.locked: raise serializers.ValidationError({'list': _('Selection list is locked')}) return ret
Ensure that the selection list is not locked.
validate
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def is_valid(self, *, raise_exception=False): """Validate the selection list. Choices are validated separately.""" choices = ( self.initial_data.pop('choices') if self.initial_data.get('choices') is not None else [] ) # Validate the choices _c...
Validate the selection list. Choices are validated separately.
is_valid
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT
def create(self, validated_data): """Create a new selection list. Save the choices separately.""" list_entry = common_models.SelectionList.objects.create(**validated_data) for choice_data in self._choices_validated: common_models.SelectionListEntry.objects.create(**{ ...
Create a new selection list. Save the choices separately.
create
python
inventree/InvenTree
src/backend/InvenTree/common/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/common/serializers.py
MIT