2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dotty
  • 40,405
  • 66
  • 150
  • 195

4 Answers4

11

First, read this. Then:

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
2

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
  • 24,664
  • 5
  • 76
  • 70
0

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
  • 97,747
  • 36
  • 197
  • 212
0

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 Zieliński
  • 16,136
  • 7
  • 59
  • 83