Built-in context processors
By default, Django templates are enabled to have access to various variables. This eliminates the need to constantly declare widely used variables in every single Django view methods or as url extra options. These variables are made available through template context processors.
Django template context
processors are explicitly defined in a project's
settings.py
file, in the TEMPLATES
variable inside the OPTIONS
key. By default and as
illustrated in listing 3-1, Django projects are enabled with four
context processors built-in to Django. Next, I'll describe the data
variables made available by each of these context processors.
Django debug context processor (django.template.context_processors.debug)
The Django debug context processor exposes variables that are helpful for debugging. This context processor makes the following variables available on all Django templates:
debug
.- Contains True or False, based on theDEBUG
variable in thesettings.py
file.sql_queries
.- Contains the database connection details (e.g. SQL statements) run by the backing method view.
Note The Django debug context processor displays variable values only if the requesting IP address is defined in the INTERNAL_IPS variable in settings.py. Even if the variables are declared in a template (e.g.{{debug}} or {{sql_queries}}) this restriction permits that only certain users view the debug messages in the template, while other users won't view anything.
For example, to view the debug and sql_queries values on your local workstation, add INTERNAL_IPS = ['127.0.0.1'] to the settings.py file. This tells Django to display these variables values for requests made from the IP address 127.0.0.1
Django request context processor (django.template.context_processors.request)
The Django request context
processor exposes variables related to a request (i.e. HTTP
request). This context processor makes data available through a
massive dictionary named request
, which includes some
of the following key-values:
request.GET
.- Contains a request's HTTP GET parameters.request.POST
.- Contains a request's HTTP POST parameters.request.COOKIES
.- Contains a request's HTTP COOKIES.request.CONTENT_TYPE
.- Contains a request's HTTP Content-type header.request.META
.- Contains a request's HTTP META data.request.REMOTE_ADDR
.- Contains a request's HTTP remote address.
The remaining content for Django 4.0 is only available with a subscription.