如何在 Django 中显示自定义 404.html 页面 [英] How to display custom 404.html page in Django

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

问题描述

我想在最终用户输入错误网址时显示自定义 404 错误页面.我试过了,但我只得到了 Django 默认的 404 页面.我使用的是 Python 2.7.5 和 Django 1.5.4.

I want to display a custom 404 error page when an end user enters a wrong url. I have tried but I am only getting the Django default 404 page. I am using Python 2.7.5 and Django 1.5.4.

我的代码:

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)

我已将我的 404.html 页面放在模板目录中.如何处理?

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

推荐答案

自定义 URL 处理程序不适用于 DEBUG=True.设置 DEBUG=False 就可以了.(您还需要设置 ALLOWED_HOSTS=['127.0.0.1'])

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 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆