in Dev/Code

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 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 file.

    # ...

Now categories is available for use in all your templates.


Write a Comment


  1. Thanks man, that way is very easy to understand and to code. I just added it to my project and it worked perfectly, I needed to have a dynamic name in the base.html.
    My only doubt is if I need to have all those others processors, I only added mine and .auth because it was giving me an error.
    Thanks again!