Django-尝试使用 APPEND_SLASH 和自定义包罗万象的 404 视图
我通常会在 Django 网站中添加一个包罗万象的 404 正则表达式,作为 urls.py 中的最后一个表达式:
urlpatterns += patterns('django.views.generic.simple',
(r'^.', 'direct_to_template', {'template': 'unknown.html'}),
我通常对此性能感到满意。 known.html 模板扩展了我的基本模板,并很好地告诉查看者他们输入的 url 不存在,但该页面仍然具有我网站的所有导航和样式。
然而,在不得不反复告诉人们输入尾部斜杠之后,我觉得需要设置settings.py中的APPEND_SLASH = True参数。
文档指出:
如果 APPEND_SLASH 为 True 并且 初始 URL 不以斜杠结尾, 并且在 URLconf 中找不到它, 然后通过附加形成一个新的 URL 末尾有一个斜杠。如果这个新 URL 是 在URLconf中找到,然后Django 将请求重定向到这个新 URL。 否则,初始 URL 为 照常处理。
因此,按照这个逻辑,foo.com/bar 会被我的“404”url 表达式成功捕获,然后才能重定向到我的 foo.com/bar/ url 表达式。 *
维护友好/自定义的包罗万象的 404 页面同时还能够使用 APPEND_SLASH 或具有类似功能的内容的最佳方法是什么?*
--编辑/回答--
不知怎的,我错过了你只需要添加一个名为 404.html 的模板,并确保 DEBUG = False
谢谢DTing!
I generally add a catch-all 404 regex to my Django websites as the last expression in my urls.py:
urlpatterns += patterns('django.views.generic.simple',
(r'^.', 'direct_to_template', {'template': 'unknown.html'}),
I'm generally happy with the performance of this. The unknown.html template extends my base template and nicely tells the viewer that their entered url doesn't exist, but the page still has all the navigation and style of my website.
However, after having to repeatedly tell people to enter a trailing slash, I feel that the APPEND_SLASH = True parameter in settings.py needs to be set.
the docs state:
If APPEND_SLASH is True and the
initial URL doesn’t end with a slash,
and it is not found in the URLconf,
then a new URL is formed by appending
a slash at the end. If this new URL is
found in the URLconf, then Django
redirects the request to this new URL.
Otherwise, the initial URL is
processed as usual.
So following this logic, foo.com/bar is successfully caught by my "404" url expression before it can be redirect to my foo.com/bar/ url expression.
*
What is the best way to maintain a friendly/custom catchall 404 page while also being able to use APPEND_SLASH or something with similar functionality?*
--edit/answer--
Somehow I missed that you just need to add a template named 404.html, and also make sure DEBUG = False
Thanks DTing!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可以自定义 404.html 而不是使用“catchall”,因为您只是重定向到自定义模板。您的自定义 404.html 模板没有理由无法扩展您网站的 base.html。
http://docs.djangoproject.com/en/ dev/topics/http/views/#customizing-error-views
如果您确实想使用自定义视图,
I think you can just customize your 404.html instead of using a "catchall" since you are just redirecting to a custom template. There is no reason why your custom 404.html template can't extend your site's base.html.
http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
if you do want to use a custom view,