Django: formats of urlpatterns in urls.py

前端 未结 2 796
不知归路
不知归路 2020-12-06 16:06

I noticed that in Django there are two formats of urlpatterns in file urls.py:

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


        
2条回答
  •  [愿得一人]
    2020-12-06 16:52

    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.

提交回复
热议问题