Django:urls.py中的urlpatterns格式 [英] Django: formats of urlpatterns in urls.py
问题描述
我注意到,在Django中,文件 urls.py
中有两种格式的 urlpatterns
:
urlpatterns = [
url(...),
url(...),
]
和
urlpatterns = pattern('',
/ pre>
url(...),
url(...),
)
第一个是
url
实例的列表,第二个调用模式
模块,空字符串和多个url
实例作为参数。
- 两者之间有什么区别?
- 第二种格式的空字符串的用途是什么?
- 推荐使用哪一个?
解决方案在Django 1.8+中,urlpatterns应该是一个
url()
的列表。这个新的语法实际上可以在1.7中工作。urlpatterns = [
url(...),
url(...),
]
旧的语法使用
pattern
已被弃用在Django 1.8中,并在Django 1.10中删除。urlpatterns = pattern('',
url ...),
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 '^ articles /([0-9] {4})/([0-9] {2})/([0-9] +)/ $','article_detail'),
)
但是,现在也不推荐使用视图的字符串参数,而应该提供可调用的。 / p>
I noticed that in Django there are two formats of
urlpatterns
in fileurls.py
:urlpatterns = [ url(...), url(...), ]
and
urlpatterns = pattern('', url(...), url(...), )
The first is a list of
url
instances, and the second invokes thepattern
module with an empty string and a number ofurl
instances as parameters.
- What is the difference between the two?
- What is the purpose of an empty string in the second format?
- Which one is recommended to use?
解决方案In Django 1.8+, urlpatterns should simply be a list of
url()
s. This new syntax actually works in 1.7 as well.urlpatterns = [ url(...), url(...), ]
The old syntax using
pattern
is deprecated in Django 1.8, and is removed in Django 1.10.urlpatterns = pattern('', url(...), url(...), )
With the old syntax, you could provide a prefix. The example given in the docs is
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'), )
However, using strings arguments for the view is now deprecated as well, and you should provide the callable instead.
这篇关于Django:urls.py中的urlpatterns格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!