diff --git a/first_django_app.md b/first_django_app.md index ca94c7a..1864f5e 100644 --- a/first_django_app.md +++ b/first_django_app.md @@ -180,12 +180,12 @@ Here `path()` function is passed **route** and **view**; two additional option a * Django use 'URLconfs' to map btw URL and Views. Details of[pURL manager](https://docs.djangoproject.com/zh-hans/3.1/topics/http/urls/) * URL's general form: `/newsarchive///` -### Create more Views +### 3.1 Create more Views > 当某人请求你网站的某一页面时——比如说, "/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 +### 3.2 Create a true useful View 每个视图必须要做的只有两件事:返回一个包含被请求页面内容的 HttpResponse 对象,或者抛出一个异常,比如 Http404 。至于你还想干些什么,随便你。 @@ -193,8 +193,13 @@ Here `path()` function is passed **route** and **view**; two additional option a `django.shortcuts.render` 可以“载入模板,填充上下文,再返回由它生成的 HttpResponse 对象“ -### shortcut function: `render()` +#### 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 +> 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. + +### 3.3 Throw 404 error + +如果指定问题 ID 所对应的问题不存在,这个视图就会抛出一个 Http404 异常。 + diff --git a/src/polls/templates/polls/detail.html b/src/polls/templates/polls/detail.html new file mode 100644 index 0000000..3bbdd2a --- /dev/null +++ b/src/polls/templates/polls/detail.html @@ -0,0 +1 @@ +{{ question }} \ No newline at end of file diff --git a/src/polls/views.py b/src/polls/views.py index 5cbe997..5d70d19 100644 --- a/src/polls/views.py +++ b/src/polls/views.py @@ -11,7 +11,11 @@ def index(request): return render(request, 'polls/index.html', context) def detail(request, question_id): - return HttpResponse("You're looking at question %s." % question_id) + try: + question = Question.objects.get(pk=question_id) + except Question.DoesNotExist: + raise Http404("Question does not exist") + return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s."