Form Validation not happening for Django model form

I have created the following model form and I want to apply validation on it but it is not working. Can anyone please tell me what mistake I am making?

"""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

Just override the is_valid() instead of the clean.. That's where I've found success

"""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

That is_valid is called when you do form.is_valid() in the view, so make sure you're doing that too

Back to Top