【问题标题】:string as second argument in url dispatcher for CBV字符串作为 CBV 的 url 调度程序中的第二个参数
【发布时间】:2013-11-25 16:41:02
【问题描述】:

在基于类的视图之前,我的 urls.py 看起来像这样:

urlpatterns= patterns('mypackage.views',
                      url(r'^$', 'home', name='home'),
                      url(r'other', name='other'),
                      )

现在我的主页视图是基于类的。由于我喜欢统一性,我确实 想将视图类保留为字符串。我试过了:

urlpatterns= patterns('mypackage.views',
                      url(r'^$', 'Home.as_view', name='home'),
                      url(r'Other.as_view', name='other'),
                      )

我得到 Parent module mypackage.views.Home does not exist 。如果我简单地给出类名:

urlpatterns= patterns('mypackage.views',
                      url(r'^$', 'Home', name='home'),
                      url(r'Other', name='other'),
                      )

我得到:__init__ takes exactly 1 argument, 2 given

有没有办法将字符串作为第二个参数传递给 CBV 的 url 函数,而不是 from mypackage.views import *

编辑: 似乎没有内置的解决方案。在这种情况下:为什么字符串作为 url 函数的第二个参数允许:它不违反禅宗(“只有一种方法可以做到这一点)?

【问题讨论】:

    标签: python django django-class-based-views


    【解决方案1】:

    您应该导入基于类的视图并以这种方式指定它们:

    from mypackage.views import *
    
    urlpatterns = patterns('mypackage.views',
                           url(r'^$', Home.as_view(), name='home'),
                           url(r'other', Other.as_view() name='other'),
                           )
    

    还请注意,您的url() 调用应具有三个参数:URL 模式、视图和名称(您编写的一些示例没有所有这些)。

    【讨论】:

    • 这就是我想弄清楚的,为什么有可能将字符串作为第二个参数传递,如果它只适用于 FBV?
    • @ProfHase85 这是出于历史原因(即 FBV)。 CBV 是通过导入视图对象并调用 as_view() 来完成的。
    • FWIW,“import *”语句是魔鬼。 “从 mypackage.views 导入主页,其他”
    【解决方案2】:

    如果您想将视图作为字符串传递,那么在您的视图中执行以下操作:

    class Home(View):
        pass
    
    home = Home.as_view()
    

    然后在您的网址中:

    url(r'^$', 'mypackage.views.home', name='home'),
    

    您需要使用完整路径。

    【讨论】:

    • 谢谢,这是一个可能的解决方案,但这违反了 DRY 原则,因为必须为每个视图编写相同的内容
    猜你喜欢
    • 1970-01-01
    • 2021-06-05
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2020-05-13
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多