Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 475
Shruthi suresh Avatar asked Nov 12 '17 06:11

Shruthi suresh


People also ask

What is P in Django URL?

In django, named capturing groups are passed to your view as keyword arguments. Unnamed capturing groups (just a parenthesis) are passed to your view as arguments. The ? P is a named capturing group, as opposed to an unnamed capturing group.

What happens if you skip the trailing slash in Django?

The local Django webserver will automatically restart to reflect the changes. Try again to refresh the web page for the User section of the admin without the trailing slash: 127.0. 0.1:8000/admin/auth/user .

What is slug in Django URLs?

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs."


1 Answers

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

like image 196
Chaitu Pendyala Avatar answered Sep 18 '22 01:09

Chaitu Pendyala