Django:URL conf,url模板标记的最佳实践

Bra*_*ant 5 django django-templates django-urls django-views

由于基于类的视图在Django中变得更好,我在实现基于类的视图时遇到了"最佳实践"问题.它基本上归结为URL模板标记.

给出这样的urls.py:

urlpatterns = patterns('some_app.views', 
    url(r'^$', 'index', name='some_app_index')
)
Run Code Online (Sandbox Code Playgroud)

该标记可以采用视图的路径:

{% url some_app.views.index %}
Run Code Online (Sandbox Code Playgroud)

或网址的名称:

{% url some_app_index %}
Run Code Online (Sandbox Code Playgroud)

现在,使用基于类的url conf,最终会得到一个这样的url:

from some_app.views import Index

urlpatterns = patterns('', 
    url(r'^$', Index.as_view(), name='some_app_index')
)
Run Code Online (Sandbox Code Playgroud)

这意味着使用{% url some_app.views.index %}不再有效但{% url some_app_index %}仍然有效.(而且{% url some_app.views.Index.as_view %}似乎不是一个解决方案).


所以,我的问题是,从模板中引用URL confs的最佳做法是什么?

到目前为止,我发现使用path.to.view方法更好,因为它是干净的命名空间.但是,基于类的视图看起来越来越好,使用url名称是一个更好的方法吗?在这种情况下,命名空间完全依赖于应用程序开发人员设置的名称属性,其方式是将网址名称与其他应用程序分开...

思考?我在Django文档中找不到"这样做"但如果有人写过这个,我很乐意阅读它.

Ton*_*ell 8

我总是使用名字.

除了你提到的路径问题,如果你有两个指向同一视图的URL,你也会遇到问题.