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

标签 python django

当我加载一个不存在的 url 时,页面 404 不显示,而是显示页面 500。在我的设置下面。 能否请您指导我打开 Django 以显示 404 页面?谢谢

Ubuntu 服务器 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 模板/操作*

-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 = ['*']

最佳答案

如果您收到缺少页面的 500 错误,那是因为当 Django 尝试处理该响应时发生了错误。

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

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

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

关于python - 自定义页面 404 未显示,但页面 500 正在显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47812089/

相关文章:

django - Django 中是否有类似 request.LANGUAGE_CODE 的语言环境文化?

python - 在 url 中添加命名空间会导致根本不应该出现的错误

python - 从 pandas 的字符串日期时间列中提取日期

Python-替换列表中的项目仅替换第一个实例,而不是所有实例

Django collectstatic 从 Heroku 每次推送到 S3

python - 从django直接上传到S3

python - 如何从数据库中获取所有数据并显示在表格中

python - 检查日期是否在同一组中的其他日期内

python - Pandas 不删除重复项

Python 漂亮的矩阵打印