Preferences¶
The preferences framework is a generic framework which could easily be used in other applications too, as it is only loosely coupled to MedUX. Maybe someday I'll separate it as a standalone project.
It provides models views, and tools to use scoped configuration settings in your application. There are other approaches within Django apps, but none of them are easy to use and flexible, or are too complicated and error-prone.
Installation¶
First, add medux.preferences
to your INSTALLED_APPS
.
**TODO:** document views
To include settings in your application, you can use them in a template. It provides a context processor to add settings
as template variable Just add medux.preferences.context_processors.settings
to your context_processors
:
TEMPLATES = [{
# ...
"OPTIONS": {
"context_processors": [
# ...
"medux.preferences.context_processors.settings",
]
}
}]
Usage¶
in Python code:¶
First, your app needs to register a setting, to let the app know about it. When a setting is saved or loaded later, the registry is always asked for the correct "syntax" or scope contraints. The ideal place for registering is the AppConfig.ready()
method.
from medux.preferences.registry import PreferencesRegistry
class FooConfig(MeduxPluginAppConfig):
def ready(self):
# register a new setting
PreferencesRegistry.register(
namespace="prescriptions",
key="use_approval",
allowed_scopes=[Scope.TENANT],
key_type=KeyType.STRING,
help_text=_("Force approval of prescriptions"),
icon="gear"
)
Next, you can get a preference by a convenience method, given a request:
from medux.preferences.tools import get_effective_preference
def my_view(request):
foo_bar = get_effective_preference(namespace="foo", key="bar", request=request)
in Django templates¶
You can use preferences.<namespace>.<key>
straightforward in your template:
{% if preferences.prescriptions.use_approval %}
we are using approvals for prescriptions
{% endif %}
The key is automatically generated by the context processor and matches the TENANT
, GROUP
, DEVICE
, and USER
of the current request - so it is the effective preference for that context.
medux.preferences
provides a few helpers that ease your life.