Home > Backend Development > Python Tutorial > How to use Django to implement customized 404, 500 pages

How to use Django to implement customized 404, 500 pages

高洛峰
Release: 2017-03-28 09:32:29
Original
2503 people have browsed it

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',
   ],
  },
 },
]
Copy after login
4. Create a new views.py

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')
Copy after login
5. Modify urls.py, the code is as follows

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
Copy after login
Recompile, restart uwsgi, enter localhost/HelloWorld/test, 'Hello World!' is displayed. If you enter other addresses, 404.html content will be displayed. If an error occurs, 500.html content will be displayed.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template