Can't get parameters from URL. Django

Few days ago I started to learn Django. I have a problem with URL parameter. My views.py function:

def hotel(request, id):
    return HttpResponse(id)

My urls.py code:

re_path(r'^hotel/(?P<id>)[\d]/$', views.hotel)

And when I load the page like http://127.0.0.1:8000/hotel/4/. HttpResponse shows me nothing. id = None. Why? How can I take this id == 4?

Upvotes: 1

Views: 130

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

There are two problems here:

  1. between the parenthesis, you did not match anything, indeed, you wrote (?P<id>), so the integer is captured later, and not in the id group; and
  2. you forgot the + quantifier. This means \d will match exactly one digit.

You can fix this by rewriting the path to:

re_path(r'^hotel/(?P<id>\d+)/$', views.hotel),

That being said, like @sam says using path converters is likely more convenient and less error prone, you can define path [Django-doc] with:

path('hotel/<int:id>', views.hotel)

Upvotes: 1

Swetank Poddar
Swetank Poddar

Reputation: 1291

Try this:

path('hotel/<int:id>/', views.hotel)

As your id is an integer, this is a cleaner way to go about it.

Upvotes: 1

Related Questions