Skip to content

Settings Mixin

SettingsMixin

The SettingsMixin allows the plugin to save and load persistent settings to the database.

  • Plugin settings are stored against the individual plugin, and thus do not have to be unique
  • Plugin settings are stored using a "key:value" pair

Plugin Settings

Use the class attribute SETTINGS for a dict of settings that should be added as global database settings.

The dict must be formatted similar to the following sample that shows how to use validator choices and default.

Take a look at the settings defined in InvenTree.common.models.InvenTreeSetting for all possible parameters.

get_setting

Use the get_setting method to retrieve a setting value based on the provided key.

Return the 'value' of the setting associated with this plugin.

Parameters:

Name Type Description Default
key str

The 'name' of the setting value to be retrieved

required
cache bool

Whether to use cached value (default = False)

False
backup_value Any

A backup value to return if the setting is not found

None
Source code in src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def get_setting(
    self, key: str, cache: bool = False, backup_value: Any = None
) -> Any:
    """Return the 'value' of the setting associated with this plugin.

    Arguments:
        key: The 'name' of the setting value to be retrieved
        cache: Whether to use cached value (default = False)
        backup_value: A backup value to return if the setting is not found
    """
    from plugin.models import PluginSetting

    return PluginSetting.get_setting(
        key, plugin=self.plugin_config(), cache=cache, backup_value=backup_value
    )

set_setting

Use the set_setting method to set a value for a specific setting key.

Set plugin setting value by key.

Parameters:

Name Type Description Default
key str

The 'name' of the setting value to be set

required
value Any

The value to be set for the setting

required
user Optional[User]

The user who is making the change (optional)

None
Source code in src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def set_setting(
    self, key: str, value: Any, user: Optional[User] = None, **kwargs
) -> None:
    """Set plugin setting value by key.

    Arguments:
        key: The 'name' of the setting value to be set
        value: The value to be set for the setting
        user: The user who is making the change (optional)
    """
    from plugin.models import PluginSetting
    from plugin.registry import registry

    try:
        plugin = registry.get_plugin_config(self.plugin_slug(), self.plugin_name())
    except (OperationalError, ProgrammingError):  # pragma: no cover
        plugin = None

    if not plugin:  # pragma: no cover
        # Cannot find associated plugin model, return
        logger.error("Plugin configuration not found for plugin '%s'", self.slug)
        return

    PluginSetting.set_setting(key, value, plugin=plugin)

User Settings

Plugins may also define user-specific settings, which allow users to customize the behavior of the plugin on a per-user basis.

To add user-specific settings, use the USER_SETTINGS class attribute in a similar way to the SETTINGS attribute.

get_user_setting

Use the get_user_setting method to retrieve a user-specific setting value based on the provided key and user.

Return the 'value' of the user setting associated with this plugin.

Parameters:

Name Type Description Default
key str

The 'name' of the user setting value to be retrieved

required
user User

The user for which the setting is to be retrieved

required
cache bool

Whether to use cached value (default = False)

False
backup_value Any

A backup value to return if the setting is not found

None
Source code in src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def get_user_setting(
    self, key: str, user: User, cache: bool = False, backup_value: Any = None
) -> Any:
    """Return the 'value' of the user setting associated with this plugin.

    Arguments:
        key: The 'name' of the user setting value to be retrieved
        user: The user for which the setting is to be retrieved
        cache: Whether to use cached value (default = False)
        backup_value: A backup value to return if the setting is not found
    """
    from plugin.models import PluginUserSetting

    return PluginUserSetting.get_setting(
        key,
        plugin=self.plugin_config(),
        user=user,
        cache=cache,
        backup_value=backup_value,
        settings=self.user_settings,
    )

set_user_setting

Use the set_user_setting method to set a value for a specific user setting key.

Set user setting value by key.

Parameters:

Name Type Description Default
key str

The 'name' of the user setting value to be set

required
value Any

The value to be set for the user setting

required
user User

The user for which the setting is to be set

required
Source code in src/backend/InvenTree/plugin/base/integration/SettingsMixin.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def set_user_setting(self, key: str, value: Any, user: User) -> None:
    """Set user setting value by key.

    Arguments:
        key: The 'name' of the user setting value to be set
        value: The value to be set for the user setting
        user: The user for which the setting is to be set
    """
    from plugin.models import PluginUserSetting
    from plugin.registry import registry

    try:
        plugin = registry.get_plugin_config(self.plugin_slug(), self.plugin_name())
    except (OperationalError, ProgrammingError):
        plugin = None

    if not plugin:  # pragma: no cover
        # Cannot find associated plugin model, return
        logger.error("Plugin configuration not found for plugin '%s'", self.slug)
        return

    PluginUserSetting.set_setting(key, value, user, user=user, plugin=plugin)

Example Plugin

Below is a simple example of how a plugin can implement settings:

class PluginWithSettings(SettingsMixin, InvenTreePlugin):

    NAME = "PluginWithSettings"

    SETTINGS = {
        'API_ENABLE': {
            'name': 'API Functionality',
            'description': 'Enable remote API queries',
            'validator': bool,
            'default': True,
        },
        'API_KEY': {
            'name': 'API Key',
            'description': 'Security key for accessing remote API',
            'default': '',
            'required': True,
        },
        'API_URL': {
            'name': _('API URL'),
            'description': _('Base URL for remote server'),
            'default': 'http://remote.url/api',
        },
        'CONNECTION': {
            'name': _('Printer Interface'),
            'description': _('Select local or network printer'),
            'choices': [('local','Local printer e.g. USB'),('network','Network printer with IP address')],
            'default': 'local',
        },
        'NUMBER': {
            'name': _('A Name'),
            'description': _('Describe me here'),
            'default': 6,
            'validator': [
                int,
                MinValueValidator(2),
                MaxValueValidator(25)
            ]
        },
        'ASSEMBLY': {
            'name': _('Assembled Part'),
            'description': _('Settings can point to internal database models'),
            'model': 'part.part',
            'model_filters': {
                'active': True,
                'assembly': True
            }
        },
        'GROUP': {
            'name': _('User Group'),
            'description': _('Select a group of users'),
            'model': 'auth.group'
        },
        'HIDDEN_SETTING': {
            'name': _('Hidden Setting'),
            'description': _('This setting is hidden from the automatically generated plugin settings page'),
            'hidden': True,
        }
    }

More Info

For more information on any of the methods described below, refer to the InvenTree source code.

Hidden Settings

Plugin settings can be hidden from the settings page by marking them as 'hidden'

This mixin defines the helper functions plugin.get_setting, plugin.set_setting and plugin.check_settings to access all plugin specific settings. The plugin.check_settings function can be used to check if all settings marked with 'required': True are defined and not equal to ''. Note that these methods cannot be used in the __init__ function of your plugin.

api_url = self.get_setting('API_URL', cache = False)
self.set_setting('API_URL', 'some value')
is_valid, missing_settings = self.check_settings()
get_setting has an additional parameter which lets control if the value is taken directly from the database or from the cache. If it is left away False is the default that means the value is taken directly from the database.