Django - Forms - What does (?P<pk>\d+)/$ signify?

15,267

Solution 1

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

Solution 2

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

Share:
15,267
Shruthi suresh
Author by

Shruthi suresh

Updated on August 11, 2022

Comments

  • Shruthi suresh
    Shruthi suresh over 1 year

    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