views:

47

answers:

1

Hay, I have come to a point where i need to pass certain variables to all 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'.

This looks like

def say_hello(request):
        return {
            'say_hello':"Hello",
        }

Am i right to assume i can now do this within my views

{{ say_hello }}

because it doesn't return anything.

My view look like

from django.shortcuts import *

def test(request):
        return render_to_response("test.html")
+3  A: 

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))
TM
The 'context_instance' is what was missing! Thanks TM
dotty
Follow up, how come i need this context_instance? How come i don't need this if i use django's auth system?
dotty
Django's built in views handle this for you (they use a `RequestContext`). Think about the context processor that you made. It takes `request` as an argument. That means you need to somehow give the current request to the rendering logic. `RequestContext` basically just handles the simple logic of looping through all the context processors and passing the current request to them, then updating the page context with the results.
TM
Could i modify my view to request the context?
dotty
@dotty Not sure what you mean by "request the context".
TM