From 6792a0795cb568409c67e9bb819cc5de53a8daef Mon Sep 17 00:00:00 2001 From: roger Date: Fri, 16 Sep 2022 18:24:01 +0800 Subject: [PATCH] modify detail view use new methods for return 404. --- polls/templates/detail.html | 7 ++++++- polls/views.py | 22 +++++++++++++--------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/polls/templates/detail.html b/polls/templates/detail.html index 1a9dfba..840a832 100644 --- a/polls/templates/detail.html +++ b/polls/templates/detail.html @@ -5,6 +5,11 @@ Title-{{ question }} -{{ question }} +

{{ question.question_text }}

+ \ No newline at end of file diff --git a/polls/views.py b/polls/views.py index 9d1a7ec..494b046 100644 --- a/polls/views.py +++ b/polls/views.py @@ -1,4 +1,5 @@ from django.shortcuts import render +from django.shortcuts import get_object_or_404 from django.http import HttpResponse from django.http import Http404 from .models import Question @@ -26,15 +27,18 @@ def index(request): def detail(request, question_id): # return HttpResponse(f"You're looking at question {question_id}.") - # 添加404页面展示 - try: - question = Question.objects.get(pk=question_id) - context = {'question': question} - print(context) - except Question.DoesNotExist: - raise Http404("Question does not exist") - return render(request, 'detail.html', context) - + # 添加404页面展示 方式1 + # try: + # question = Question.objects.get(pk=question_id) + # context = {'question': question} + # print(context) + # except Question.DoesNotExist: + # raise Http404("Question does not exist") + # return render(request, 'detail.html', context) + + # 添加404页面展示 方式2 + question = get_object_or_404(Question, pk=question_id) + return render(request, 'detail.html', {'question': question}) def result(request, question_id): return HttpResponse(f"You're looking at the result of question {question_id}.")