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 trial

Python Django Basics Django Templates Add a Detail View

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,734 Points

Help 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
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The 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>...)

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

The url() function handles that. There are good examples in the docs.

I also noticed a missing paren the second URL in your original post:

urlpatterns = [
    url(r'^$', views.course_list),
    url(r'(?P<pk>\d+)/$', views.course_detail),  # <-- added missing left paren
]
Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,715 Points

The 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),
]