This article mainly introduces the http://www.php.cn/wiki/1515.html "target=" _blank ">django implementation of custom 404,500 page of the detailed method, very simple and practical, the need for small partners can refer to the following
1. Create a project
django-admin.py startproject HelloWorld
2. Enter the HelloWorld project, create the templates directory in the same level directory of manage.py, and new 404.html,500.html two files in the templates directory.
3. Modify settings.py
(1.) Debug modified to False, (2.) allowed_hosts Add the specified domain name or IP, (3.) Specify the template path ' DIRS ': [Os.path.join (Base_dir, ' templates ')],
# SECURITY Warning:don ' t run with debug turned on production! DEBUG = falseallowed_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 ', ], },},]
4. Create a new views.py
From django.http import httpresponsefrom django.shortcuts import Render_to_responsefrom django.views.decorators.csrf Import csrf_exempt@csrf_exemptdef Hello (Request): Return HttpResponse (' Hello world! ') @csrf_exemptdef Page_not_found (Request): Return Render_to_response (' 404.html ') @csrf_exemptdef Page_Error (Request): Return Render_to_response (' 500.html ')
5. Modify the urls.py, the code is as follows
From django.conf.urls import urlfrom django.contrib import adminimport helloworld.views as Viewurlpatterns = [url (r ' ^admi n/', admin.site.urls), url (r ' ^test$ ', View.hello),]handler404 = view.page_not_foundhandler500 = View.page_error
Recompile, restart Uwsgi, enter localhost/helloworld/test, display ' Hello world! ', enter other address will display 404.html content, if the error displays 500.html content.