我試圖在我的應用程序中自定義404錯誤頁面。搜索了很多可能的解決方案之後,我創建了一個404.html模板,添加了一個應該處理HTTP錯誤404並編輯我的urls.py的方法。自定義404 django模板
但我想我正在做一些非常錯誤的事情。我的日誌顯示無效的語法錯誤,我無法解決它。
我views.py:
# HTTP Error 400
def page_not_found(request):
response = render_to_response('404.html',context_instance=RequestContext(request))
response.status_code = 404
return response
而且語法錯誤:
Traceback (most recent call last):
File "/.../myenv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 393, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
...
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/home/dcaled/work/portal-interface/portal/urls.py", line 12
handler404 = 'views.handler404'
^
SyntaxError: invalid syntax
有沒有人有什麼事情的想法? 謝謝。
更新: @Alasdair建議後,我做了一些修改和修復。錯誤已經停止。
現在,我的urls.py是這樣的:
handler404 = 'views.page_not_found'
urlpatterns = [
url(r'^$', views.home),]
但我還是訪問一個不存在的頁面時,沒有得到我的自定義404.html。 相反,默認加載頁面時,此消息:
「未找到
的請求URL/URL/404沒有此服務器上找不到。」
而且,我的settings.py:
DEBUG = False
ALLOWED_HOSTS = ['*']
TEMPLATE_DIRS = (os.path.join(BASE_DIR , 'portal/templates'),)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
我的項目樹:
├── fb_dev
│ ├── __init__.py
│ ├── __pycache__
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
│
└── portal
├── admin.py
├── forms.py
├── json
├── migrations
├── models.py
├── static
├── templates
│ ├── 404.html
│ └── portal
│ ├── base.html
│ ├── home.html
├── templatetags
├── urls.py
└── views.py
您正在使用哪個版本的Django?你的'404.html'模板在哪裏? – Alasdair
我的版本是1.8.5。我用模板位置更新了問題。 – revy
你有'TEMPLATES'設置嗎?你的代碼的其他部分是否成功地在'portal/templates'中找到模板?它可能是你的[瀏覽器](http://stackoverflow.com/questions/2642340/django-404-page-not-showing-up)或你的服務器(例如Apache)劫持404頁面。 – Alasdair