When you want to handle basically fixed constant values such as domain name and site name in Django template, use the function called Context Processor and do not pass the constant from the view side each time, like a constant from within the template Can be handled.
Context Processor is a function that can describe the process of adding variables when passing a context object from a view to a template.
Csrf_token
etc. used in the template are implemented by this mechanism.
The Context Processor is defined as a function that takes a HTTP Request
object as an argument and returns a dictionary-type object.
Create the function name with any name, and create the file under the application directory.
hogeapp/context_processors.py
def my_context_processor(req):
return {
'domain_name': 'https://hogehoge.com',
'site_name': 'Hogehoge Site',
}
In the above example, the dictionary object is simply returned, but you can also describe the process in the same way as a normal function. You can also use this to refer to a constant defined separately in an external file, or change the value of an environment variable depending on the environment.
To use the created Context Processor, you need to set it in config.py
.
Add the function created in the previous section to context_processors
in OPTIONS of TEMPLATES defined in config.py
.
config.py
TEMPLATES = [
{
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'hogeapp.context_processors.my_context_processor', #add to
],
},
},
]
Variables added by the Context Processor can be used from within the template in the same way as variables in a normal context.
template.html
<link rel="icon" href="{{ domain_name }}/favicon.ico">
<title>{{ site_name }}</title>
The Django template language: for Python programmers |Django documentation| Django https://docs.djangoproject.com/ja/2.2/ref/templates/api/#writing-your-own-context-processors
Recommended Posts