开发者

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/


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.


read the docs, http://docs.djangoproject.com/en/1.2/topics/http/urls/#topics-http-urls


My python regex is rusty but here goes:

r'^polls/$

the ^ means starts with.
The $ means the end

(?P<poll_id>\d+) means an integer \d+ which in my code will be put into a variable poll_id

(r'^admin/', include(admin.site.urls))
doesn't have a $ because you may not want the url to end there. You want admin/somethingelse to be passed to your admin.sites.urls class.


The r means the provided string is raw and escape characters should be ignored. The (r'^admin/', include(admin.site.urls)) line has no $ because it is an include for another url confs. So the end $ is somewhere in the admin.site.urls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜