Reputation: 41483
I'm finding myself always passing a 'user' variable to every call to render_to_response
A lot of my renders looks like this
return render_to_response('some/template', {'my':context,'user':user})
Is there a way to automatically send this 'user' variable without manually adding it to the context each time a method is called?
Upvotes: 2
Views: 6116
Reputation: 25164
Yes you can do this with Context Processors: http://docs.djangoproject.com/en/dev/ref/templates/api/#id1
In fact if you include DJANGO.CORE.CONTEXT_PROCESSORS.AUTH in your context processors then the user is added to every request object. http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-auth
You will need to use context_instance=RequestContext(request)
as others have mentioned to use the Context Processors.
Upvotes: 2
Reputation: 16367
Dimitry is right, but you can further simplify this by using direct_to_template generic view as regular function. Source code for it is here.
There is also nice add-on, django-annoying
, that provides render_to decorator doing similar thing but without the need for explicit template rendering.
Upvotes: 0
Reputation: 99811
You might want to look at render_to
, which is part of django-annoying - which allows you to do things like this:
@render_to('template.html')
def foo(request):
bar = Bar.object.all()
return {'bar': bar}
# equals to
def foo(request):
bar = Bar.object.all()
return render_to_response('template.html',
{'bar': bar},
context_instance=RequestContext(request))
You could write a similar decorator (e.g. render_with_user_to
) that wraps that up with you.
Upvotes: 0
Reputation: 32424
First, read this. Then:
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
Upvotes: 10