About Modifying Template Context Variables Globally

Template context variables can't be modified globally in context processors or middlewares, but instead you can modify the attributes of the HttpRequest object in context processors, for example:

site_specific/views.py

1
2
3
4
5
6
7
from django.shortcuts import render

def home(request):
    request.user_settings = {
        "show_ads": True,
    }
    return render(request, "home.html", {})

site_specific/context_processors.py

1
2
3
4
5
6
7
def modify_user_settings(request):
    if not hasattr(request, "user_settings"):
        request.user_settings = {}
    request.user_settings["expand_sidebar"] = (
        request.session.get("expand_sidebar")
    )
    return {}

templates/home.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{% extends "base.html" %}

{% block content %}
    <nav {% if request.user_settings.expand_sidebar %}
        class="open"
    >...</nav>
    {% if request.user_settings.show_ads %}
        {% include "ads/ad.html" %}
    {% endif %}
{% endblock %}

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 HTML5