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
from django.shortcuts import render
def home(request):
request.user_settings = {
"show_ads": True,
}
return render(request, "home.html", {})
site_specific/context_processors.py
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
{% 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 5.2 Django 4.2 Django 3.2 HTML5
Django/Python Consulting
If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.