我想检查用户选择的日期是否尚未预订。我在下面编写了代码,在输入数据库中预订的日期后,我被告知该日期是免费的,不应该是。
模型
属性模型
class Kip(models.Model):
user=models.ForeignKey(User)
name=models.CharField(max_length=250)
address=models.CharField(max_length=200)
财产所有者日历模型
class OwnerCalendar(models.Model):
user=models.ForeignKey(User)
kip=models.ForeignKey(Kip)
booked_dates=models.CharField(max_length=1000)
pub_date=models.DateTimeField()
预订房产模型
class Bookable(models.Model):
user=models.ForeignKey(User)
event_date=models.DateField()
session=models.ForeignKey(Session)
full_name=models.CharField(max_length=100)
phone_no=models.CharField(max_length=40)
kip=models.ForeignKey(Kip)
浏览
def booking_of_space(request, kipid):
if request.method=="POST":
form=BookableForm(request.POST)
if form.is_valid():
data=form.cleaned_data
newbooking=Bookable(
user=request.user,
pub_date=datetime.datetime.now(),
event_date=data['event_date'],
phone_no=data['phone_no'],
kip=Kip.objects.get(pk=kipid),
session=Session.objects.get(session_key=request.session.session_key))
newbooking.save()
renter=newbooking.event_date
owners=OwnerCalendar.objects.filter(kip__id=kipid).values_list('booked_dates')
if renter in owners:
return HttpResponse('Booked already')
else:
return HttpResponse('Go ahead and book')
else:
return HttpResponse('Kindly input the right data')
else:
return render_to_response('bookablespace.html',{'BookableForm':BookableForm},context_instance=RequestContext(request))
我错过了什么?
答案 0 :(得分:2)
您正在将日期对象newbooking.event_date
与字符串booked_dates
的列表进行比较,而这些字符串永远不会成立。为什么不进行查询以检查在特定时间是否已为某个属性创建了Bookable
条目?类似的东西:
if form.is_valid():
data=form.cleaned_data
requested_date = data['event_date']
requested_kip = Finapart.objects.get(pk=kipid)
existing_bookings = Bookable.objects.filter(
kip = requested_kip,
event_date = requested_date
)
if existing_bookings:
return HttpResponse('Booked already')
newbooking=Bookable(
user=request.user,
pub_date=datetime.datetime.now(),
event_date=requested_date,
phone_no=data['phone_no'],
kip=requested_kip,
session=Session.objects.get(session_key=request.session.session_key))
newbooking.save()
return HttpResponse('Booking saved')
...