Django:urls.py 中的 urlpatterns 格式

标签 django url

我注意到在 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 string prefix.



    它还提供了一个示例,说明您可能想要使用它的原因:

    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'),
    )
    


    但是,请注意,此功能已弃用:

    Deprecated since version 1.8:

    urlpatterns should be a plain list of django.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 to patterns()?").

    关于Django:urls.py 中的 urlpatterns 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31474285/

    相关文章:

    django - 使用 Django 引发默认错误 on_delete PROTECT

    django - 有没有办法将事件 Hook 到 django-cms 页面发布事件

    ruby-on-rails - 在本地设置支持子域的虚假 URL

    c# - 在 C# ASP.NET 中获取完整的查询字符串

    url - 网站的 Unicode url 和 seo 问题

    python - Django:事务原子性是否确保代码在保存数据库后发生?

    django - 在具有ManyToMany字段的QuerySet上输出values()

    Django 使用 AJAX 传递参数

    regex - Perl Regexp::Common 意外匹配错误的 URL

    asp.net - 在IIS中禁用目录列表