# Preferences

The settings 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``.

.. note::

    **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``:

.. code-block:: python

    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.

.. code-block:: python

    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 setting by a convenience function of the model:
.. code-block:: python

    from medux.preferences.models import ScopedPreference


in Django Templates
--------------------
Then you can use ``preferences.<namespace>.<key>`` straightforward in your template:

.. code-block:: django

    {% if settings.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* setting for that context.

``medux.preferences`` provides a few helpers that ease your life.
