tags:

views:

132

answers:

4

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?

+5  A: 

First, read this. Then:

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
Dmitry Shevchenko
A: 

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.

Dominic Rodger
A: 

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.

Tomasz Zielinski
+2  A: 

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.

Mark Lavin