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 trialBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsHelp me understand P<pk>
I'm just confused about what this part of the regular expression is doing
P<pk>
urlpatterns = [
url(r'^$', views.course_list),
url(r'?P<pk>\d+)/$', views.course_detail),
]
2 Answers
Chris Freeman
Treehouse Moderator 68,428 PointsThe notation ?P<pk>
is a Python extension to the standard regex syntax. It means assign the results of this group (bounded by parens) to the variable name inside. In this case, assign the regex result to pk
.
More in the Python docs re. Look for (?P<name>...)
Jeff Muday
Treehouse Moderator 28,720 PointsThe regex variants of urlpatterns which will also work are numerous. I favor using [0-9]+ as the regex sub-pattern to recognize digits in the URL rather than Kenneth's \d+. Studying this, I learned some more ways to write the regex! Note that I am using the chevron as the leading character to limit the course detail to be shown only with the digit string.
The documentation at the Django Project is excellent!
https://docs.djangoproject.com/en/1.9/topics/http/urls/
This is a "generic" approach: the parameter name for the course pk is not specified, but views.course_detail is still sent the digit string of unspecified length.
urlpatterns = [
url(r'^$',views.course_list),
url(r'^([0-9])+/$', views.course_detail),
]
This is almost exactly Kenneth's approach, pk is the specific "named parameter" coming in as a digit string of unspecified length. Again, the chevron on the front to only allow digit recognition.
urlpatterns = [
url(r'^$',views.course_list),
url(r'^(?P<pk>[0-9])+/$', views.course_detail),
]
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsHow does it know to then pass that variable as an argument into the course_detail function?
Chris Freeman
Treehouse Moderator 68,428 PointsChris Freeman
Treehouse Moderator 68,428 PointsThe
url()
function handles that. There are good examples in the docs.I also noticed a missing paren the second URL in your original post:
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsThank you