Django 에러 페이지 처리

Ethan·2023년 12월 28일
0

django

목록 보기
17/28

이전 포스팅에서 주소/pokemon-book/ 다음 url을 pikachucharmander로 입력하여 접근하는 것과 둘다 아닌 경우에 접근하는 경우 아래와 같이 views.py 를 정의 했다. 여기서 else 문으로 정의한 즉, 둘다 아닌 경우의도하지 않은 접근이라 한다. 이전 포스팅의 경우 의도하지 않은 접근등록되지 않은 도감으로 응답했지만, 본 포스팅에서는 의도하지 않은 접근에러페이지로 응답하는 방법을 설명한다.

def pokemon_list(request):
	return render(request, 'pokemon-book/pokemon-list.html')

def pokemon_detail(request, pokemon_name):  
	context = dict()
	if pokemon_name == "pikachu":
    	context["name"] = "피카추"
		context["description"] = "피카추는 전기속성 포켓몬이다"
        context["level"] = 3
        context["img_path"] = "pokemon-book/images/pikachu.jpg"  
    elif pokemon_name == "charmander":
    	context["name"] = "파이리"
		context["description"] = "파이리는 불속성 포켓몬이다"
        context["level"] = 5
        context["img_path"] = "pokemon-book/images/charmander.jpg"  
    else:  📌의도하지 않은 접근
    	context["name"] = "미등록"
        context["description"] = "등록되지 않은 포켓몬이다"
        context["level"] = "알 수 없음"
        context["img_path"] = "pokemon-book/images/noimage.jpg"  
	return render(request, 'pokemon-book/pokemon-detail.html', context=context)

http404에러 모듈 불러오기

장고에서 제공하는 404에러 모듈을 불러온다.

from django.http import Http404  📌404에러 모듈 불러오기

def pokemon_list(request):
	return render(request, 'pokemon-book/pokemon-list.html')

def pokemon_detail(request, pokemon_name):  
	context = dict()
	if pokemon_name == "pikachu":
    	context["name"] = "피카추"
		context["description"] = "피카추는 전기속성 포켓몬이다"
        context["level"] = 3
        context["img_path"] = "pokemon-book/images/pikachu.jpg"  
    elif pokemon_name == "charmander":
    	context["name"] = "파이리"
		context["description"] = "파이리는 불속성 포켓몬이다"
        context["level"] = 5
        context["img_path"] = "pokemon-book/images/charmander.jpg"  
    else:
    	context["name"] = "미등록"
        context["description"] = "등록되지 않은 포켓몬이다"
        context["level"] = "알 수 없음"
        context["img_path"] = "pokemon-book/images/noimage.jpg"  
	return render(request, 'pokemon-book/pokemon-detail.html', context=context)

else문 수정

else문을 수정해 의도하지 않은 접근 시 호출할 메세지를 작성한다.

from django.http import Http404 

def pokemon_list(request):
	return render(request, 'pokemon-book/pokemon-list.html')

def pokemon_detail(request, pokemon_name):  
	context = dict()
	if pokemon_name == "pikachu":
    	context["name"] = "피카추"
		context["description"] = "피카추는 전기속성 포켓몬이다"
        context["level"] = 3
        context["img_path"] = "pokemon-book/images/pikachu.jpg"  
    elif pokemon_name == "charmander":
    	context["name"] = "파이리"
		context["description"] = "파이리는 불속성 포켓몬이다"
        context["level"] = 5
        context["img_path"] = "pokemon-book/images/charmander.jpg"  
    else:  📌변경된 조건문
		raise Http404("등록되지 않은 포켓몬이다.")
	return render(request, 'pokemon-book/pokemon-detail.html', context=context)

여기서 raise는 파이썬에서 지정한 에러를 강제로 발생시키는 문법이다.

profile
글로 쓰면 머리 속에 정리가 되...나?

0개의 댓글

관련 채용 정보