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.
Add the following to settings.py
settings.py
INSTALLED_APPS = [
~~~~~
'django.contrib.sites', #add to
]
SITE_ID = 1 #add to
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.
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)
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}}
.
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.
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