[PYTHON] Handle constants in Django templates

Introduction

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.

environment

What is Context Processor?

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.

Creating a Context Processor

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.

config.py settings

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
            ],
        },
    },
]

How to call from a template

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>

reference

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

Handle constants in Django templates
PHP var_dump in Django templates
Get parameter values ​​in Django templates
Models in Django
Forms in Django
Designing URL schemes and creating templates in Django
Handle signals in C
Model changes in Django
Handle markdown in python
Handle Parquet in Python
Handle Ambient data in Python
Implement follow functionality in Django
Rename table columns in Django3
Handle environment variables in Python
Output table structure in Django
(Note) Django in Vagrant environment
Show Django ManyToManyField in Template
Handle complex numbers in Python
[Django] How to read variables / constants defined in an external file
reload in django shell with ipython
How to handle session in SQLAlchemy
Set placeholders in input fields in Django
8 Frequently Used Commands in Python Django
Dynamically add form fields in Django
Errors related to memcached in django
Handle csv files with Django (django-import-export)
Implementation of login function in Django
Register your Django application in your project
Handle dates in Linux bash commands
Handle posix message queues in python
Handle NetCDF format data in Python
Handle GDS II format in Python
Handle requests in a separate process
Write foreign key constraints in Django
How to reflect CSS in Django
Switch the language displayed in Django 1.9
The meaning of ".object" in Django
Deploy Django in 3 minutes using docker-compose
Pin factory_boy seed value in Django
GraphQL API with graphene_django in Django
Like button implementation in Django + Ajax
How to handle Japanese in Python
Get the query string (query string) in Django
Create a LINE Bot in Django