首页 文章

Django1.5:尝试自定义404.html页面而不是500

提问于
浏览
0

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

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

为此,我已经完成了Django Docs .

我采取了以下步骤:

1) . DEBUG=False in settings.py

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

3) . views.py

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

4) . 我已将 404.html 文件放在模板目录中, 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

请指出问题是什么?

EDIT :stacktarce错误

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

......................... Solution:

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

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

1 回答

  • 0

    在settings.py中有一个设置:

    ALLOWED_HOSTS = []
    

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

    ALLOWED_HOSTS = ['*']
    

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

相关问题