# C:\Code\mysite\elections\urls.py
#기존 코드 유지
urlpatterns = [
# ...
#url(r'^candidates/(?P<name>[가-힣]+)/$', views.candidates)
]
여러가지 방법으로 예외 처리하기
1. Basic
# C:\Code\mysite\elections\views.py
# 기존 코드 유지
def candidates(request, name):
candidate = Candidate.objects.get(name = name)
return HttpResponse(candidate.name)
2. 예외 처리로 object가 없는 경우 HttpResponseNotFound 처리하기
# C:\Code\mysite\elections\views.py
from django.http import HttpResponseNotFound #추가
# 기존 코드 유지
def candidates(request, name):
try :
candidate = Candidate.objects.get(name = name)
except:
return HttpResponseNotFound("없는 페이지 입니다.")
return HttpResponse(candidate.name)
3. 예외 처리로 url이 없는 경우와, object가 없는 경우를 함께 처리하기
# C:\Code\mysite\elections\views.py
from django.http import Http404 #추가
# 기존 코드 유지
def candidates(request, name):
try :
candidate = Candidate.objects.get(name = name)
except:
raise Http404
return HttpResponse(candidate.name)
4. 예외 처리없이 url이 없는 경우와, object가 없는 경우를 함께 처리하기
# C:\Code\mysite\elections\views.py
from django.shortcuts import get_object_or_404 #추가
# 기존 코드 유지
def candidates(request, name):
candidate = get_object_or_404(Candidate, name = name)
return HttpResponse(candidate.name)