I have come to a point where I need to pass certain variables to all of my views (mostly custom authentication type variables).
I was told writing my own context processor was the best way to do this, but I am having some issues.
My settings file looks like this
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
"sandbox.context_processors.say_hello",
)
As you can see, I have a module called 'context_processors' and a function within that called 'say_hello'.
Which looks like
def say_hello(request):
return {
'say_hello':"Hello",
}
Am I right to assume I can now do the following within my views?
{{ say_hello }}
Right now, this renders to nothing in my template.
My view looks like
from django.shortcuts import render_to_response
def test(request):
return render_to_response("test.html")
The context processor you have written should work. The problem is in your view.
Are you positive that your view is being rendered with
RequestContext
?For example:
The view above will not use the context processors listed in
TEMPLATE_CONTEXT_PROCESSORS
. Make sure you are supplying aRequestContext
like so:According to the django docs you can use
render
as a shortcut instead of render_to_response with the context_instance argument:If you’re using Django’s
render_to_response()
shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not aRequestContext
). To use aRequestContext
in your template rendering, use therender()
shortcut which is the same as a call torender_to_response()
with acontext_instance
argument that forces the use of aRequestContext
.Since Django 1.8 you register your custom context processors like this:
assuming your context processor is in app
www
incontext_processors.py