2.3 Shortcut function render()
parent
44a2c72895
commit
9af5aeda4c
|
@ -192,3 +192,9 @@ Here `path()` function is passed **route** and **view**; two additional option a
|
|||
你的视图可以从数据库里读取记录,可以使用一个模板引擎(比如 Django 自带的,或者其他第三方的),可以生成一个 PDF 文件,可以输出一个 XML,创建一个 ZIP 文件,你可以做任何你想做的事,使用任何你想用的 Python 库。
|
||||
|
||||
`django.shortcuts.render` 可以“载入模板,填充上下文,再返回由它生成的 HttpResponse 对象“
|
||||
|
||||
### shortcut function: `render()`
|
||||
|
||||
「载入模板,填充上下文,再返回由它生成的 HttpResponse 对象」是一个非常常用的操作流程。于是 Django 提供了一个快捷函数 render
|
||||
|
||||
> The render() function takes the request object as its first argument, a template name as its second argument and a dictionary as its optional third argument. It returns an HttpResponse object of the given template rendered with the given context.
|
|
@ -7,10 +7,8 @@ from .models import Question
|
|||
def index(request):
|
||||
latest_question_list = Question.objects.order_by('-pub_date')[:5]
|
||||
template = loader.get_template('polls/index.html')
|
||||
context = {
|
||||
'latest_question_list': latest_question_list,
|
||||
}
|
||||
return HttpResponse(template.render(context, request))
|
||||
context = {'latest_question_list': latest_question_list}
|
||||
return render(request, 'polls/index.html', context)
|
||||
|
||||
def detail(request, question_id):
|
||||
return HttpResponse("You're looking at question %s." % question_id)
|
||||
|
|
Loading…
Reference in New Issue