我注意到在 Django 中有两种格式 urlpatterns
在文件 urls.py
:
urlpatterns = [
url(...),
url(...),
]
和
urlpatterns = pattern('',
url(...),
url(...),
)
第一个是
url
的列表实例,第二个调用 pattern
具有空字符串和数字 url
的模块实例作为参数。最佳答案
根据 the documentation , patterns
是:
A function that takes a prefix, and an arbitrary number of URL patterns, and returns a list of URL patterns in the format Django needs.
The first argument to
patterns()
is a stringprefix
.
它还提供了一个示例,说明您可能想要使用它的原因:
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^articles/([0-9]{4})/$', 'news.views.year_archive'), url(r'^articles/([0-9]{4})/([0-9]{2})/$', 'news.views.month_archive'), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', 'news.views.article_detail'), )
In this example, each view has a common prefix –
'news.views'
. Instead of typing that out for each entry inurlpatterns
, you can use the first argument to thepatterns()
function to specify a prefix to apply to each view function.With this in mind, the above example can be written more concisely as:
from django.conf.urls import patterns, url urlpatterns = patterns('news.views', url(r'^articles/([0-9]{4})/$', 'year_archive'), url(r'^articles/([0-9]{4})/([0-9]{2})/$', 'month_archive'), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', 'article_detail'), )
但是,请注意,此功能已弃用:
Deprecated since version 1.8:
urlpatterns
should be a plain list ofdjango.conf.urls.url()
instances instead.
请注意 the explanation as to why包括(有充分的理由,显然!):
Thus
patterns()
serves little purpose and is a burden when teaching new users (answering the newbie’s question "why do I need this empty string as the first argument topatterns()
?").
关于Django:urls.py 中的 urlpatterns 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474285/