Django Context Processors Extending your templates

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Context processor to determine the template based on group membership(or any query/logic). This allows our public/regular users to get one template and our special group to get a different one.

myapp/context_processors.py

def template_selection(request):
    site_template = 'template_public.html'
    if request.user.is_authenticated():
        if request.user.groups.filter(name="some_group_name").exists():
            site_template = 'template_new.html'

    return {
        'site_template': site_template,
    }

Add the context processor to your settings.

In your templates, use the variable defined in the context processor.

{% extends site_template %}


Got any Django Question?