Custom context processors
When you set up data in view methods or url extra options, you do so to access the data on individual Django templates. Custom Django context processors allow you to set up data for access on all Django templates.
A Django custom context processor
is structured just like a regular Python method with an
HttpRequest
object argument that returns a dictionary.
The returning dictionary keys of the context processor represent
template references and the dictionary values data objects (e.g.
strings, lists, dictionaries) accessible in templates. Listing 3-13
illustrates a custom Django context processor method.
Listing 3-13. Custom Django context processor method
def onsale(request): # Create fixed data structures to pass to template # data could equally come from database queries # web services or social APIs sale_items = {'Monday':'Mocha 2x1','Tuesday':'Latte 2x1'} return {'SALE_ITEMS': sale_items}
As you can see in listing 3-13,
the onsale
method has a request
argument
-- representing an HttpRequest
object -- and returns a
dictionary. The dictionary in this case has a single key called
SALE_ITEMS
and a value which is a hard-coded
dictionary.
However, just as you can set up any type of data in a Django view method or url option to pass to a template, a custom Django context processor method can also access data from the request argument (e.g. cookie, remote IP address) or even query a database and make this data available to all templates.
The custom context processor
method can be placed inside any project file or directory. The
location and naming conventions are of little importance, because
Django detects context processors through the
context_processors
variable in OPTIONS
of
the TEMPLATES
variable in a project's
settings.py
file. I'll place the context processor
method in listing 3-13 in a file called processors.py
in the stores
app sub-directory.
The remaining content for Django 4.0 is only available with a subscription.