为什么Django在渲染模板时需要一个请求对象?
return render(request, 'polls/index.html', context)
答案 0 :(得分:3)
将给定模板与给定的上下文字典组合并返回 带有渲染文本的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)