自定义页面404未显示,但页面500正在显示

当我加载不存在的URL时,页面404不显示,而是显示页面500 . 在我的设置下面 . Could you please 指导我将Django打开显示404页面?谢谢

Ubuntu Server 16.04; Python 3.5.2; Django 2.0

cat contatoproj/urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.conf.urls import include
from django.conf.urls import handler404, handler500
from contatoapp import views
from contatoapp import views as myapp_views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name='index'),
    url(r'^contato', views.contato, name='contato'),
]

handler404 = myapp_views.error_404
handler500 = myapp_views.error_500

cat contatoapp/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib import messages
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from contatoapp.forms import ContatoForm

def error_404(request):
    data = {}
    return render(request, 'ops404.html', data)

def error_500(request):
    data = {}
    return render(request, 'ops500.html', data)

$ ls -la templates / ops *

-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:31 templates/ops404.html
-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:29 templates/ops500.html

cat contatoproj/settings.py

DEBUG = False
ALLOWED_HOSTS = ['*']

回答(2)

3 years ago

如果你因缺少页面而得到500错误,那就是因为当Django试图处理该响应时发生错误 .

从查看代码,这可能是因为错误地定义了404错误处理程序 - 它需要接受缺少的第二个 exception 参数 . 将其更改为:

def error_404(request, exception):
    data = {}
    return render(request, 'ops404.html', data)

另请注意,您应该返回HttpResponseNotFound,否则客户端将不会收到HTTP 404响应 .

3 years ago

您在处理404时遇到错误 . 这意味着您将获得500 .

当您需要使用 handler404/500 为它们显式定义处理程序视图时 .

相反,您应该在模板目录中定义 404.html500.html . Django将使用这些而不是默认模板,您不需要正确地重新实现404和500视图 .