Невозможно вызвать ValidationError в форме Django

Я сделал форму, в которой пользователь должен ввести дату и время. Я хочу убедиться, что время вводится в правильном формате, поэтому я написал функцию convert_to_time, чтобы она вызывала ValidationError, когда формат времени неправильный, но это не работает так, как я хочу. Я хочу отображать ошибку в самой форме. Похоже, что функция Exception не работает. То есть элемент управления не попадает внутрь части Exception.

Вот мой файл forms.py.


"""Function to convert string to time."""
def convert_to_time(date_time):
    format = '%H:%M:%S'
    try:
        datetime.datetime.strptime(date_time, format).time()
    except Exception:
        #print("qkftio")   This statement does not get executed even when the time format is wrong
        raise ValidationError(
                "Wrong time format entered."
            )

"""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 ensure that booking is done for future."""
    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")
        convert_to_time(str(normal_check_in))

Вот мой файл models.py.

"""class used when a user books a room slot."""
class Booking(models.Model):
    check_in_date = models.DateField()
    check_in_time = models.TimeField()
    check_out_time = models.TimeField()
    PERSON = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )
    person = models.PositiveSmallIntegerField(choices=PERSON, default=1)
    no_of_rooms = models.PositiveSmallIntegerField(
        validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1
        )

Может ли кто-нибудь помочь?

Обычно внутри 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']

    def is_valid(self):
        valid = super(BookingForm, self).is_valid()
        # ^ Boolean value

        format = '%H:%M:%S'
        try:
            # Note: `self.cleaned_date.get()`
            datetime.datetime.strptime(str(self.cleaned_data.get('check_in_time')), format).time()
        except Exception:

            self.add_error('check_in_time', 'Wrong time format entered.')
            valid = False

        return valid
Вернуться на верх