我不确定理解下面两个网址之间的区别
from django.conf.urls import patterns, url
from main_app import views
urlpatterns = patterns('',
url(r'^$', views.main, name='home'),
(r'^accounts/$', views.accounts, name="account"),
...
)
两者都在为我工作。我应该使用一个而不是另一个吗?为什么?我很快发现的所有例子都是对第一个合成器的反应,但我想了解原因。
答案 0 :(得分:2)
这是来自Django Documentation的urls.py文件的最新示例
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'),
)
所以你可以说这是标准,因为大多数人会以这种方式学习它,而且它似乎也是这样推广的。
答案 1 :(得分:1)
第一种语法,使用url函数,允许您将关键字参数的字典传递给视图。
https://docs.djangoproject.com/en/dev/topics/http/urls/#passing-extra-options-to-view-functions
来自文档:
urlpatterns = patterns('blog.views',
url(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)
在此示例中,对于 / blog / 2005 / 的请求,Django将调用
blog.views.year_archive(request, year='2005', foo='bar')