Django “Global” Template Variable

Depending on the project you are working on, you might want to access one or more template variables across all your templates like the User object. If you are making news or blog project, one example would be navigation bar item, say a category list.

You might be tempted to pass the category list from your views or create a template tag for that; but that just violate the Django’s DRY principle. So the best way would be through custom context processor. Writing your own is actually very easy.

1. Writing the context processor function.

You can put this function anywhere in your project. My preference is to place this code inside a context_processors.py file under the related app.

# The context processor function
def categories(request):
    all_categories = Category.objects.all()

    return {
        'categories': all_categories,
    }

Note: Each context processor must return a dictionary and takes only one arguement, HttpRequest object.

2. Point it to your TEMPLATE_CONTEXT_PROCESSORS in your settings.py file.

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    # ...
    "yourapp.context_processors.categories"
)

Now categories is available for use in all your templates.

Done!