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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With