From 44a2c728958e7aefc79392a4136f335b743f21b8 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Tue, 20 Oct 2020 15:28:25 +1100 Subject: [PATCH] 2.3 Created a true useful View --- first_django_app.md | 8 ++++++++ src/polls/templates/polls/index.html | 9 +++++++++ src/polls/views.py | 10 +++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/polls/templates/polls/index.html diff --git a/first_django_app.md b/first_django_app.md index 6b60364..8a0976d 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -184,3 +184,11 @@ Here `path()` function is passed **route** and **view**; two additional option a > 当某人请求你网站的某一页面时——比如说, "/polls/34/" ,Django 将会载入 mysite.urls 模块,因为这在配置项 ROOT_URLCONF 中设置了。然后 Django 寻找名为 urlpatterns 变量并且按序匹配正则表达式。在找到匹配项 'polls/',它切掉了匹配的文本("polls/"),将剩余文本——"34/",发送至 'polls.urls' URLconf 做进一步处理。在这里剩余文本匹配了 "/",使得我们 Django 以如下形式调用 polls.urls.detail(): > `detail(request=, question_id=34)` + +### Create a true useful View + +每个视图必须要做的只有两件事:返回一个包含被请求页面内容的 HttpResponse 对象,或者抛出一个异常,比如 Http404 。至于你还想干些什么,随便你。 + +你的视图可以从数据库里读取记录,可以使用一个模板引擎(比如 Django 自带的,或者其他第三方的),可以生成一个 PDF 文件,可以输出一个 XML,创建一个 ZIP 文件,你可以做任何你想做的事,使用任何你想用的 Python 库。 + +`django.shortcuts.render` 可以“载入模板,填充上下文,再返回由它生成的 HttpResponse 对象“ \ No newline at end of file diff --git a/src/polls/templates/polls/index.html b/src/polls/templates/polls/index.html new file mode 100644 index 0000000..79823ba --- /dev/null +++ b/src/polls/templates/polls/index.html @@ -0,0 +1,9 @@ +{% if latest_question_list %} + +{% else %} +

No polls are available.

+{% endif %} \ No newline at end of file diff --git a/src/polls/views.py b/src/polls/views.py index c76691c..f645828 100644 --- a/src/polls/views.py +++ b/src/polls/views.py @@ -1,8 +1,16 @@ from django.http import request, HttpResponse from django.shortcuts import render +from django.template import loader + +from .models import Question def index(request): - return HttpResponse("Hello, world. You're at the polls index") + 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)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id)