Issue
I'm facing an issue with my forms in Django. I've created something like this:
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = [
"name",
"start_date",
"end_date"
]
def clean(self):
start_date = self.cleaned_data["start_date"]
end_date = self.cleaned_data["end_date"]
if start_date > end_date:
raise ValidationError("Start Date cannot be great than End Date")
elif start_date == end_date:
raise ValidationError("The dates must be different.")
def clean_start_date(self):
start_date = self.cleaned_data["start_date"]
if timezone.now() > start_date:
raise ValidationError("The start date of the event must be after today.")
return start_date
When I tried to test it, something weird is happening. So, when I tried to input a start_date that is after today, I get the following message: start_date = self.cleaned_data["start_date"] KeyError: 'start_date' It looks like clean() doesn't see the start_date. But why?
Solution
clean
happens after custom clean_<field_name>
methods. Your clean_start_date
raised a ValidationError, so the value for start_date
was rejected and not included in cleaned_data
.
Here is the relevant Django code:
def full_clean(self):
"""
Clean all of self.data and populate self._errors and self.cleaned_data.
"""
self._errors = ErrorDict()
if not self.is_bound: # Stop further processing.
return
self.cleaned_data = {}
# If the form is permitted to be empty, and none of the form data has
# changed from the initial data, short circuit any validation.
if self.empty_permitted and not self.has_changed():
return
self._clean_fields() # <--- clean_start_date is called here
self._clean_form() # <--- clean is called in here
self._post_clean()
def _clean_fields(self):
for name, bf in self._bound_items():
field = bf.field
value = bf.initial if field.disabled else bf.data
try:
if isinstance(field, FileField):
value = field.clean(value, bf.initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, "clean_%s" % name):
value = getattr(self, "clean_%s" % name)() # <--- your clean method raises a ValidationError
self.cleaned_data[name] = value
except ValidationError as e:
self.add_error(name, e) # <--- except is triggered; 'start_date' never added to cleaned_data
Answered By - CoffeeBasedLifeform
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.