0
votes

I Need To compare the Booking datetime, Book the room when no one booked the Room

While I'm Trying to Compare Two dates I got Below Error can't compare offset-naive and offset-aware datetimes

Here Is my Check availability function

import datetime
from booking.models import Booking
from mainapp.models import Room
def check_avaliblity(room,Check_in,Check_out):
    avaliblity_list=[]  #It will return binch of True and False
    booking_list=Booking.objects.filter(room=room)#It will check bookings of specific room ex:101
    for booking in booking_list:
        if booking.Check_in>Check_out or booking.Check_out<Check_in: 
            #booking.check_in and booking.check_out is existing booking
            avaliblity_list.append(True)
        else:
            avaliblity_list.append(False) #If any of list in avaliblity_list is get False The Booking cannot happend
    return all(avaliblity_list)

This is My Booking Model

class Booking(models.Model):
    """Django data model Booking"""
    user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)

    room=models.ForeignKey(Room,on_delete=models.CASCADE)
    Check_in = models.DateTimeField(datetime.datetime.strptime(str(datetime.datetime.now()),'%Y-%m-%d %H:%M:%S.%f').strftime("%Y-%m-%d %H:%M"))
    Check_out = models.DateTimeField(datetime.datetime.strptime(str(datetime.datetime.now()),'%Y-%m-%d %H:%M:%S.%f').strftime("%Y-%m-%d %H:%M"))
 
    class Meta:
        verbose_name = 'Booking'
        verbose_name_plural = 'Bookings'

    def __str__(self):
        return f'{self.user} booked {self.room} from {self.Check_in} to {self.Check_out}'

And Finally Views.py

if request.method=='POST':
    #This is from booking page
        get_roomType=Room_Type.objects.get(roomtype=request.POST['type'])
        roomid=get_roomType.id
        getout=request.POST['check_out']  
        check_out=datetime.datetime.strptime(getout,'%m/%d/%Y %H:%M %p').strftime('%Y-%m-%d %H:%M:%S+00:00')
        getin=request.POST['check_in']  
        check_in=datetime.datetime.strptime(getin,'%m/%d/%Y %H:%M %p').strftime('%Y-%m-%d %H:%M:%S+00:00')
        check_in=datetime.datetime.strptime(check_in,'%Y-%m-%d %H:%M:%S+00:00')
        check_out=(datetime.datetime.strptime(check_out,'%Y-%m-%d %H:%M:%S+00:00'))
        print(type(check_out))
    #This can set the values id to roomtype id
        room_list=Room.objects.filter(room_type_id=get_roomType)
        user_book=request.user
        avalible_rooms=[]
        for room in room_list:
            if avalablity.check_avaliblity(room,check_in,check_out):
                avalible_rooms.append(room)
                if len(avalible_rooms)>0:
                    room=avalible_rooms
                    book_room=Booking.objects.create(
                        user=user_book,
                        room=room,
                        Check_in=check_in,
                        Check_out=check_out
                    )
                    book_room.save()
                    return HttpResponse(book_room)
            else:
                return HttpResponse("Not found")
    type_of_room=Room_Type.objects.get(roomtype=room)
    context={'type':type_of_room}
    return render(request,'app/book.html',context)

HERE IS MY ERROR

TypeError at /booking/booking/Lux

can't compare offset-naive and offset-aware datetimes

Request Method:     POST
Request URL:    http://127.0.0.1:8000/booking/booking/Lux
Django Version:     3.1.4
Exception Type:     TypeError
Exception Value:    

can't compare offset-naive and offset-aware datetimes

Exception Location:     /home/hussain/Documents/GitHub/Noris-Hotel-Booking/Hotel/booking/bookingFunction/avalablity.py, line 9, in check_avaliblity
Python Executable:  /home/hussain/Documents/GitHub/Noris-Hotel-Booking/env/bin/python3
Python Version:     3.8.6
Python Path:    

['/home/hussain/Documents/GitHub/Noris-Hotel-Booking/Hotel',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/hussain/Documents/GitHub/Noris-Hotel-Booking/env/lib/python3.8/site-packages']

Server time:    Sat, 12 Dec 2020 05:45:52 +0000

Im Trying to upload Screenshot,But I don't Know How to Upload Images,So I copy the Text and Paste It In code Block

Here is my Explaination I'm Waiting for Your Reply Guys

1
SOrry Brother I cant Understand What you r saying Please explain in Begginner level - user13743271
Basically, the error says that you cannot compare datetimes that have an offset from UTC specified ("aware datetime") with ones that do not ("naive datetime") - docs. Now in a web application I'd work in UTC, meaning that you specify the UTC offset to be zero (would show up as "+00:00" in a string). Your question to me seems to be django-specific, which I'm no expert in so I fear I cannot help you further... But enough people here should be able to help out ;-) - MrFuppes
from django.utils.timezone import make_aware and convert it into aware make_aware(datetime_I_Have) - user13743271

1 Answers

0
votes

if booking.Check_in>Check_out or booking.Check_out<Check_in:

You need to make sure that in your database , the datetime is simple or have timezone (timestamptz in case of using PostgreSQL).

===============

For example:

If you pass the tzinfo, when you call datetime.now(), you can compare the dates

enter image description here