如何在 Django 中创建自定义 403 页面?
遵循本文档(https://docs.djangoproject .com/en/dev/topics/http/views/#customizing-error-views),我正在尝试为我的 Django 应用程序创建自定义错误 403 页面。
我在 URLConf: 中创建了一个错误处理程序:
handler403 = 'courses.views.error403'
我还创建了一个处理错误 403 的视图,称为 error403:
def error403(request):
'''
Default view for error 403: Inadequate permissions.
'''
return render_to_response('utility/mustLogin.html', {'user': request.user})
但是,该视图根本不呈现。当我故意引发错误 403 时,默认浏览器 403 页面只会出现,而不是我的模板。
我是否忘记执行某些操作?谢谢。
Following this documentation (https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views), I am trying to create a custom error 403 page for my Django application.
I have created an error handler in my URLConf:
handler403 = 'courses.views.error403'
I have also created a view that handles error 403 called error403:
def error403(request):
'''
Default view for error 403: Inadequate permissions.
'''
return render_to_response('utility/mustLogin.html', {'user': request.user})
However, this view is simply not rendering. When I instigate an error 403 on purpose, the default browser 403 page merely appears as opposed to my template.
Am I forgetting to perform some action? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
handler403
是开发版本中的新增内容。如果您使用的是旧版本 (<= 1.3),则此选项尚未实现。在旧版本中,有一些方法可以实现这一点,如此处。它涉及一个新的中间件、一个自定义异常和 HttpResponseForbidden 。但不知道它与你项目的其他部分集成得有多好......
The
handler403
is new in the development version. If you're using an older version (<= 1.3) this option is not yet implemented.There are some ways of accomplishing that in older versions, as described here. It involves a new middleware, a custom exception and the HttpResponseForbidden. Don't know how well it would integrate with the rest of your project, though...
如果返回的页面大小小于 512 字节,Google Chrome 会将其替换为通用页面。他们也对 404 响应执行相同的操作。
值得一提的是,Internet Explorer 也做了同样的事情。
如果您的响应大于 512 字节,那么一切都会好起来的。
Google Chrome will replace it with their generic one if the returned page is less than 512 bytes in size. They do the same with 404 responses as well.
For what it's worth Internet Explorer does the same thing.
If you make your response greater than 512bytes then all shall be well.