Django自定义404页面不工作 [英] Django custom 404 page not working
问题描述
所以,在我的项目中,我想添加一个自定义的404错误页面,所以我按照我可以在网上找到的东西,但似乎没有什么对我有用。
So, in my projects I wanted to add a custom 404 error page, so I followed what I could find on the web, but nothing seemed to work for me.
这是我对我的文件的支持:
This is what I have on my files:
settings.py
settings.py
import os
# Django settings for HogwartsMail project.
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
DEBUG = False
TEMPLATE_DEBUG = DEBUG
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
urls.py
urlpatterns = patterns('',
...
)
handler404 = "HogwartsMail.views.error404"
views.py
def error404(request):
return render(request,'404.html')
每当我尝试输入一个随机的URL ,但是,而不是404错误,我得到一个服务器错误(500)。
Whenever I try to enter a random url, though, instead of getting a 404 error, I get a Server Error (500).
正如我所说,我尝试了很多不同的方式,但没有一个为我工作。
As I've said, i tried it many different ways, but none actually worked for me.
此外,我遇到的另一个问题是我加载的页面真的很慢,他们没有打开样式或图片,所以我认为,当 DEBUG = False
时,我需要一切已经在线。是否正确?
Also, another problem I am having is that the pages I have load really slowly and they don't open the styling or images, so I assume that, when DEBUG = False
, I need everything to be already online. Is that correct?
推荐答案
在项目文件夹的urls.py中添加这个帐号(可以是任何应用程序)同一个项目的应用程序:
In the urls.py of project folder add this where the accounts (it can be any app) is an app of the same project:
project / urls.py
handler404 = 'accounts.views.page_not_found'
在帐户视图中添加这个:
In accounts' view add this:
accounts / views.py
def page_not_found(request):
"""
Page not found Error 404
"""
response = render_to_response('404.html',context_instance=RequestContext(request))
response.status_code = 404
return response
不要忘记进行必要的导入。在分阶段测试时也不要忘记在settings.py中更改Debug = False。
Don't forget to make necessary imports. Also don't forget to change Debug=False in settings.py when testing in staging.
这篇关于Django自定义404页面不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!