Yayyy!! Mindbrews First Edition is now live on Magzter!

Developers & Open Source

Context processor in Django

We can all agree that we have come across request.user in a django project. Have you ever wondered what it was ? Well, its an inbuilt context processor.

A context processor is a function that accepts an argument and returns a dictionary as its output. In our case, the returning dictionary is added as the context and the biggest advantage is that, it can be accessed globally i.e, across all templates. While this might seem too complex or hard to achieve, its actually not the case and it is very simple to implement.

Now lets understand it by taking some examples:

Example 1: Building a dynamic footer using context processor

So, now we will look into building a dynamic footer using the context processor – a footer which can render the year dynamically, pretty convenient, when you dont have to change your source code every year.

Suggested:  A learning Step Towards Git...

First,create (or add to) a file in your app directory called context_processors.py:

import datetime

def get_current_year_to_context(request):
    current_datetime = datetime.datetime.now()
    return {
        'current_year': current_datetime.year
    }

Second, you need to specify your context processor in your settings file.

TEMPLATES = [
{
        ...
        'OPTIONS': {
           'context_processors': [
             ...
            'myapp.context_processors.get_current_year_to_context', # <-- Add your context processor
              ],
          },
     },
]

Thats it. Your context processor is now ready to be used in your templates and it can be accessed using the key that we specified ‘current_year’. So, to create a dynamic footer section, all i need to do is.

Copyright {{ current_year }} - Rithik Manchanda

Example 2: Using a context processor to access your most recent blog entries in all templates

Assuming you have a model called Post defined in your models.py file that contains blog posts, and has a date_published field.

Suggested:  GPT-3: The Gamechanger Is Here

Step 1: Write the context processor

Firstly, to the file named as context_processors.py as created for above you need to add the following code.

from myapp.models import Post

def recent_blog_posts(request):
    return {'recent_posts':Post.objects.order_by('-date_published')[0:3],}  # Can change numbers for more/fewer posts

Step 2: Add the context processor to your settings file

Make sure that you add your new context processor to your settings.py file in the TEMPLATES variable

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'myapp.context_processors.get_current_year_to_context',
                'myapp.context_processors.recent_blog_posts',# <-- Add your context processor
            ],
        },
    },
]

Step 3: Use the context processor in your templates

No need to pass recent blog entries through individual views anymore! Just use recent_blog_posts in any template.

Suggested:  Top 4 highly paid programming languages in 2019

E.g., in home.html you could create a sidebar with links to recent posts:

<div class="blog_post_sidebar">
    {% for post in recent_blog_posts %}
        <div class="post">
            <a href="{{post.get_absolute_url}}">{{post.title}}</a>
        </div>
    {% endfor %}
</div>

Or in blog.html you could create a more detailed display of each post:

<div class="content">
    {% for post in recent_blog_posts %}
        <div class="post_detail">
            <h2>{{post.title}}</h2>
            <p>Published on {{post.date_published}}</p>
            <p class="author">Written by: {{post.author}}</p>
            <p><a href="{{post.get_absolute_url}}">Permalink</a></p>
            <p class="post_body">{{post.body}}</p>
        </div>
    {% endfor %}
</div>

So now, i think you may have got a clear idea about how context processors works and makes your work a lot simple and dynamic.

Try practicing it in your own app to get a better hand on it. And in case of any doubt or issue feel free to write it down in the comment section. ✌

Rithik Manchanda
About author

I solve problems in creative ways. At Ajay Kumar Garg, where I am completing my 3rd year in the College of Engineering, I have learned the importance of applying classical strategies to modern-day projects. Concentrations in IT engineering provide a broad knowledge of engineering concepts. Passion for innovation and high-quality production.
Related posts
Developers & Open SourceSpecificationsTechnology

Intriguing Machine Learning Projects That Every ML Enthusiast Must Know Of

Developers & Open Source

How to Filter for Values in a Django QuerySet?

Developers & Open Source

How to create a Python Virtual Environment?

Developers & Open Source

Superpower your Static HTML with Static Jinja!