【问题标题】:Django pattern prefix in URL isn't spreading to included views: Bug or misunderstanding?URL 中的 Django 模式前缀没有传播到包含的视图:错误或误解?
【发布时间】:2014-05-09 09:06:07
【问题描述】:

如果我这样做:

urlpatterns += patterns('datasets.views',                                  
    url(r'^$', 'home', name="home"),                 
    url(r'^(?P<slug>\w+)/', include(patterns('',#HERE I OMIT THE PREFIX                    
        url(r'^edit/', 'edit_api', name="edit_api"),                                            
    ))),
)

我会在 /my-slug-name/ 'str' object is not callable 处得到一个 ``TypeError

但是如果我第二次包含前缀,它就可以工作了。

urlpatterns += patterns('datasets.views',                                  
    url(r'^$', 'home', name="home"),                 
    url(r'^(?P<slug>\w+)/', include(patterns('datasets.views', #HERE THE PREFIX IS REPEATED                      
        url(r'^edit/', 'edit_api', name="edit_api"),                                            
    ))),
) 

我是否误解了 include 的工作原理?我应该将此报告为错误吗?

【问题讨论】:

标签: django django-urls


【解决方案1】:

这不是include() 的工作方式,而是patterns 的工作方式。如果没有前缀,edit_api 只是一个模式字符串,它无法将其解析为视图。为第一个模式提供前缀不会使其隐式包含在嵌套模式中。您使用模式的方式有点难看。您需要单独考虑每个patterns()。前缀是为了让你的 url 配置干净,考虑一下 -

api_patterns = patterns('datasets.views',
        url(r'^edit/', 'edit_api', name="edit_api"),
        # --------------^ Here edit_api is actually datasets.views.edit_api
        # if you don't want to provide the prefix, you write the full path to the view
        # url(r'^edit/', 'datasets.views.edit_api', name="edit_api"),
)
urlpatterns += patterns('datasets.views',
    url(r'^$', 'home', name="home"),
    url(r'^(?P<slug>\w+)/', include(api_patterns)),
    # ------------------------------^
    # Here include doesn't use the pattern prefix you used 3 lines above
)

原因是,include 旨在包含来自不同地方的模式,如应用程序等。每个模式都可能有单独的模式前缀。因此,为了简单起见,您可以提供模式前缀并编写相对视图名称,也可以省略模式前缀并编写完整的视图路径。

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 2010-12-20
    • 1970-01-01
    • 2012-04-11
    • 2015-10-20
    • 2016-04-11
    • 2023-03-27
    • 2021-06-16
    • 1970-01-01
    相关资源
    最近更新 更多