Django provides a convenient way to add extra data to the context of a template through context processors. These context processors can be used to display information such as the current user, site-wide settings, or even data that is fetched from the database.
With a few lines of code, you can create your own custom context processors and make them available to all of your templates.
In this article, we will show you how to create custom context processors in Django, and how to use them in your templates.
Before we start, it's important to note that context processors are only available to templates that use the RequestContext
context. If you're using the default django.template.context_processors.request
context processor, then you're already using RequestContext
.
Creating a Custom Context Processor
To create a custom context processor, you first need to create a new file in your app folder. This file can be named anything you like, for example context_processors.py
.
In the new file, create a function that will return the data you want to add to the context. The function should take one parameter, the request object, and should return a dictionary containing the data.
For example:
def site_settings(request):
return {'site_name': 'My awesome site', 'site_creation_date': '12/12/12'}
site_name
and site_creation_date
, with the values 'My awesome site
' and '12/12/12
', respectively.Using the Custom Context Processor
To use the custom context processor, you need to add the name of the function to the context_processors
option in the TEMPLATES
setting in your settings.py
file.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'yourapp.context_processors.site_settings' # <-- our custom context processor ], }, }, ]Note that you have to provide the full path of the
context_processors.py
file. Now, in any template that extends a template that uses the RequestContext
context processor, the site_name
and site_creation_date
variables will be available to use. For example, in your base.html
template, you can use the variables as follows:
<html>
<head>
<title>{{ site_name }}</title>
</head>
<body>
<div>
<p>Created at; {{ site_creation_date }}</p>
</div>
</body>
</html>
As you can see, the context processor makes it easy to add variables that can be used across multiple templates without having to pass them through the view or template.