我在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,然后检查预订是否与该公寓相关。所以,如果我的公寓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的值传递给我的表单?
答案 0 :(得分:2)
您的__init__()
方法应在实例上设置参数,并在clean()
方法中将其用作
FORMS.PY
def __init__(self,*args,**kwargs):
#use self to store id
self.form_apartman_id=kwargs.pop("apartman_id")
super(BookingForm, self).__init__(*args,**kwargs)
def clean(self):
....
the_apartment = Apartman.objects.get(id=self.form_apartman_id)
Views.py
def booking(request, apartman_id):
a = Apartman.objects.get(id=apartman_id)
if request.method == 'POST':
f = BookingForm(apartman_id=apartman_id, request.POST)
if f.is_valid():
....
else:
f = BookingForm(apartman_id=apartman_id)