Валидация формы не происходит для формы модели Django
Я создал следующую модель формы и хочу применить к ней валидацию, но она не работает. Может ли кто-нибудь сказать мне, какую ошибку я допускаю?
"""class used for booking a time slot."""
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['check_in_date', 'check_in_time', 'check_out_time',
'person', 'no_of_rooms']
"""Function to check if username and password match or not."""
def clean(self):
cleaned_data = super().clean()
normal_book_date = cleaned_data.get("check_in_date")
normal_check_in = cleaned_data.get("check_in_time")
if (normal_book_date < now.date() or
(normal_book_date == now.date() and
normal_check_in < now.time())):
#self._errors['check_in_date'] = self.error_class([
# 'You can only book for future.])
raise ValidationError(
"You can only book for future."
)
return cleaned_data
Просто переопределите is_valid()
вместо чистого... Вот где я нашел успех
"""class used for booking a time slot."""
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields = ['check_in_date', 'check_in_time', 'check_out_time',
'person', 'no_of_rooms']
"""Function to check if username and password match or not."""
def is_valid(self):
valid = super(BookingForm, self).is_valid()
# ^ valid is a Boolean
# Note: added self to cleaned_data.get()
normal_book_date = self.cleaned_data.get("check_in_date")
normal_check_in = self.cleaned_data.get("check_in_time")
if (normal_book_date < now.date() or
(normal_book_date == now.date() and
normal_check_in < now.time())):
valid = False
# Not sure if this works, or is needed (the "raise" part mostly)
# if it doesn't work just add the error to the field instead (see below)
raise ValidationError(
"You can only book for future."
)
# You could also add the error msg per field & it will render it
# - extra tidbit
self.add_error('normal_book_date', 'You can only book for future.')
return valid
Вызов is_valid происходит, когда вы делаете form.is_valid()
в представлении, поэтому убедитесь, что вы делаете и это