Allow a Django user to set a theme preference.
-
Install django-theme via pip:
pip install django-theme
-
Add
theme
to yourINSTALLED_APPS
in your project settings.py file:INSTALLED_APPS = [ '...', 'theme', ]
-
Run migrate:
python manage.py migrate
-
Add the following to your
context_processors
setting:TEMPLATES = [ { 'BACKEND': '...', 'OPTIONS': { 'context_processors': [ '...', '...', 'theme.context_processors.theme', ], }, }, ]
-
In your template, you can then use the following snippet (theme options are 'system', 'dark' and 'light'):
<body class="{% spaceless %} {% if theme == 'dark' %} dark-theme {% endif %} {% endspaceless %}">
-
The
Theme
model defines a one-to-one relationship with theUser
model. Therefore, the theme object for a user can be retrieved by using:theme = user.theme
- Compatible with Python 3.8 and above.
- Compatible with Django 3.2 and above.
This project follows semantic versioning (SemVer).
Check the root of the repo for these files.