Sevenearths Sevenearths - 1 year ago 71
Python Question

Having a global variable available to your templates in Django

I would like to have a common variable available to all my templates. I've been working on this all morning and the only way I can find to do it is to have middleware like this:

class GetNameMiddleware(object):

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)
return response

def process_template_response(self, request, response):
response.context_data['name'] = 'dave'
return response

and have a view like this:

from django.template.response import TemplateResponse
from django.shortcuts import render

def home(request):
return TemplateResponse(request, 'home.html', {})

and then I can access it in the template

Hello {{ name }}

It just seems a bit ugly that I can't use
any more (I know I can do
from django.template.response import TemplateResponse as render
but that's not really a solution)

(Django 1.10, python 3.5.2)

Answer Source

Django has a standard way for implementing this, which is context processors. This article provides an example implementation

Actually a context processor is just a function that accepts a request object and returns a dict with the data you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download