如何在Django中显示自定义的404

如何在Django中显示自定义的404

本文介绍了如何在Django中显示自定义的404.html页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在最终用户输入错误的URL时显示自定义的404错误页面,我已经尝试过,但我只得到Django默认的404页面。我使用Python(2.7.5),Django(1.5.4)



我的代码



urls.py

来自django.conf.urls导入模式的包含来自mysite导入视图的url 

handler404 = views.error404

urlpatterns = patterns('',
url(r'^ $','mysite.views.home',name ='home'),

views.py

  from django.http import HttpResponse 
from django $ s

返回HttpResponse(欢迎来到我的世界)

def error404(request):
template = loader.get_template('404.html')
context = Context({'message':'All:%s'%request,})
返回HttpResponse(content = template.render(context),content_type ='text / html; charset = utf-8',status = 404)

404.html页面在templates目录下。如何处理这个..?

解决方案

自定义URL处理程序不适用于 DEBUG =真。设置 DEBUG = False ,它将工作。 (您还需要设置 ALLOWED_HOSTS = ['127.0.0.1']


I want to display custom 404 error page when end user enters wrong url,I have tried but i am getting only Django default 404 page.I am using Python(2.7.5),Django(1.5.4)

My Code

urls.py

from django.conf.urls import patterns, include, url
from mysite import views
handler404 = views.error404

urlpatterns = patterns('',
url(r'^$', 'mysite.views.home', name='home'),
)

views.py

from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, loader

def home(request):
     return HttpResponse("welcome to my world")

def error404(request):
     template = loader.get_template('404.html')
     context = Context({'message': 'All: %s' % request,})
     return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)

I have placed my 404.html page in templates directory.How to handle this..?

解决方案

Custom URL handlers don't work with DEBUG=True. Set DEBUG=False and it will work. (You'll also need to set ALLOWED_HOSTS=['127.0.0.1'])

这篇关于如何在Django中显示自定义的404.html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:34