0

我正在使用一些较旧的 Django 代码,并且该url函数未在任何地方使用,类似于Django 1.4 文档中的示例:

from django.conf.urls import patterns, url, include

urlpatterns = patterns('',
    (r'^articles/2003/$', 'news.views.special_case_2003'),
    (r'^articles/(\d{4})/$', 'news.views.year_archive'),
    (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)

但我在Django 1.5 文档中注意到该url函数经常使用:

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^articles/2003/$', 'news.views.special_case_2003'),
    url(r'^articles/(\d{4})/$', 'news.views.year_archive'),
    url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
    url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)

为什么是这样?这是惯例问题,还是有使用该url功能的技术原因?将来我应该遵循哪种做法,我应该如何在没有url调用的情况下维护我的遗留代码?

4

1 回答 1

2

文档

url(正则表达式,视图,kwargs=无,名称=无,前缀='')

您可以使用 url() 函数而不是元组作为 patterns() 的参数。如果您想指定一个没有可选额外参数字典的名称,这很方便。例如:

urlpatterns = patterns('',
    url(r'^index/$', index_view, name="main-view"),
    ...
)

然后您将它们用于反向 URL 匹配(同样,文档

您可以将第一个示例转换为:

url(r'^articles/2003/$', special_case_2003, name="special_case_2003"),

并在您的模板中调用它

{% url special_case_2003 %}

是的,也许您发布的两个示例对此有点太模糊了

于 2013-04-23T22:05:43.547 回答