Django: formats of urlpatterns in urls.py

2019-01-19 09:59发布

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?

标签: django url
2条回答
beautiful°
2楼-- · 2019-01-19 10:23

Per the documentation, patterns is:

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 string prefix.

It also provides an example of why you might want to use it:

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 in urlpatterns, you can use the first argument to the patterns() 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'),
)

However, note that this function is deprecated:

Deprecated since version 1.8:

urlpatterns should be a plain list of django.conf.urls.url() instances instead.

Note that the explanation as to why includes (with good reason, clearly!):

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 to patterns()?").

查看更多
做个烂人
3楼-- · 2019-01-19 10:41

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.

查看更多
登录 后发表回答