How to Create Context Processor in Django

Context processors in Django are a great way of making functions available throughout the templates in your project.

 

Let's say, for example, we have some featured categories that we want to display in the header of the website. It wouldn't be a very good idea to create a function in every app view to grab them, instead, we can create a context processor function and tell Django to use it on every template.

 

Step 1

First, add the context processor function to the TEMPLATES sections of your settings.py file inside OPTIONS.context_processors.

 

my_project/settings.py
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',
               'pages.context_processors.global_settings',
               'categories.context_processors.nav_cats', #custom context processor
           ],
       },
   },
]

 

In the above example, I am adding the nav_cats function from the categories app.

 

Step 2

Create a context_processors.py file in the root of the app you referenced in settings.py.

 

Now open the file and add your function to return data anywhere in your templates. In my case, I am grabbing featured categories using a Category model.

 

categories/context_processors.py
from .models import Category

def nav_cats(request):
objects = Category.objects.filter(status=True, featured=True)
return {'nav_cats': objects}

 

Step 3

Now you can call your context processor function from any template and use the data returned from it. In my case, I am looping through and displaying each object.

 

{% for i in nav_cats %}
  <a href="{{ i.get_absolute_url }}" class="mr-2 text-grey-900">{{ i.name }}</a>
{% endfor %}
django