Python Forum
Django: View is unable to find attributes of database model
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Django: View is unable to find attributes of database model
#1
I am trying to make a reservation system for a hotel using Django. I am getting this error when I try to finalize the reservation, I am unable to do so. I believe it is related to the ways that I am trying to get the rooms from the database

Here is my make_reservation view
def make_reservation(request, room_type, check_in_date, check_out_date, guests):
    if request.method == 'POST':
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        phone_number = request.POST.get('phone_number')

        customer = Customer.objects.create(
            first_name=first_name,
            last_name=last_name,
            email=email,
            phone_number=phone_number
        )

        room_type = request.resolver_match.kwargs['room_type']
        rooms = Room.objects.filter(type=room_type)

        if rooms.exists():
            room = rooms.first()
            
            reservation = Reservation.objects.create(
                    room=room,
                    customer=customer,
                    check_in_date=check_in_date,
                    check_out_date=check_out_date
                )

            room.mark_as_booked()

            return redirect('reservation_success') 
        else:
            print(f"No room of type {room_type} exists.")

    context = {
        'room_type': room_type,
        'check_in_date': check_in_date,
        'check_out_date': check_out_date,
        'guests': guests,
    }

    return render(request, 'make_reservation.html', context)
I believe the issue is here
        room_type = request.resolver_match.kwargs['room_type']
        rooms = Room.objects.filter(type=room_type)

        if rooms.exists():
            room = rooms.first()
            
Here are my models
class Room(models.Model):
    
    TYPES = [
        ('double', 'Double'),
        ('king', 'King'),
        ('two_double', 'Two Double'),
        ('suite', 'Suite')
    ]
    
    room_no = models.IntegerField(unique=True)
    type = models.CharField(max_length=20, choices=TYPES)    
    price = models.IntegerField()
    available = models.BooleanField(default=True) 

    def __str__(self):
        return f"Room: {self.room_no} - ${self.price}"

    def mark_as_booked(self):
        self.available = False
        self.save()

    def mark_as_available(self):
        self.available = True
        self.save()

class Reservation(models.Model):
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    check_in_date = models.DateField()
    check_out_date = models.DateField()

    def __str__(self):
        return f"Reservation for {self.customer} - Room {self.room.room_no}
Basically it's not showing there are rooms in the db. Any ideas why?
Reply
#2
Ensure the room_type value is correctly passed and matches the choices defined in your Room model. For instance, if you pass "king" but it is stored as "King" in the database, there will be a mismatch.

Improve error handling to get more information about the failure update this code:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Room, Reservation, Customer
from django.core.exceptions import ObjectDoesNotExist

def make_reservation(request, room_type, check_in_date, check_out_date, guests):
    if request.method == 'POST':
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        phone_number = request.POST.get('phone_number')
        
        try:
            customer = Customer.objects.create(
                first_name=first_name,
                last_name=last_name,
                email=email,
                phone_number=phone_number
            )
        except Exception as e:
            return HttpResponse(f"Error creating customer: {e}")

        try:
            # Filter rooms by type and availability
            rooms = Room.objects.filter(type=room_type, available=True)

            if rooms.exists():
                room = rooms.first()
                
                # Create a reservation
                reservation = Reservation.objects.create(
                    room=room,
                    customer=customer,
                    check_in_date=check_in_date,
                    check_out_date=check_out_date
                )
                
                # Mark room as booked
                room.mark_as_booked()

                return redirect('reservation_success') 
            else:
                return HttpResponse(f"No available room of type {room_type} exists.")
        except ObjectDoesNotExist:
            return HttpResponse(f"Room type {room_type} does not exist.")
        except Exception as e:
            return HttpResponse(f"Error during reservation: {e}")

    context = {
        'room_type': room_type,
        'check_in_date': check_in_date,
        'check_out_date': check_out_date,
        'guests': guests,
    }
    return render(request, 'make_reservation.html', context)
Gribouillis write May-20-2024, 05:57 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  view option in Django Sowmya 1 546 Mar-29-2024, 12:41 PM
Last Post: SULMAN
  Python django view error ZeeKolachi 1 500 Mar-18-2024, 03:14 PM
Last Post: Sowmya
  Querying Django model db - from Jose Portilla’s Udemy course Drone4four 2 1,799 Aug-09-2022, 09:25 AM
Last Post: Addweb
  Save JSON data to sqlite database on Django Quin 0 2,970 Mar-26-2022, 06:22 PM
Last Post: Quin
Photo After using models.Model on my class Im getting 'ImproperlyConfigured' error Django khavro 1 2,270 Apr-05-2021, 03:11 PM
Last Post: SheeppOSU
  [Django]calculate value in model smabubakkar 0 1,722 Apr-15-2020, 03:40 PM
Last Post: smabubakkar
  Downloading Images - Unable to find correct selector Brompy 4 3,142 Jan-22-2020, 04:54 PM
Last Post: snippsat
  Send email to gmail after user fill up contact form and getting django database updat Man_from_India 0 2,170 Jan-22-2020, 03:59 PM
Last Post: Man_from_India
  how retrieve database save multiple data in web Django 2.1 taomihiranga 0 2,875 Jul-30-2019, 04:58 PM
Last Post: taomihiranga
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 3,450 Jun-30-2019, 12:21 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020