Django2.2 custom error interface in mind filled pit

Background problem

When Django can not find a match the request URL, or when an exception is thrown, the call to an error handling view. Error view including 400,403,404 and 500, respectively request error, denial of service, and server error page does not exist. They are located at:

handler400 —— django.conf.urls.handler400。

handler403 —— django.conf.urls.handler403。

handler404 —— django.conf.urls.handler404。

handler500 —— django.conf.urls.handler500。

How to do?

First, assume that our project named mp

First Step

Make the following changes in mp / settings.py file in the project

# DEBUG = True
#
# ALLOWED_HOSTS = []

DEBUG = False  # 开发环境下为True,此时我们改为False
ALLOWED_HOSTS = ['*']  # 或者 ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

While in this file modification TEMPLATES

'DIRS': [os.path.join(BASE_DIR, 'templates')],

It represents the static resources (404.html, 500.html, etc.) under the templates folder located in the project, if there is no need to create folders and ready html file.

Next Step

New rviews.py in mp / project in the
contents of the file are as follows:

from django.shortcuts import render

def bad_request(request, exception, template_name='400.html'):
    return render(request, template_name)


def permission_denied(request, exception, template_name='403.html'):
    return render(request, template_name)


def page_not_found(request, exception, template_name='404.html'):
    return render(request, template_name)

# 注意这里没有 exception 参数
def server_error(request, template_name='500.html'):
    return render(request, template_name)

final step

Make the following changes in mp / urls.py files in the project

from django.conf.urls import url
from . import rviews

handler400 = rviews.bad_request
handler403 = rviews.permission_denied
handler404 = rviews.page_not_found
handler500 = rviews.server_error

Then python manage.py runserver restart can
when valid 2019/11/3

Published 84 original articles · won praise 250 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ygdxt/article/details/102888382