When creating an app with Django, it's often useful to have constants (variables) that can be used throughout the site.
For example, the text to be displayed throughout the site, such as the app name and version.
Django uses the Context Processor to retrieve the defined constants. Of course, multiple settings are possible.
soft | version |
---|---|
Nginx | 1.16.1 |
uWSGI | 2.0.18 |
Python | 3.8.2 |
Django | 3.0.5 |
It's the way Django 3.0.x works.
Template gets and displays variables like {{variable}}
, which is usually passed through view. This method is inefficient because it is necessary to describe the process of passing variables for each application.
test/view.py
def viewFunc(request):
template_name = "template.html"
context = {"variable" : "hello world!"}
return render(request,template_name,context)
Create a view function in your app's view and pass the value as context.
template.html
<p>{{Variable name}}</p>
It will be displayed in the template in this way.
By creating a Context Processor, you can pass values / objects to the entire app.
app/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
…
'mlapp.context_processors.constant_text',, #Add this
],
},
},
]
The function called constant_text that we will add will get the value of the template.
app/context_processors.py
def constant_text(request):
return {
'APP_NAME': 'TEST APP',
}
I added ʻAPP_NAMEto
return. Create
context_processors.py in the same directory as
settings.py`.
template.html
<p>{{ APP_NAME }}</p>
Now you can get the variables from the whole app and display them in the template. That's all, so it's easy.
settings.py
APP_DESCRIPTION='This is a test app.'
Create a variable in settings.py
and assign the value.
app/context_processors.py
from django.conf import settings
def constant_text(request):
return {
'APP_NAME': 'TEST APP',
'APP_DESCRIPTION': settings.APP_DESCRIPTION,
}
Read the value from settings.py
.
template.html
<h1>{{ APP_NAME }}</h2>
<p>{{ APP_DESCRIPTION }}</p>
By doing this, you can also handle the value of settings.py
.
It's very easy.