Validate end_date is bigger than start_date in Django Model Form

juanefren picture juanefren · Sep 9, 2011 · Viewed 7.4k times · Source

I have a start_date and end_date fields in my model, I want to assign an error to end_date when it is bigger than start_date, I have been looking docs, but don't find an example about that.

Answer

Rob Osborne picture Rob Osborne · Sep 9, 2011

You need a custom clean function in your form that does the check:

def clean(self):
    cleaned_data = super().clean()
    start_date = cleaned_data.get("start_date")
    end_date = cleaned_data.get("end_date")
    if end_date < start_date:
        raise forms.ValidationError("End date should be greater than start date.")