Save arbitrary settings per user.
This pluggable Django app should integrate easily with other apps, also in existing projects.
- Django (of course) 2.2+
- django-picklefield
Install into your python path using pip:
pip install git+https://github.com/fiee/django-userpreferences.git
Add 'preferences' to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = (
...
'preferences',
)
Add '('preferences', include('preferences.urls'))' to your urls:
urlpatterns = [
....
path('preferences', include('preferences.urls')),
]
Don't forget to run
./manage.py makemigrations preferences ./manage.py migrate
to create the preferences table.
Add a preferences.py file to your app test_app:
test_app/ -- preferences.py -- models.py -- views.py
That looks like this:
PREFERENCES = (
'mailing_period':(
# ('Preference Display', 'value')
('Weekly', 'week'), # first item is the default value
('Monthly', 'month'),
('Daily', 'day'),
)
)
You can now access user preferences within your views:
>>> user.preferences['test_app']
{'mailing_period' : 'week'}
>>> user.preferences['test_app'] = { 'mailing_period' : 'month' }
>>> user.preferences.save()
>>> user.preferences['test_app']
{'mailing_period' : 'month'}
Note: Though it may have some properties of a dict, user.preferences is not a dict.
It's a Model object; dict behaviour is a shortcut for user.preferences.preferences.
If you use the preferences urls, there’s an url to change preferences:
<a href="http://github.com/%7B%%20url%20preferences.views.change'test_app' 'mailing_period' 'month' %}?return_url='/'>Receive monthly newsletter</a>
If the value in the database does not match any of the preferences in your
preferences.py, the default value will be returned (this allows to disable
preferences after people actually used them, without breaking your app).
Since we use pickle serialization, you can use only pickle-able settings. These include strings, integers, floats, booleans, tuples, lists, sets.
Only discrete sets of settings are allowed for now. Patches are welcome for preferences that accept user input.
django-userpreferences uses a separator between app name and preference name in forms. By default the separator is '/'. To override this, in the weird case you might be needing it in some variable name, you need to change it in your settings.py file:
PREFERENCES_SEPARATOR = '/'
- Nicolas Patry, <[email protected]> (first author)
- Henning Hraban Ramm, <[email protected]> (i18n, fixes, adaption to Django 2+)
- Gonzalo Delgado, <[email protected]> (form)
- Andrei Kuziakov (adaption to Django 1.7, tests, migration)
GNU Lesser/Library Public License (LGPL)
django-picklefield is MIT-licensed. Django itself is BSD-licensed. Discuss.