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")
A context processor is a Python function that takes the request object as an argument and returns a dictionary that gets added to the request context. They come in handy when you need to make something available globally to all templates.
template. Context, but Django also comes with a subclass, django. template. RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default – things like the HttpRequest object or information about the currently logged-in user.
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:
def test_view(request): return render_to_response('template.html')
The view above will not use the context processors listed in TEMPLATE_CONTEXT_PROCESSORS
. Make sure you are supplying a RequestContext
like so:
def test_view(request): return render_to_response('template.html', context_instance=RequestContext(request))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With