코딩이야기

Django 404 페이지 세팅 본문

BackEnd/장고(Django)

Django 404 페이지 세팅

기획자 비제이 2024. 7. 7. 18:16

 

1. setting.py에 값을 수정 

기본값으로 세팅된 DEBUG 값 TRUE를 False로 변경하고 
Allowed Hosts값을 변경

 

# settings.py

DEBUG = False

ALLOWED_HOSTS = ['*']  # 모든 호스트를 허용. 실제 배포 환경에서는 특정 도메인 또는 IP 주소를 추가하세요.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates',
            #Base_DIR / 'folder/newfolder/templates', <-처럼 templates 폴더를 계속 추가 가능
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

 

2. 404에러를 보여줄 페이지 작성 

 

<!-- templates/404.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Not Found</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html {
            height: 100%;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        .container {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            flex-direction: column;
        }
        .container h1 {
            font-size: 5rem;
            margin-bottom: 0;
        }
        .container p {
            font-size: 1.5rem;
            margin-top: 0;
        }
        .container a {
            margin-top: 20px;
            font-size: 1.2rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>404</h1>
        <div>404 페이지임을 알리는 내용을 필요에 맞게 추가  </div>
    </div>
</body>
</html>

 

 

3. projectname/urls.py에 404 에러핸들러 생성 

 

# project_name/urls.py
from django.contrib import admin
from django.urls import path, include

# 404를 나타내기 위해 아래 2줄이 추가 됨. 
from django.conf.urls import handler404
from django.shortcuts import render

urlpatterns = [
    path('admin/', admin.site.urls),
]

def your_404(request, exception):
    return render(request, '404.html', status=404)

handler404 = your_404