[Django]-Django 2.2.5 URL regex in url path

5👍

You’ve got that warning because Django unable to match the url to any of your urlpattern. Shortly you can use this to solve your problem:

# products/urls.py

from django.urls import path
from .import views

urlpatterns = [
    path('', views.ProductListView.as_view(), name='products'),
    path('products/<int:pk>/$', views.ProductDetailView.as_view(), name='details')
]

or if you want to use regex to match your url then:

# products/urls.py

from django.urls import path, re_path
from .import views

urlpatterns = [
    path('', views.ProductListView.as_view(), name='products'),
    re_path(r'^products/(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='details')
]

The reason is because your ProductDetailView are inheriting from DetailView of Django. That View already implemented some mixin to get the object from pk key instead of id that’s why when you change to use <int:pk> it’ll works.

You can take a look at the source code to see how Django implementing to query the object. (Keep you eyes on SingleObjectMixin mixin and property pk_url_kwarg = 'pk'.

I also recommend you to change the value of pk_url_kwarg in ProductDetailView view and also remember to change pk in the urlpattern into the new value which match with pk_url_kwarg value.

Leave a comment