This article mainly introduces DjangoThe details of implementing custom 404, 500 pages The method is very simple and practical. Friends in need can refer to it
1. Create a project
django-admin.py startproject HelloWorld
2. Enter the HelloWorld project, create the templates directory at the same level as manage.py, and create two files, 404.html and 500.html, in the templates directory
3. Modify settings.py##.
# (1.) Modify DEBUG to False, (2.) Add the specified domain name or IP to ALLOWED_HOSTS, (3.) Specify the template path 'DIRS': [os.path.join(BASE_DIR,'templates')],# SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost','www.example.com', '127.0.0.1'] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ]
from django.http import HttpResponse from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt @csrf_exempt def hello(request): return HttpResponse('Hello World!') @csrf_exempt def page_not_found(request): return render_to_response('404.html') @csrf_exempt def page_error(request): return render_to_response('500.html')
from django.conf.urls import url from django.contrib import admin import HelloWorld.views as view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test$', view.hello), ] handler404 = view.page_not_found handler500 = view.page_error
The above is the detailed content of How to use Django to implement customized 404, 500 pages. For more information, please follow other related articles on the PHP Chinese website!