Validate end_date is bigger than start_date in Django Model Form
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.")
This is an update for Django 2.2 - doc
from django import forms
from .models import Project
class ProjectAddForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'name',
'overview',
'start_date',
'end_date',
'status',
'completed_on',
]
labels = {
"name": "Project Name",
"overview": "Project Overview",
"status": "Project Status",
}
# Logic for raising error if end_date < start_date
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.")
This is the actual recommended example from the docs
In short, remember to return cleaned_data, and raise form errors correctly.
from django import forms
class ContactForm(forms.Form):
# Everything as before.
...
def clean_recipients(self):
data = self.cleaned_data['recipients']
if "[email protected]" not in data:
raise forms.ValidationError("You have forgotten about Fred!")
# Always return the cleaned data, whether you have changed it or
# not.
return data