Django shortcut functionsDjango快捷功能
软件包django.shortcuts
收集了“跨越”多个级别的MVC的帮助函数和类。 换句话说,为方便起见,这些功能/类引入了可控制的耦合。
render()
render(request,template_name,context = None,content_type = None,status = None,using = None)[source]
将给定的模板与给定的上下文字典组合,并使用该呈现的文本返回一个HttpResponse
对象。
Django不提供返回TemplateResponse
的快捷方式,因为TemplateResponse
的构造函数提供与render()
相同的方便性。
Required arguments
request
用于生成此响应的请求对象。
template_name
要使用的模板的全名或模板名称的序列。 如果给出序列,将使用存在的第一个模板。
Optional arguments
context
要添加到模板上下文的值的字典。 默认情况下,这是一个空字典。 如果字典中的值可调用,则视图将在渲染模板之前调用它。
content_type
用于生成的文档的MIME类型。 默认为DEFAULT_CONTENT_TYPE设置的值。
status
响应的状态代码。 默认为200。
using
用于加载模板的模板引擎的NAME。
Example
以下示例使用MIME
类型application / xhtml + xml
呈现模板myapp / index.html
:
from django.shortcuts import render
def my_view(request):
# View code here...
return render(request, 'myapp/index.html', {
'foo': 'bar',
}, content_type='application/xhtml+xml')
此示例相当于:
from django.http import HttpResponse
from django.template import loader
def my_view(request):
# View code here...
t = loader.get_template('myapp/index.html')
c = {'foo': 'bar'}
return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')