Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

In particular, I don't understand the following:

  • ?P
  • \d+
  • name='detail'

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'),
)
like image 504
Anthony Avatar asked Jun 05 '13 20:06

Anthony


People also ask

What is a URLconf?

Overview. To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views). This mapping can be as short or as long as needed.

What is URLconf search against?

The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name. For example, in a request to http://www.example.com/myapp/, the URLconf will look for myapp/ .

What is URLconf module in Django?

In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration)

What happens if you skip the trailing slash in Django?

The local Django webserver will automatically restart to reflect the changes. Try again to refresh the web page for the User section of the admin without the trailing slash: 127.0. 0.1:8000/admin/auth/user .


1 Answers

  • (?P<poll_id>...) creates a named group; 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). 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. See Naming URL patterns in the Django manual.

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. The name keyword makes it easy to generate a URL to this view:

{% url 'name' poll.id %}

would generate a URL to http://yourserver/[digits of poll.id]/.

like image 109
Martijn Pieters Avatar answered Sep 20 '22 10:09

Martijn Pieters