2

我发现自己总是将“用户”变量传递给每次调用render_to_response

我的很多渲染看起来像这样

return render_to_response('some/template', {'my':context,'user':user})

有没有办法在每次调用方法时自动发送这个“用户”变量而无需手动将其添加到上下文中?

4

4 回答 4

11

首先,阅读这个。然后:

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
于 2010-02-11T12:58:43.807 回答
2

是的,您可以使用上下文处理器执行此操作:http: //docs.djangoproject.com/en/dev/ref/templates/api/#id1

事实上,如果您在上下文处理器中包含 DJANGO.CORE.CONTEXT_PROCESSORS.AUTH,那么用户就会被添加到每个请求对象中。 http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-auth

您将需要context_instance=RequestContext(request)像其他人提到的那样使用上下文处理器。

于 2010-02-11T13:17:01.920 回答
0

您可能想查看render_todjango-annoying 的一部分,它允许您执行以下操作:

@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))

您可以编写一个类似的装饰器(例如render_with_user_to)将其包装起来。

于 2010-02-11T13:04:23.690 回答
0

Dimitry 是对的,但是您可以通过使用direct_to_template通用视图作为常规函数来进一步简化这一点。它的源代码在这里

还有一个不错的附加组件django-annoying,它提供render_to装饰器做类似的事情,但不需要显式模板渲染。

于 2010-02-11T13:14:01.607 回答