[英]How to specify a custom 404 view for Django using Class Based Views?
Using Django, you can override the default 404 page by doing this in the root urls.py
:使用 Django,您可以通过在根
urls.py
执行此操作来覆盖默认的 404 页面:
handler404 = 'path.to.views.custom404'
How to do this when using Class based views?使用基于类的视图时如何执行此操作? I can't figure it out and the documentation doesn't seem to say anything.
我想不通,文档似乎什么也没说。
I've tried:我试过了:
handler404 = 'path.to.view.Custom404.as_view'
Never mind, I forgot to try this:没关系,我忘了尝试这个:
from path.to.view import Custom404
handler404 = Custom404.as_view()
Seems so simple now, it probably doesn't merit a question on StackOverflow.现在看起来很简单,它可能不值得在 StackOverflow 上提问。
Managed to make it work by having the following code in my custom 404 CBV (found it on other StackOverflow post: Django handler500 as a Class Based View )通过在我的自定义 404 CBV 中包含以下代码(在其他 StackOverflow 帖子中找到它: Django handler500 as a Class Based View ) 设法使其工作
from django.views.generic import TemplateView
class NotFoundView(TemplateView):
template_name = "errors/404.html"
@classmethod
def get_rendered_view(cls):
as_view_fn = cls.as_view()
def view_fn(request):
response = as_view_fn(request)
# this is what was missing before
response.render()
return response
return view_fn
In my root URLConf file I have the following:在我的根 URLConf 文件中,我有以下内容:
from apps.errors.views.notfound import NotFoundView
handler404 = NotFoundView.get_rendered_view()
In your main urls.py
you can just add from app_name.views import Custom404
and then set handler404 = Custom404.as_view()
.在您的主
urls.py
您只需添加from app_name.views import Custom404
然后设置handler404 = Custom404.as_view()
。 It should work它应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.