如何自定义Django中的404页面?

5 投票
2 回答
3816 浏览
提问于 2025-04-17 19:04

我怎么在Django中自定义错误页面,以及我应该把这个页面的HTML放在哪里。

2 个回答

2

首先,你需要编辑settings.py文件,让它指向一个模板文件夹:

Django模板路径

当你把404.htm文件放进模板文件夹后,可以按照下面的步骤进行:

告诉搜索引擎当前页面是404错误页面是很重要的。你可以通过修改HTTP头来做到这一点。所以这里有一个好的方法:

在你的应用程序的urls.py文件中添加:

# Imports
from django.conf.urls.static import static
from django.conf.urls import handler404
from django.conf.urls import patterns, include, url
from yourapplication import views

##
# Handles the URLS calls
urlpatterns = patterns('',
    # url(r'^$', include('app.homepage.urls')),
)

handler404 = views.error404

在你的应用程序的views.py文件中添加:

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


##
# Handle 404 Errors
# @param request WSGIRequest list with all HTTP Request
def error404(request):

    # 1. Load models for this view
    #from idgsupply.models import My404Method

    # 2. Generate Content for this view
    template = loader.get_template('404.htm')
    context = Context({
        'message': 'All: %s' % request,
        })

    # 3. Return Template for this view + Data
    return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)

关键在于最后一行:status=404

希望这对你有帮助!

期待看到大家对这个方法的反馈。=)

11

只需要在你项目的根目录下的 templates 文件夹里创建一个 404.html 文件就可以了。

撰写回答