~/aglili

Context Processors In Django

Published: 12/29/2025 (Updated: 12/29/2025)

What is a Context Processor??

a context processor in Django is a function that add variable to the global template context so that variable is automatically available for render in all templates

How context processors functions work

They take a request object and return a dictionary. The dictionaries keys then become variables available in the global templates context

Django's Default Context Processors

Django comes with some context processor by default. You can see them in your projects default settings.py file.

they look like this

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

these provide variables like user,messages and request in the global templates scope. they are the reason why you can write something like this in your templates without any preconfiguration

<h1>{{user.username}}</h1>

Custom Context Processors

  • To create a custom context processor, create a file in django app eg: context_processor.py
from django.conf import settings
from datetime import datetime

def site_info(request):
    return {
        'site_name': getattr(settings, 'SITE_NAME', 'My Site'),
        'current_year': datetime.now().year
}

this is responsible for fetching a site name we set in our settings.py if its available , if not then we use the default. it also returns the current year

  • We now how to register our context processor in our settings.py
TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                # ... existing processors
                'yourApp.context_processors.site_info',
            ],
        },
    },
]
  • now we can use it in our templates
<footer>
    <p>&copy; {{ current_year }} {{ site_name }}</p>
</footer>

Common Use Cases

  • User Cart Information
  • Feature Flags
  • Site Wide Settings (company name, contact info, social media links)

Usage Notes

  • Context processors run with every request so they should be lightweight
  • Dont make complex database queries in context processors
  • They only work with templates rendered using RequestContext (which Django's generic views use by default)
  • The request parameter is always passed, even if you don't use it