Reputation: 53
I know, there is a similiar question, which (I have read), but I have a question to that issue.
How my forms.py goes:
class DataForm(forms.ModelForm):
start_date = forms.CharField(
widget=widgets.DateTimePicker(attrs={'class': 'form-control', 'style': 'width:90%'}),
required=False
)
....
class Meta:
model = Data
My models.py goes that way:
start_date = models.DateTimeField(null=True, blank=True)
And when I try to save that way:
if form.is_valid():
form.save()
I got this error:
[u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
What is wrong with that? I want to make start_date field optional.
Upvotes: 2
Views: 2932
Reputation: 2622
That happens because you declare start_date
as a CharField
in your DataForm
, you should use instead forms.DateTimeField
.
Your field is not required, so the user is allowed to leave it empty. This is what happens inside Django when you post data in a form:
empty_values
array (list of the values considered "empty", hardcoded into the field's source code).empty_values
(and that is the case in your situation), it returns the proper Python representation of the empty value. Unless the field is required, in that case raises a ValidationError
.At point 3. forms.CharField
and forms.DateTimeField
behaves differently. CharField
finds the empty value and returns ''
, an empty string, while instead DateTimeField
returns None
. The correct blank value for the model.DateTimeField
is None
not ''
.
That's why Django raises the exception: because you're trying to assign ''
to models.DateTimeField
, and the latter is unable to cast it properly into a date, because it doesn't recognize ''
as a valid blank value for a DateTimeField
.
You can see Django's source code to understand better how it works, and also the documentation on writing custom fields and on form and field validation.
Upvotes: 6