J code
J code

Reputation: 9

Can't find the error in my django project

I am creating a booking website for hotels using Django, I used the booking api to get the hotels with its images and location highlights... I sent to the django template a list of dictionaries from the backend, each dict represents a hotel, now there is two apis request that I am using 1- To get all the hotels 2-To get the images and location highlights of the hotel based on its id that 1 will give me alongside other info like the name and address... (when a button is pressed)

I implemented a loop in the template that will fetch all the hotels from the list on the page and I used the id of the hotel to pass it to a url namespace in the template (Template.html) where I want to call a function (book_now) and pass the arguments below: id of the hotel, name of the hotel, address of the hotel.

Now what's happening is that when I choose certain destination like Berlin or Istanbul or Paris I get this error:

NoReverseMatch at /homepage/
Reverse for 'book_now' with keyword arguments '{'id_hotel': **'6140138'**, 'name': 'Vital Hotel Fulya Istanbul Sisli', 'add': 'FULYA MAH. MEHMETÇİK CAD. NO: 61 İÇ KAPI NO: 3 ŞİŞLİ/İSTANBUL '}' not found. 1 pattern(s) tried: ['homepage/Book_now/(?P<id_hotel>[^/]+)/(?P<name>[^/]+)/(?P<add>[^/]+)$']

If I choose Dubai , Madrid , Los Angeles everything is working normally I don't know why its not logic

and and If I run book_now function alone with the id 6140138 and the name of the respective hotel that is given in the error (Here its Vital Hotel Fulya..) I get the expected result in the terminal

I really don't know what's happening

Homepage.urls

    app_name='Homepage'

urlpatterns = [
    path('',views.hotels_generator,name='hotels_generator'),
    path('Book_now/<id_hotel>/<name>/<add>',views.book_now,name='book_now'),
    path('logging_out/',views.log_out,name='logout'),
    path('AboutUs/',views.about_us,name='AboutUs'),
    path('contact/',views.contact_us,name='contact')
]

Homepage.views

def hotels_generator(request):
     if request.method=='POST':
          start_date=request.POST.get("trip-start")
          end_date=request.POST.get("trip-end")
          if start_date>end_date or start_date<str(datetime.date(datetime.now())) or end_date<str(datetime.date(datetime.now())):
               return render(request,'Homepage/homepage.html',{'l':['error']})
          destination=request.POST.get("Destination")
          nb_adults=request.POST.get("numofadults")
          nb_kids=request.POST.get("numofkids")
          location=name.geocode(destination)
          latitude=location.latitude
          longitude=location.longitude
          url = "https://booking-com.p.rapidapi.com/v1/hotels/search-by-coordinates"
          querystring = {"checkin_date":start_date,"order_by":"popularity","units":"metric","longitude":longitude,"adults_number":nb_adults,"latitude":latitude,"room_number":"1","locale":"en-gb","filter_by_currency":"USD","checkout_date":end_date,"children_number":nb_kids,"children_ages":"5,0","page_number":"0","categories_filter_ids":"class::2,class::4,free_cancellation::1","include_adjacency":"true"}
          if nb_kids=='':
               querystring.pop('children_number')
          headers = {
          'x-rapidapi-host': "booking-com.p.rapidapi.com",
          'x-rapidapi-key': "42dbab23b1msh23693ff3dc47fa2p1e3cbdjsn11dce8163003"
          }
          response = requests.request("GET", url, headers=headers, params=querystring)
          info=json.loads(response.text)
          l=[]
          for i in range(0,len(info['result'])):
               dict={}
               dict['Hotel_name']=info['result'][i]['hotel_name']
               dict['hotel_city']=info['result'][i]['city_trans']
               dict['hotel_address']=info['result'][i]['address_trans']
               dict['price']=str(info['result'][i]['price_breakdown']['gross_price'])+' '+info['result'][i]['currencycode']
               dict['image_url']=str(info['result'][i]['max_photo_url'])
               dict['id_Hotel']=str(info['result'][i]['id'][14:])
               l.append(dict)
          return render(request,'Homepage/Template.html',{'l':l})
     else:
          return render(request,'Homepage/homepage.html')

def book_now(request,id_hotel,name,add):
     print('suiwer')
     Hotel_landmarks=[]
     url_landmarks = "https://booking-com.p.rapidapi.com/v1/hotels/nearby-places"
     querystring1= {"locale":"en-gb","hotel_id":id_hotel}
     headers1 = {
        'x-rapidapi-host': "booking-com.p.rapidapi.com",
        'x-rapidapi-key': "42dbab23b1msh23693ff3dc47fa2p1e3cbdjsn11dce8163003"
        }
     response1 = requests.request("GET", url_landmarks, headers=headers1, params=querystring1)
     info=json.loads(response1.text)
     for i in info['landmarks']['closests']:
        Hotel_landmarks.append(i['landmark_name']+'  '+str(i['distance'])+' m')

     
     hotel_images_url=[]
     url_images = "https://booking-com.p.rapidapi.com/v1/hotels/photos"
     querystring2 = {"locale":"en-gb","hotel_id":id_hotel}

     headers2 = {
         "X-RapidAPI-Host": "booking-com.p.rapidapi.com",
         "X-RapidAPI-Key": '42dbab23b1msh23693ff3dc47fa2p1e3cbdjsn11dce8163003'
     }
     response2 = requests.request("GET", url_images, headers=headers2, params=querystring2)
     response2=json.loads(response2.text)
     for i in response2:
          hotel_images_url.append(i['url_max'])

     
     url_desc = "https://booking-com.p.rapidapi.com/v1/hotels/description"

     querystring3 = {"hotel_id":id_hotel,"locale":"en-gb"}

     headers3 = {
          "X-RapidAPI-Host": "booking-com.p.rapidapi.com",
          "X-RapidAPI-Key": '42dbab23b1msh23693ff3dc47fa2p1e3cbdjsn11dce8163003'
     }

     response3 = requests.request("GET", url_desc, headers=headers3, params=querystring3)
     response3=json.loads(response3.text)
     hotel_desc=response3['description']

     liste_of_monuments=[]
     url4 = "https://booking-com.p.rapidapi.com/v1/hotels/nearby-places"
     querystring4 = {"locale":"en-gb","hotel_id":id_hotel}
     headers4 = {
          'x-rapidapi-host': "booking-com.p.rapidapi.com",
          'x-rapidapi-key': '42dbab23b1msh23693ff3dc47fa2p1e3cbdjsn11dce8163003'
          }
     response4 = requests.request("GET", url4, headers=headers4, params=querystring4)
     info=json.loads(response4.text)
     for i in info['landmarks']['populars']:
           liste_of_monuments.append(i['landmark_name']+'  '+str(i['distance'])+' m')
     print('siuiu')
     return render(request,'Homepage/Hotels_page.html',{'l':Hotel_landmarks,'name':name,'add':add,'img':hotel_images_url,'desc':hotel_desc,'l2':liste_of_monuments})

Template.html

<!DOCTYPE html>
<html>
    <head>
        <title>Hotels</title>
        {% load static %}
        <link rel="stylesheet" href="{% static 'Template.css' %}">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        
    </head>
<section class="packages" id="packages">
    <div class="box-container">
    {% for i  in l %}

            <div class="box">
                <img src="{{i.image_url}}">
                <div class="content">
                    <div><h2>{{i.Hotel_name}}, {{i.hotel_city}}</h2></div>
                    <h4>{{i.hotel_address}}<br><br></h4>
                    <div class="boxxx">
                        <div></div>
                        <div></div>
                        <div class="price"><span>{{i.price}}</span></div>
                    </div>
                    <br>
                    <a href="#"><button style="height: 50px; width: 250px">View on map</button></a>
                    <a href="{% url 'Homepage:book_now' id_hotel=i.id_Hotel name=i.Hotel_name add=i.hotel_address %}"><button style="height: 50px; width: 250px;padding-left:30px;">Book Now</button></a>
                </div>
            </div>
            <script>
                let ratings=1;
                document.getElementById("demo").innerHTML = ratings;
                
            </script>
        <br><br>
    {% endfor %}
    </div>

Upvotes: 0

Views: 70

Answers (1)

CemreY
CemreY

Reputation: 394

In that case, the address section of the query is causing the issue I think. You may need to update your regex to include special characters like ÇŞİ

ie. (?:[A-Z]|[ŞİÇ])

or your regex could be more inclusive by accepting any character

ie. book_now\/{id_hotel}\/.*\/

feel free to test out your new regex here https://regex101.com/

enter image description here

Upvotes: 1

Related Questions