[Django]-Django 2.0 Trying to Grab the primary key with regular Expressions but im getting 404

3👍

I Fixed it…I used re_path instead of path and it worked like a charm..

re_path('(?P<pk>\d+)/',views.School_Dview.as_view(),name='detail')

2👍

django2.0 don’t support the use of regex in django.urls.path() else if you really want to write the regex in your urls i will advice you use
django.urls.re_path() which is the new function for the old version django.conf.urls.url

difference between path() and re_path()

with path() your urls would be written as;

from urls import path
urlpatterns =[
   path('',views.School_Lview.as_view(),name='list'),
   path('<int:pk>/',views.School_Dview.as_view(),name='detail')
]

with re_path()

from urls import path
 urlpatterns =[
    re_path('',views.School_Lview.as_view(),name='list'),
    re_path('(?P<pk>\d+)/',views.School_Dview.as_view(),name='detail')
 ]

check the official documentation for more insight on urls routing in django2.0

1👍

While the answers are correct I just wanted to point out that Django actually uses the regular expression [0-9]+ instead of \d+ for primary keys.

They both have the same effect but here you can see all the default converters and their regular expressions who are hidden behind the ‘new’ path syntax.

Leave a comment