6

I am new to django. I was creating forms in django with the help of an online tutorial. I didnot understand a line in the urls.py file. Can someone explain what exactly it means?

from django.conf.urls import url
from . import views
from . views import BlogListView, BlogDetailView, BlogCreateView

urlpatterns = [
    url(r'^$', views.BlogListView.as_view(), name='post_list'),
    url(r'^post/(?P<pk>\d+)/$', BlogDetailView.as_view(), name='post-detail'),
    url(r'^post/new/$', BlogCreateView.as_view(), name='post_new'),
    url(r'^post/(?P<pk>\d+)/edit/$', BlogUpdateView.as_view(), name='post_edit'),
]

I did not understand the following line:

url(r'^post/(?P<pk>\d+)/$'

What does (?P<pk>\d+)/$ signify? Help please

2
  • It is explained in the docs: docs.djangoproject.com/en/1.11/topics/http/urls/#named-groups
    – Klaus D.
    Nov 12, 2017 at 6:26
  • 1
    Stay away from the tutorials on any website other than Django's. None of them explain things in-depth. I think it's a huge waste of time that everytime you need to understand a basic thing, you have to ask a question and wait another half an hour for an answer. Django's docs has an excellent 7-part tutorial that actually explains almost every concept you need to know to get started.
    – xyres
    Nov 12, 2017 at 10:05

2 Answers 2

22

It is a regular expression, which is matched against the actual URL

Here r'' specifies that the string is a raw string. '^' signifies the start, and $ marks the end.

Now 'pk' (when inside <>) stands for a primary key. A primary key can be anything eg. it can be a string, number etc. A primary key is used to differentiate different columns of a table.

Here it is written

<pk>\d+

\d matches [0-9] and other digit characters.

'+' signifies that there must be at least 1 or more digits in the number

So,

.../posts/1 is valid

.../posts/1234 is valid

.../posts/ is not valid since there must be at least 1 digit in the number

Now this number is sent as an argument to BlogListView and you run you desired operations with this primary key

0
1

your BlogDetailView must be having 'id' as an parameter to capture blog post to be updated

this will capture 'id' of selected blog post and pass it to BlogDetailView

url(r'^post/(?P<pk>\d+)/$'

eg: for url: http://localhost:8000/post/2 2 will be captured and will be passed as an 'id' on to BlogDetailView

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.