Hekje
Hekje

Reputation: 451

How can I pass variables to a view using a context processor?

I am using a context processor to pass several variables to all my templates. However, I would also like use these variables in the actual views that render the respective templates. Should I add them to the session object of the request object or to the request object itself (if at all possible)?

Upvotes: 5

Views: 2586

Answers (2)

Gareth Rees
Gareth Rees

Reputation: 65874

Use RequestContext:

def my_view(request):
    c = RequestContext(request)
    # c['key'] gets the value for 'key' from your context processor.
    return render_to_response('template.html', {}, context_instance = c)

Upvotes: 5

mgibsonbr
mgibsonbr

Reputation: 22007

Can't you just get a reference to the context processor and call it in your views? From what I read in the docs, there's nothing special about a context processor:

A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed-to by your TEMPLATE_CONTEXT_PROCESSORS setting.

You could have each view access them in the beginning, passing it the request parameter, or maybe create a decorator that would "inject" it in your views for you (whatever's easier in your case).

Upvotes: 0

Related Questions