웹개발/Django 웹서비스 개발(인프런)
28. (app2) Django 404핸들링
Storage Gonie
2019. 2. 17. 22:48
반응형
1. views.py에서 detail 메소드에 추가해봄
<기존>
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
<수정후>
def detail(request, question_id): # question_id은 url로 전달받은 값
try:
q = Question.objects.get(pk = question_id)
except Question.DoesNotExist:
raise Http404("Question %s does not exist" % question_id) #존재하지 않을 경우 404페이지를 띄움
return render(request, 'polls/detail.html', {'question' : q})
2. templates/polls 폴더에 detail.html추가
{{ question }}
3. localhost/polls/10 에 인위적으로 접속해보면 아래와 같은 404 페이지를 보여줌
4. short cut(자주 사용되어 간소화 되어있는 모듈) 중에서 get_object_or_404를 사용하여 좀더 간단하게 404 처리하는 방법
- try, except를 지우고 아래의 것을 사용하는 것임.
- get_object_or_404 => get 사용시 존재하는 객체가 없을 때 처리가능.
- get_list_or_404 => filter 사용시 존재하는 객체가 없을 때 처리가능.
- 각각에 대한 사용법은 문서를 참고하길 추천함.
- localhost/polls/10 에 인위적으로 접속해보면 아래와 같은 404 페이지를 보여줌
from django.shortcuts import get_object_or_404
def detail(request, question_id): # question_id은 url로 전달받은 값
q = get_object_or_404(Question, pk = question_id) #존재하지 않을 경우 404페이지를 띄움
return render(request, 'polls/detail.html', {'question' : q})
반응형