Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMaxim Andreev
24,529 PointsRegex within urls.py in Django
I'm going through the Django tutorial on https://docs.djangoproject.com/en/1.7/intro/tutorial03/
Now from my understanding the urls.py file simply forwards you to the correct view based on the url. It does this by using regular expressions.
However I'm having trouble understanding the regex that they use.
r'^(?P<question_id>\d+)/results/$'
I understand that in the above case it basically filters for 'www.blahmysite.com/theappimbuilding-polls/question_id/results/' but Can anyone explain in detail how regex is used in this case?
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
Thank you!
PS unrelated but, where does virtualenvs store django? I must have looked through every single hidden folder haha
1 Answer
Kenneth Love
Treehouse Guest TeacherThis is exactly why I'm doing a regex course before the first Django course ;)
Congrats on figuring it out.
Maxim Andreev
24,529 PointsNice..
hopefully you'll expand on what I learned here: https://www.youtube.com/watch?v=koyjj87QbXg
Maxim Andreev
24,529 PointsMaxim Andreev
24,529 PointsOk I think I figured it out...the answer was just below lol, getting late..
?P<question_id>
declares a named capturing group, in this case named question_id, it captures the data within (), and the \d+ just means that it has to be all digits. It is then used as an arg in views.detail. The /$ means that it has to end with '/'. It's then named 'detail' for templating. I think..