DEV Community

Cover image for Custom Context Processors in Django.
Gilbish
Gilbish

Posted on β€’ Edited on

15 4

Custom Context Processors in Django.

What's the need of context processors? πŸ˜‡

Sometimes you want to make a variable accessible to all templates in a project.

Two ways to access a variable in all templates:

1. Hard Way: By providing the same variable in the context of each view. 😐

2. Easy Way: creating a custom context processor πŸ˜‹

Personally I don't like the hard way, cause then I have to write the same code in each view.

Let's see how it can be done the easy way.

Consider a situation where you need to display a banner image in each page of your website, the banner image will be fetched from the database.

Model for the banner image:

#models.py
class BannerImage(models.Model):
    image = models.ImageField(upload_to='img')
Enter fullscreen mode Exit fullscreen mode

We can access the banner image in each page using the context processor.

Write Custom Context Processor πŸ™Œ

Create a new file context_processors.py inside your app and write a function which will return a dictionary containing the variable we want to use.

#context_processors.py

from .models import BannerImage

def access_banner_image(request):
    """
      The context processor must return a dictionary.
    """
    bannerImage = BannerImage.objects.latest('-id') #query the latest banner image
    return {'bannerImage':bannerImage} 

Enter fullscreen mode Exit fullscreen mode

access_banner_image is the custom context processors we just created, add it to the context_processors option in the TEMPLATES setting so that the variable bannerImage is accessible in all templates.

#settings.py
TEMPLATES = [
    {
        #under OPTIONS key
        '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',
               #context processor written by us.
           'appname.context_processors.access_banner_image'
],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode

We are done πŸŽ‰ , the bannerImage variable will be now accessible in all the templates.

Example:

<img src="{{bannerImage.image.url}}" alt=''/>
Enter fullscreen mode Exit fullscreen mode

Thanks For Reading my post.πŸ™‚

Self-Promotion πŸ˜€

IllustrationHunt One place to look for sites offering free illustrations.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (3)

Collapse
 
alimp5 profile image
alimp5 β€’

Tnx a lot :X

Collapse
 
codephilanthropist profile image
Rian β€’ β€’ Edited

Thanks for this. I've read a lot of articles on how to extend my search form to all templates including the base.html. This one works best.

Collapse
 
gilbishkosma profile image
Gilbish β€’

Thanks Rian, it really made my day πŸ˜„

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay