簡體   English   中英

如何使用基於類的視圖為 Django 指定自定義 404 視圖?

[英]How to specify a custom 404 view for Django using Class Based Views?

使用 Django,您可以通過在根urls.py執行此操作來覆蓋默認的 404 頁面:

handler404 = 'path.to.views.custom404'

使用基於類的視圖時如何執行此操作? 我想不通,文檔似乎什么也沒說。

我試過了:

handler404 = 'path.to.view.Custom404.as_view'

沒關系,我忘了嘗試這個:

from path.to.view import Custom404
handler404 = Custom404.as_view()

現在看起來很簡單,它可能不值得在 StackOverflow 上提問。

通過在我的自定義 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

在我的根 URLConf 文件中,我有以下內容:

from apps.errors.views.notfound import NotFoundView

handler404 = NotFoundView.get_rendered_view()

在您的主urls.py您只需添加from app_name.views import Custom404然后設置handler404 = Custom404.as_view() 它應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM