我在 Django 中的表单验证有问题。
假设我有 2 间公寓,可以选择预订。用户在预订公寓时应选择 start_date 和 end_date。当我验证我的预订表格时,我会检查几个条件,其中之一是查看开始日期和结束日期之间是否有预订天数。如果存在则引发错误。对于数据库中的一间公寓来说,它工作得很好。它看起来像这样:
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['booking_start', 'booking_end', 'gsm']
def clean(self):
cleaned_data = self.cleaned_data
form_booking_start = cleaned_data.get("booking_start")
form_booking_end = cleaned_data.get("booking_end")
the_apartment = Apartman.objects.get(id=2)
between = Booking.objects.filter(booking_start__gte=form_booking_start, booking_end__lte=form_booking_end).exists()
if form_booking_start and form_booking_end:
...
if between:
raise forms.ValidationError("It seems like there are days that are already booked between your booking start and booking end. Please take care of it and book days that are not already booked.")
return cleaned_data
但问题是,当我添加另一个公寓时,如果用户预订日期已经为其他公寓预订,则每次都会引发错误。所以我需要检查那间公寓的身份证,然后检查预订是否与那间公寓有关。所以如果我的公寓 id=2 那么它应该是这样的:
between = Booking.objects.filter(booking_start__gte=form_booking_start, booking_end__lte=form_booking_end, apartman__id=2).exists()
问题是,我不知道如何将该 id 的值从视图传递到我的表单。我的观点是这样的:
def booking(request, apartman_id):
a = Apartman.objects.get(id=apartman_id)
if request.method == 'POST':
f = BookingForm(request.POST)
if f.is_valid():
....
else:
f = BookingForm()
那么,最后,我怎样才能将那个 Apartman_id 的值传递给我的表单呢?