How to Implement Global Responses in Django Using Context Processors

Hi Guys!,
Have you encountered challenges when needing to use a consistent response or value across multiple pages in your Django project? Instead of duplicating code in each view, we can leverage the power of context processors to streamline our development process and reduce redundancy.

In this discussion, we’ll explore the efficient use of context processors in Django. in the first place what is context processors in Django?

What is Context Processors?

Context processors in Django helps add additional data to the context of every template that is going to be rendered. They mostly run before the template is rendered. So this helps us to add anything we want to display anywhere in our template.

How to use Context Processors

Let’s say your Django project has been created, and you have an app named “blog“. Let’s create a folder named “global_values“. Your structure should look something like this:

└── django_project/
    ├── blog/
    │   ├── global_values/
    │   │   └── blog_count.py
    │   ├── migrations
    │   ├── templates/
    │   │   └── blog
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   └── views.py
    ├── django_project/
    │   ├── __init__.py
    │   ├── asgi.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    ├── .gitignore
    ├── .sample.env
    ├── manage.py
    └── requirements.txt

In the global_values folder, we will be creating a file called blog_count.py. In this file, we are going to display the number of blogs a user has created. For those who have not created any, the count will be 0. This is to demonstrate how to handle both instances in case you encounter such scenarios.

models.py;

class Blogs(models.Model):
    user = models.ForeignKey(User,on_delete=models.ON_CASCADE)
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    
    def __str__(self) -> str:
        return f"{self.title}"

in your “blog_count.py”

from .models import Blogs

def blog_count(request):
    count = 0
    if request.user.is_authenticated:
        user = request.user
        count = Blogs.objects.filter(user = user).count()

    return {
        'blog_count': count
    }

In this code we checking if the user is logged in. if yes we check the number of blogs that user has if not we display 0.

Next we will be adding it to Django context processors. in your settings.py look for the variable “TEMPLATES”. in that add the path to this file you created. this is the format
<name-of-app-of-where-the-code-is>.<folder-inwhich-the-code-is-located>.<file-which-contain-the-code>.<function-of-the-code>.

so for this its going to be "blog.global_values.blog_count.blog_count"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [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",
"blog.global_values.blog_count.blog_count",
            ],
        },
    },
]

after adding it to your context processors you will be able to call the return variable any where in your templates. in the function we returned “blog_count” so in your template files you will call them in it.

Example

<p>{{blog_count}}</p>

This will work.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top