简体   繁体   English

理解Django的urlconf

[英]Understanding Django's urlconf

I'm trying to understand this line: url(r'^(?P<poll_id>\\d+)/$', views.detail, name='detail'), from Django's tutorial on how to create views. 我试图理解这一行: url(r'^(?P<poll_id>\\d+)/$', views.detail, name='detail'),来自Django关于如何创建视图的教程

In particular, I don't understand the following: 特别是,我不明白以下几点:

  • ?P 2 P
  • \\d+ \\ d +
  • name='detail' 命名=“细节”

urls.py urls.py

urlpatterns = patterns('',
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
  • (?P<poll_id>...) creates a named group ; (?P<poll_id>...)创建一个命名组 ; you can now refer to whatever was matched in that group by name. 您现在可以通过名称引用该组中匹配的任何内容。

    The view will be passed a keyword parameter by that name when called. 调用时,视图将通过该名称传递一个关键字参数。

  • \\d is a character group, it matches numeric digits ( 0 through to 9 for ASCII data). \\d是一个字符组,它匹配数字(ASCII数据为09 )。 The + is a quantifier; +是量词; only 1 or more digits will match. 只有一个或多个数字匹配。

  • name='detail' names the URL pattern so you can refer to it by name later when creating reverse URLs. name='detail'命名URL模式,以便稍后在创建反向URL时按名称引用它。 See Naming URL patterns in the Django manual. 请参阅Django手册中的命名URL模式

All in all, that pattern matches a URL that starts with digits, followed by just a / slash, causing Django to call the views.detail view, passing in the matched digits as the poll_id parameter. 总而言之,该模式匹配以数字开头的URL,后跟一个/斜杠,导致Django调用views.detail视图,将匹配的数字作为poll_id参数传递。 The name keyword makes it easy to generate a URL to this view: name关键字可以轻松生成此视图的URL:

{% url 'name' poll.id %}

would generate a URL to http://yourserver/[digits of poll.id]/ . 会生成一个URL到http://yourserver/[digits of poll.id]/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM