본문 바로가기

62 Django 커스텀 404, 500 페이지 만들기

62.1 셋팅파일 수정하기 - local.py

셋팅파일(setting.py)에서 DEBUG 모드를 False로 해줘야 합니다.
DEBUG=True 상태에서 404가 발생하면 디버그 화면을 보여주기 때문입니다.

작업 후 운영에 배포시에는 DEBUG=True로 꼭 변경해주셔야 합니다.

저는 로컬/운영 환경 셋팅파일 분리 에서
셋팅파일을 분리했기에 local.py를 수정합니다.

ALLOWED_HOSTS에 localhost가 없으면 추가합니다.

DEBUG = True
ALLOWED_HOSTS = ['localhost']

62.2 urls.py와 views.py 수정하기

404는 클래스 방식으로
500은 함수 방식으로 작업했습니다.

urls.py에서는 404와 500함수를 구현한 뷰의 위치를 설정하면 됩니다.

#config/urls.py

from myapp.common.common_views import customHandler404
handler404 = customHandler404.as_view()

handler500 = 'myapp.common.common_views.handler500'

views.py 에서는 render함수로 에러 페이지의 위치와 context를 빈값( {} )으로
넣어주시면 됩니다.

저는 404페이지에서 메뉴를 보이게 하려고
context에 menuMixin().getMenuList를 넣었습니다.

※ error handler 함수는 자신의 app의 view에 구현하시고 urls.py에서 경로만 잘 잡아주시면 됩니다.
pythonblog는 app이 2개(blog, coding)여서 공통으로 쓸 view를 만들어 구현했습니다.

#myapp/common/common_views.py
from django.shortcuts import render
from django.utils.functional import cached_property
from myapp.blog.models import PyBlog, PyBlogDetail
from myapp.coding.models import PyCoding
import logging as log

from django.views import generic

class menuMixin(object):
    @cached_property
    def getMenuList(self):
        print("getMenuList")
        return {"blog_menu":PyBlog.objects.all(),
                "coding_menu": PyCoding.objects.all()}

class customHandler404(generic.View):   
    def get(self, request, *args, **kwargs):        
        context = menuMixin().getMenuList
        return render(request, "errors/404.html",context)

def handler500(request):
    context = menuMixin().getMenuList
    response = render(request, "errors/500.html", context=context)
    response.status_code = 500
    return response

62.3 urls.py와 views.py 수정하기

templates/errors 디렉토리를 새로 만들고
404.html 과 500.html을 신규생성하였습니다.

62.4 브라우저에서 확인하기

404와 500에러가 잘 발생합니다. 좌측 메뉴도 잘 나옵니다.^__^

현재글 : 62 Django 커스텀 404, 500 페이지 만들기
Comments
Login:

Copyright © PythonBlog 2021 - 2022 All rights reserved
Mail : PYTHONBLOG