diff --git a/first_django_app.md b/first_django_app.md index 8a0976d..ca94c7a 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -191,4 +191,10 @@ Here `path()` function is passed **route** and **view**; two additional option a 你的视图可以从数据库里读取记录,可以使用一个模板引擎(比如 Django 自带的,或者其他第三方的),可以生成一个 PDF 文件,可以输出一个 XML,创建一个 ZIP 文件,你可以做任何你想做的事,使用任何你想用的 Python 库。 -`django.shortcuts.render` 可以“载入模板,填充上下文,再返回由它生成的 HttpResponse 对象“ \ No newline at end of file +`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. \ No newline at end of file diff --git a/src/polls/views.py b/src/polls/views.py index f645828..5cbe997 100644 --- a/src/polls/views.py +++ b/src/polls/views.py @@ -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)