Evgenii Legotckoi
Evgenii LegotckoiNov. 22, 2019, 2:03 a.m.

Django - Tutorial 050. Creating Dynamic Site Settings Using SingletonModel

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.


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):
        self.__class__.objects.exclude(id=self.id).delete()
        super(SingletonModel, self).save(*args, **kwargs)

    @classmethod
    def load(cls):
        try:
            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'

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
        try:
            SiteSettings.load().save()
        except ProgrammingError:
            pass

    # 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


admin.site.register(SiteSettings, SiteSettingsAdmin)

Now the settings can be used in Python code

Creating a context processor to load settings into a template

context_proccessors.py

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

from evileg_settings.models import SiteSettings


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

settings.py

Then we connect load_settings

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # Загружаем наши настройки при каждом рендеринге шаблона с контекстом
                'my_app.context_processors.load_settings', 
            ],
        },
    },
]

Usage in the template

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

Conclusion

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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 p.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 p.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 9:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 10:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks