Home > Enterprise >  Django regex not working when adding other branches to url
Django regex not working when adding other branches to url

Time:02-20

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?

CodePudding user response:

  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'),
    
    ]
    

CodePudding user response:

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

  • Related