[PYTHON] How to set variables that can be used throughout the Django app-useful for templates, etc.-

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.

environment

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.

Variables handled by Template are usually passed through view, but ...

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.

Normal reference method

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.

Setting constants that can be used throughout the app

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_NAMEtoreturn. 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.

If you want to set a value in settings.py

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.

Recommended Posts

How to set variables that can be used throughout the Django app-useful for templates, etc.-
How to filter foreign keys that can be selected on the Django admin screen
About the matter that the re.compiled object can be used for the re.match pattern
Functions that can be used in for statements
How to install a Python library that can be used by pharmaceutical companies
[Small story] How to install the module when pip cannot be used due to proxy etc.
How to set up a simple SMTP server that can be tested locally in Python
[For beginners] How to use for statements on Linux (variables, etc.)
Goroutine (parallel control) that can be used in the field
[Django] Field names, user registration, and login methods that can be used in the User model
How to solve the problem that video content cannot be played on Firefox for Linux
Goroutine that can be used in the field (errgroup.Group edition)
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference
[Flask] I tried to summarize the "docker-compose configuration" that can be created quickly for web applications
I tried to expand the database so that it can be used with PES analysis software
Understand the probabilities and statistics that can be used for progress management with a python program
How to set the output resolution for each keyframe in Blender
Python standard module that can be used on the command line
Can the Kalman filter be used to predict stock price trends?
Solution to the problem that Ctrl + z cannot be used in Powershell in Docker for windows environment (provisional)
I created a template for a Python project that can be used universally
Hide the warning that zsh can be used by default on Mac
How to make a rock-paper-scissors bot that can be easily moved (commentary)
How to pass values to JavaScript variables directly from the [Django] template tag
It seems that cancelall childorders can be used to cancel all parent orders (special orders) with the bitflyer API
How to check the version of Django
How to set the server time to Japanese time
QPS control that can be used in the field (Rate Limit) Limits execution to n times per second
[Python3] Code that can be used when you want to change the extension of an image at once
A memo for making a figure that can be posted to a journal with matplotlib
I tried to summarize the operations that are likely to be used with numpy-stl
I tried to make OneHotEncoder, which is often used for data analysis, so that it can reach the itch.
Libraries that should be included when creating APIs in the Django Rest Frakework environment, vscode extensions, etc. (for beginners)
How to specify the launch browser for JupyterLab 3.0.0
How to use MkDocs for the first time
File types that can be used with Go
How to print debug messages to the Django console
How to set CPU affinity for process threads
The problem that the ifconfig command cannot be used
Overview and useful features of scikit-learn that can also be used for deep learning
[Jinja2] Solution to the problem that variables added in the for statement are not inherited
Convert images from FlyCapture SDK to a form that can be used with openCV
I will try to summarize the links that seem to be useful for the time being
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
How to create a property of relations that can be prefetch_related by specific conditions
File sharing server made with Raspberry Pi that can be used for remote work
How to set the development environment for each project with VSCode + Python extension + Miniconda
How to extract conditions (acquire all elements of Group that satisfy the conditions) for Group by Group
Simple statistics that can be used to analyze the effect of measures on EC sites and codes that can be used in jupyter notebook
I made a tool to automatically generate a state transition diagram that can be used for both web development and application development
[New employee studying] Let's summarize the Linux commands that are likely to be used for network construction from now on