python 执行自定义 Django 404 页面的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1167434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:38:03  来源:igfitidea点击:

Executing code for a custom Django 404 page

pythondjango

提问by Chris Lieb

I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.

我正准备部署我的第一个 Django 应用程序,但遇到了一些障碍。我的基本模板依赖于我传入会话对象,以便它可以读出当前登录的用户名。当我控制调用模板的代码时,这不是问题。

However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?

但是,作为准备部署此应用程序的一部分,我需要创建一个 404.html 页面。我扩展了我的基本模板,就像我对其他页面所做的一样,但我没有看到传递会话对象以便我可以使用它的方法。有没有办法让 Django 调用自定义方法来呈现您的 404,而不仅仅是为您呈现 404.html?

回答by AlbertoPL

You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:

您需要覆盖 404 错误的默认视图处理程序。以下是有关如何创建自己的自定义 404 视图函数的文档:

http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views

http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views

回答by Alexander Ljungberg

Define your own 404 handler. See Django URLs, specifically the part about handler404.

定义您自己的 404 处理程序。请参阅Django URL,特别是有关handler404的部分。