Reputation: 4008
I have the following model where I have a DateField:
class E(models.Model):
name = models.CharField(max_length=255
description = models.TextField(max_length=255)
start_date = models.DateField(verbose_name='Start Date')
the ModelForm:
class EventModelForm(forms.ModelForm):
class Meta:
model = Event
fields = ['name', 'description','start_date']
def clean_start_date(self):
datetime_format = '%a %b %d %Y'
start_date = self.cleaned_data['start_date']
return datetime.strptime(start_date, datetime_format)
My issue is that Django ignores the clean method for the start_date, but take in consideration the clean methods for the other fields.
So I use the debugger to check, and I see that is appearing in change_data
, but not in cleaned_data
changed_data: <class 'list'>: [name', 'description', ''start_date']
cleaned_data: name, description
which is strange, so I checked the input, and looks ok:
<input name="start_date" class="c-fi' type="text">
I don't understand why is not calling the clean method, instead make a validation on the Model a fails, so this is why I need clean to change date format before saving.
Upvotes: 1
Views: 643
Reputation: 308879
If you want to change the date formats for the DateField
, you should set input_formats
instead.
class EventModelForm(forms.ModelForm):
start_date = forms.DateField(
verbose_name='Start Date',
input_formats=['%a %b %d %Y'],
)
class Meta:
model = Event
fields = ['name', 'description','start_date']
Since you are not including your custom format in the field, the field itself will raise a validation error, therefore the clean_start_date
method never runs. You can read more about the order of validation in the docs. Note that you shouldn't have to run strptime
in a clean_*
method for a DateField
- the value in cleaned_data
will already be a date by that point.
Upvotes: 1