direct_to_template and render_to_response on {{request}}



这些函数不应该完全相同吗?

def IndexView(request):
    return direct_to_template(request, template='index.html')
def IndexView2(request):
    return render_to_response('index.html',
                              {'request': request},
                              context_instance=RequestContext(request))

我不是在问两者之间的区别,而是为什么在模板上使用 {{request}} 当我使用 direct_to_template 时......我读过很多类似的问题,但我无法弄清楚。

有谁知道为什么?谢谢

原因是

direct_to_template实际上默认使用RequestContext(request)(所有通用视图也是如此),这意味着所有模板上下文处理器在模板中都可用(包括django.core.context_processors.request这使得request变量可访问)。

使用 RequestContext 时,它会扫描所有模板上下文处理器(如 settings.py 中的TEMPLATE_CONTEXT_PROCESSORS中所定义),并自动将它们添加到上下文中,以便它们在模板中可用。从文档中:

第二个区别是,它会根据您的TEMPLATE_CONTEXT_PROCESSORS设置自动使用一些变量填充上下文。

您需要

在 settings.py 中添加django.core.context_processors.request以TEMPLATE_CONTEXT_PROCESSORS。

最新更新