Search code examples
regexdjangourlconf

Reg Ex Django Url Conf


These is my django URLconf:

urlpatterns = patterns('',
    ('^hello/$', hello),
    (r'^polls/$', 'mysite.polls.views.index'),
    (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'),
    (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'),
    (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),
    (r'^admin/', include(admin.site.urls)),
)

I don't understand what the r in this regex does:

r'^polls/$

I don't understand what this Regex does:

(?P<poll_id>\d+)

And I don't understand why in:

(r'^admin/', include(admin.site.urls))

There is no $ sign and it still works...

I don't understand what URLconf I have to add, to see a site under http://127.0.0.1:8000/


Solution

  • The 'r' denotes a 'raw' string, which makes life easier when trying to write regexes (you don't end up escaping the escape characters). http://docs.python.org/library/re.html#raw-string-notation

    As far as the second question goes, it creates a named match group of 1 or more digits, and passes that value to the view as 'poll_id'. http://docs.djangoproject.com/en/1.2/topics/http/urls/#named-groups

    The reason there isn't a $ on the admin string is that you want all urls that start with /admin to be passed to the admin app. $ is a special character that defines the end of a string. So if there were an $, then only the url /admin would be passed to the admin app, not /admin/foo or /admin/foo/bar.