'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]
Firstfully, as said in comments, you have to put
pkin url and follow that:http://127.0.0.1:8000/room/1/Then, make sure you have at least one
Roomobject in database, otherwise the url will not be active.Last thing, it should be rather
<int:pk>thanstr, because I believe yourpkis a classicidas 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 |
