【问题标题】:Django1.5 : Trying to Custom 404.html page instead getting the 500Django1.5:尝试自定义 404.html 页面而不是获取 500
【发布时间】:2013-10-15 19:23:35
【问题描述】:

我正在尝试为 HTTP 404 错误创建自定义 404.html 页面。

对于这个网址127.0.0.1:8000/polls/Books/dsfdsf/,它显示Page not found (404) 默认调试页面,而DEBUG=True。 对于相同的 url,我想创建自定义 404 页面。

为此我已经通过Django Docs

我已采取以下步骤:

1)。 DEBUG=Falsesettings.py

2)。 handler404 = 'pollsite.views.custom_404'urls.py

3)。 views.py

def custom_404(request):
    return render('404.html', context_instance=RequestContext(request))

4)。我已将404.htmlfile 放在模板目录中,TEMPLATE_DIRS

现在我希望在我尝试访问 127.0.0.1:8000/polls/Books/dsfdsf 时出现自定义错误页面 404.html,对吗? 相反,我得到了TemplateDoesNotExist: 500.html

即使是显示TemplateDoesNotExist: 500.html的有效网址

为什么它不生成 HTTP 404 错误,从而调用自定义 404.html 文件?

我尝试了 question1question2 提到的解决方案 但仍然出现烦人的错误TemplateDoesNotExist: 500.html

请指出是什么问题?

编辑:错误的堆栈

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 153, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 228, in handle_uncaught_exception
    return callback(request, **param_dict)
  File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py", line 91, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/defaults.py", line 32, in server_error
    t = loader.get_template(template_name) # You need to create a 500.html template.
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 145, in get_template
    template, origin = find_template(template_name)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 138, in find_template
    raise TemplateDoesNotExist(name)
TemplateDoesNotExist: 500.html

.......................解决方案:

1) 在 settings.py 中设置ALLOWED_HOSTS = ['127.0.0.1']

2) 在 views.py return render_to_response('404.html')

【问题讨论】:

  • 听起来您的应用实际上正在引发 500 错误,但找不到 500 错误的模板。你检查过你的日志看看错误是什么吗?
  • 我已经编辑了我的帖子,因为我遇到了错误
  • 是的,错误是因为您有DEBUG=False,所以会抛出一个错误,但您的templates 文件夹中没有500 模板。您需要在此处添加500.html,就像您拥有404.html 一样。这不会解决您的问题,因为您的设置中可能存在错误导致 500

标签: django


【解决方案1】:

在settings.py中有一个设置:

 ALLOWED_HOSTS = []

如果是Debug = False,那么 Django 会查看ALLOWED_HOSTS。此设置需要包含您的 IP 地址。您还可以将其设置为:

 ALLOWED_HOSTS = ['*']

这在开发环境中可以正常工作,但不应该在生产环境中使用。这很可能是您的问题,也是 Django 在尝试加载该页面时抛出 500.html 服务器错误的原因。

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2018-07-27
    • 2019-12-27
    相关资源
    最近更新 更多