5

我如何在 Django 中自定义错误页面,以及我在哪里放置该页面的 html。

4

2 回答 2

11

404.html只需在项目的根目录中创建一个文件templates

于 2013-03-14T10:21:26.597 回答
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

希望它有所帮助!

我期待看到社区对这种方法的投入。=)

于 2013-04-26T14:20:12.577 回答