Django - Tutorial 050. Creating Dynamic Site Settings Using SingletonModel

Django, SingletonModel, singleton, Model

Let's say you create a site with CMS based on Django, which must have some kind of dynamic site settings that will be available to the user. For example, the name of the site, some specialized information, while you take into account the possibility of multilingualism. What then can be used for this? I got the idea to use a database.

To implement this, the following is required:

  1. Creating a data model that will always contain only one object, that is, only one record. That is, it will be a Singleton Model.
  2. Prohibit deleting this entry and creating new ones in the Django admin panel
  3. The ability to use information from this model directly in the template, without loading the site settings in the view function.

Let's figure out in order how to implement this.

1. SingletonModel

I found on GitHub the code of the abstract SingletonModel, which was written back in 2012. Here is a link to gist .

Here is the code for this SingletonModel

class SingletonModel(models.Model):
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        super(SingletonModel, self).save(*args, **kwargs)

    def load(cls):
            return cls.objects.get()
        except cls.DoesNotExist:
            return cls()

The model in the save method automatically saves all the others when saving the object, which allows you to always keep only one instance of this model in the database.

The load method takes from the database the only settings object, if the object does not exist in the database, it returns a new instance of this model, which will need to be saved later.

Let's create a custom settings class to use it for our needs in the future.

# -*- coding: utf-8 -*-

from django.db import models
from django.utils.translation import ugettext_lazy as _

from my_app.singleton_model import SingletonModel

class SiteSettings(SingletonModel):
    site_url = models.URLField(verbose_name=_('Website url'), max_length=256)
    title = models.CharField(verbose_name=_('Title'), max_length=256)

    def __str__(self):
        return 'Configuration'

2. Setting up the administration panel

Now you need to prohibit deleting this entry and creating new ones in the Django admin panel.

# -*- coding: utf-8 -*-

from django.contrib import admin
from django.db.utils import ProgrammingError

from my_app.models import SiteSettings

class SiteSettingsAdmin(admin.ModelAdmin):
    # Create a default object on the first page of SiteSettingsAdmin with a list of settings
    def __init__(self, model, admin_site):
        super().__init__(model, admin_site)
        # be sure to wrap the loading and saving SiteSettings in a try catch,
        # so that you can create database migrations
        except ProgrammingError:

    # prohibit adding new settings
    def has_add_permission(self, request, obj=None):
        return False

    # as well as deleting existing
    def has_delete_permission(self, request, obj=None):
        return False, SiteSettingsAdmin)

Now the settings can be used in Python code

3. Creating a context processor to load settings into a template

# -*- coding: utf-8 -*-

from evileg_settings.models import SiteSettings

def load_settings(request):
    return {'site_settings': SiteSettings.load()}

Then we connect load_settings

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Загружаем наши настройки при каждом рендеринге шаблона с контекстом

Usage in the template

<h1>{{ site_settings.title }}</h1>


So quickly and simply, you can implement simple dynamic site settings in Django and then bind them to all the site parameters that interest us.
The advantage of this approach will be the ability to use foreign keys for some special data on the site, as well as the use of django modeltranslation, which means there will be no problems with multilingualism.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

Feb. 17, 2020, 2:41 p.m.

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
Feb. 17, 2020, 6:02 a.m.

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
Feb. 17, 2020, 5:49 a.m.

C++ - Test 001. The first program and data types

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 3:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/
Feb. 16, 2020, 1:36 p.m.

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 9:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
Feb. 16, 2020, 9:29 a.m.

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
Feb. 20, 2020, 1:24 a.m.
Igor' Poroshin

QSqlQuery query("SELECT CONCAT("#", LPAD(HEX(`t`.RGB), 6, 0)) FROM table AS t");query.exec(); while ( { QColor(query.value(0).toString()); }
Feb. 19, 2020, 11:55 p.m.
Igor' Poroshin

qDebug() << model->lastError().text() - возвращает текст и код ошибки, который возвращает база данных, чаще всего ошибка бывает из-за неправильного SQL запроса qDebug() << mo…
Feb. 19, 2020, 8:55 a.m.

Можно через сервер сделать
Feb. 19, 2020, 7:09 a.m.

Да, прямо сходу не заработало, а сейчас просто некогда разбираться, да и я уже решил не использовать в этом приложении WebEngine. Ошибка: WebEngineContext used before QtWebEngine::initialize(…
Feb. 19, 2020, 7:01 a.m.

Просто реально не вижу тут каких то проблем в модели, вот вообще ничего. Но она все равно не отображается, то есть ладно бы если данные бы не появлялись а сама таблица была бы. Так и таблиц…
© EVILEG 2015-2019
Recommend hosting TIMEWEB