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.
Validate end_date is bigger than start_date in Django Model Form
Asked Answered
Closed.... this answer my question... #2117548 –
Florafloral
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.")
I get name 'cleaned_data' is not defined –
Enjoyment
cleaned_data = super().clean() –
Betweentimes
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
© 2022 - 2024 — McMap. All rights reserved.