Django:urls.py中的urlpatterns格式 [英] Django: formats of urlpatterns in urls.py

查看:97
本文介绍了Django:urls.py中的urlpatterns格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,在Django中,文件 urls.py 中有两种格式的 urlpatterns

  urlpatterns = [
url(...),
url(...),
]

  urlpatterns = pattern('',
url(...),
url(...),

/ pre>

第一个是 url 实例的列表,第二个调用模式模块,空字符串和多个 url 实例作为参数。


  1. 两者之间有什么区别?

  2. 第二种格式的空字符串的用途是什么?

  3. 推荐使用哪一个?


解决方案

在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 file urls.py:

urlpatterns = [
    url(...),
    url(...),
]

and

urlpatterns = pattern('',
    url(...),
    url(...),
)

The first is a list of url instances, and the second invokes the pattern module with an empty string and a number of url instances as parameters.

  1. What is the difference between the two?
  2. What is the purpose of an empty string in the second format?
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆