Micks Ketches Micks Ketches - 1 year ago 144
Python Question

Regex interpretaion in Django tutorial

despite being familiar with the basics of regex, the tutorial for Django 1.10 does not go into much detail about how some regex generates dynamic links.
I am looking at this specific snippet under the polls/urls.py:

url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group,
do not make sense to me. Specifically, how does Django know that
is a foreign key?

Answer Source

The (?P<question_id>.*) Says everything captured by the regex inside the parenthesis will be in a named group called question_id. It can be directly addressed. So the regex doesn't know it is a foreign key or anything of the sort, just that there is a group named question_id. The parenthesis isn't really matched in the incoming string.

The [0-9]+ matches and numeric string 1 or more digits long.

^ is the start of the string. $ is the end of the string. ^, $, (?P<question_id>, and ) are somewhat meta and aren't impacted by the string so much as the string's position and how the regex extracted groups will be referenced.

The captured group is passed to the view (detail in this case) as a keyword argument and it's up to the view to make use of it in a meaningful way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download