为什么Django在渲染模板时需要一个请求对象?

时间:2016-06-01 07:41:02

标签: django django-templates

为什么Django在渲染模板时需要一个请求对象?

 return render(request, 'polls/index.html', context)

3 个答案:

答案 0 :(得分:3)

根据the docs about render

  

将给定模板与给定的上下文字典组合并返回   带有渲染文本的HttpResponse对象。

因此,它意味着在视图中使用,您有request个对象,需要返回HttpResponse。一个典型的用例是从请求构建上下文。

如果您只需要渲染模板,则可以使用快捷键功能render_to_string

from django.template.loader import render_to_string

render_to_string('your_template.html', {'some_key':'some_value'})

或者手动完成:

from django.template import Context, Template 

Template('your_template.html').render(Context({'some_key':'some_value'})

答案 1 :(得分:2)

如果要使用get_field,则使用request参数,这通常是您希望使用template context processors时的情况。如果需要,您可以将RequestContext作为None参数传递,您将在模板中获得常规request对象。

答案 2 :(得分:1)

我认为这是b / c,render()快捷方式使用RequestContext

您也可以直接使用get_template并使用正常的render

致电Context