Django2.1中对于请求的数据不存在的404处理

解决办法有两个,异常处理和django自带的处理函数

抛出404错误

1
2
3
4
5
6
7
8
9
10
11
from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, 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})

一个快捷函数: get_object_or_404()

1
2
3
4
5
6
7
from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})