自定义 404 Django 模板

rev*_*evy 3 python django

我正在尝试在我的应用程序中自定义 404 错误页面。在搜索了许多可能的解决方案后,我创建了一个 404.html 模板,添加了一个应该处理 HTTP 错误 404 的方法并编辑了我的 urls.py。

但我想我做错了什么。我的日志出现无效的语法错误,我无法解决。

我的意见.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
Run Code Online (Sandbox Code Playgroud)

和语法错误:

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
Run Code Online (Sandbox Code Playgroud)

有谁知道发生了什么?谢谢。

更新: 在@Alasdair 建议之后,我进行了一些更改和修复。错误已停止。

现在,我的 urls.py 是这样的:

handler404 = 'views.page_not_found'

urlpatterns = [
    url(r'^$', views.home),]    
Run Code Online (Sandbox Code Playgroud)

但是在访问不存在的页面时,我仍然没有得到我的自定义 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',
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

我的项目树:

??? 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
Run Code Online (Sandbox Code Playgroud)

rev*_*evy 7

几个月后,我重新审视了这个问题并确定了一个解决方案。这是答案:

a) 我page_not_foundviews.py 中删除了方法。没有必要添加它。Django 自动获取并呈现 404.html 模板。

b) 再一次,不需要编辑 urls.py。所以我删除了这一行:

handler404 = 'views.page_not_found'
Run Code Online (Sandbox Code Playgroud)

c) 另外,有必要编辑settings.py,设置DEBUGFALSE.

DEBUG = False
Run Code Online (Sandbox Code Playgroud)

我删除了以下行:

TEMPLATE_DIRS = (os.path.join(BASE_DIR , 'portal/templates'),)
Run Code Online (Sandbox Code Playgroud)

d) 最后,我在我的portal/templates目录中创建了一个 404.html 模板。值得注意的是,自定义模板仅在放置在此目录中时才会呈现。