[Django] Manage settings like writing in settings.py with a model

Settings that are used by the entire web application are generally made in settings.py.

However, if you change the settings frequently, or if you want the client to be able to change them easily, it is useful to be able to change them on the admin admin site.

Method

step 1

Add the following to settings.py

settings.py


INSTALLED_APPS = [
    ~~~~~
    'django.contrib.sites',  #add to
]
SITE_ID = 1  #add to

Step 2

Add the following to models.py.

models.py


from django.contrib.sites.models import Site

class SiteDetail(models.Model):
    site = models.OneToOneField(Site, verbose_name='Site', on_delete=models.PROTECT)
    #The following is an example of adding set items
    DEFAULT_FROM_EMAIL = models.CharField('DEFAULT_FROM_EMAIL', max_length=255, blank=True)

With the sites framework that comes with Django, one website will be assigned one site data. By creating a model like SiteDetail that is linked to this with OneToOne, it seems that you can create a model that represents the settings of the entire website.

Step 3

Add the following

apps.py


from django.apps import AppConfig
from django.db.models.signals import post_migrate


class AppConfig(AppConfig):
    name = 'app'

    def ready(self):
        from .models import create_default_site_detail
        post_migrate.connect(create_default_site_detail, sender=self)

models.py


def create_default_site_detail(sender, **kwargs):
    site = Site.objects.get(pk=settings.SITE_ID)
    SiteDetail.objects.get_or_create(site=site)

Step 4

Add the following

settings.py


MIDDLEWARE = [
    ~~~~~~
    'django.contrib.sites.middleware.CurrentSiteMiddleware',  #add to
]

This will allow you to access the settings with {{request.site}}. For example, you can get the email address set above with {{request.site.sitedetail.DEFAULT_FROM_EMAIL}}.

Step 5

Add the following

admin.py


from django.contrib import admin
from django.contrib.sites.models import Site
from .models import SiteDetail


class SiteDetailInline(admin.StackedInline):
    model = SiteDetail


class SiteAdmin(admin.ModelAdmin):
    inlines = [SiteDetailInline]


admin.site.unregister(Site)
admin.site.register(Site, SiteAdmin)

This allows Site and Site Detail to be edited at the same time.

References

The content is almost the same as the following site, but there were some parts that did not work, so I wrote it in Qiita. https://narito.ninja/blog/detail/104/

Recommended Posts

[Django] Manage settings like writing in settings.py with a model
Implement a Custom User Model in Django
Start Django in a virtual environment with Pipenv
Build a Django environment with Vagrant in 5 minutes
Configure a module with multiple files in Django
Send an email with a user other than EMAIL_HOST_USER written in settings in django
Model changes in Django
How to use fixture in Django to populate sample data associated with a user model
Create a flag in settings that will be True only when testing with Django
Try running python in a Django environment created with pipenv
[In one line] Visualize like a lawn with just Pandas
Create a homepage with django
Until I return something with a line bot in Django!
I made a puzzle game (like) with Tkinter in Python
reload in django shell with ipython
[python] Manage functions in a list
Manage Django config files with Python-decouple
Deploy a Django application with Docker
Django Model with left outer join
Django Tips-Create a ranking site with Django-
Automatically generate model relationships with Django
Build a web application with Django
Make a filter with a django template
Make a model iterator with PySide
GraphQL API with graphene_django in Django
Like button implementation in Django + Ajax
When writing a program in Python
Create a file uploader with Django
Create a LINE Bot in Django
Implementation of custom user model authentication in Django REST Framework with djoser
A series of amateur infrastructure engineers touching Django with Docker (2): Creating a model
[Can be done in 10 minutes] Create a local website quickly with Django
No reason to think while writing a crawler with Django and Celery
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
Install Django in a pipenv virtual environment
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Django: Migration doesn't reflect model in DB
DJango Memo: From the beginning (model settings)
A simple RSS reader made with Django
Play like a web app with ipywidgets
Use a scikit-learn model trained in PySpark
Create a model for your Django schedule
Draw a heart in Ruby with PyCall
Sum of variables in a mathematical model
Creating a login screen with Django allauth
Dynamically specify a ModelChoiceField queryset in Django
Get a reference model using Django Serializer
Manage logrotate generations with a shell script.
A note on enabling PostgreSQL with Django
Implement a model with state and behavior
Try TensorFlow RNN with a basic model
I made a WEB application with Django
If you want to display values using choices in a template in a Django model