MatheusJardimB
MatheusJardimB

Reputation: 3677

Django model validate date and datetime ranges

What is the best solution to validate a date and dateTime interval in a Django model?

This is my model:

class PriceOption(Model):
    from_datetime = DateTimeField(verbose_name=_('from datetime'))
    to_datetime = DateTimeField(verbose_name=_('to datetime'))

    from_time = TimeField(verbose_name=_('from time'))
    to_time = TimeField(verbose_name=_('to time'))

And I need to make sure that from_datetime happens before to_datetime and the same for from_time and to_time.

Should I override the save method? Or validators somehow?

I see that Postgres have Date and DateTime range fields. This would only solve the first pair of fields.

Upvotes: 2

Views: 4628

Answers (1)

Shang Wang
Shang Wang

Reputation: 25559

It's better to use a form to validate the time range, form has already built in function clean() to fit your needs:

class PriceOptionForm(forms.ModelForm):
    # some normal ModelForm setup goes here
    def clean(self):
        cleaned_data = super(PriceOptionForm, self).clean()
        from_time = cleaned_data.get("from_time")
        end_time = cleaned_data.get("end_time")

        if from_time and end_time:
            if end_time < from_time:
                raise forms.ValidationError("End time cannot be earlier than start time!")
        return cleaned_data

Upvotes: 1

Related Questions