'Django regex not working when adding other branches to url

I am a complete beginner in Django, and I have encountered a problem while trying to set up a url for each "room". Here is the code:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^home/$', views.home, name='home'),
    url(r'^room/<str:pk>/$', views.room, name='room'),

]

Everything was working perfectly, until I add /<str:pk>/$. I have also add this code in the views.py section:

def room(request,pk):
    return render(request, 'base/room.html')

However I still get an error when loading the website. Image of the error message

Does someone know how to make it work?



Solution 1:[1]

  1. Firstfully, as said in comments, you have to put pk in url and follow that:

    http://127.0.0.1:8000/room/1/
    
  2. Then, make sure you have at least one Room object in database, otherwise the url will not be active.

  3. Last thing, it should be rather <int:pk> than str, because I believe your pk is a classic id as a number. So urls:

    urlpatterns = [
        ...
        url(r'^room/<int:pk>/$', views.room, name='room'),
    
    ]
    

Solution 2:[2]

Just replaced /<str:pk>/$ by /(?P<pk>\d+)/$', views.room, name='room'), and worked out perfectly !

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NixonSparrow
Solution 2 Flusten