Kaczor
Kaczor

Reputation: 53

How to make Django DateTimefield non required?

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

Answers (1)

Pietro Saccardi
Pietro Saccardi

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:

  1. The form field tries to convert the raw data into a Python type.
  2. To do that, first checks if the raw data can be found inside the empty_values array (list of the values considered "empty", hardcoded into the field's source code).
  3. If it finds the value in 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.
  4. If the value is not empty, then it proceeds with the casting into Python's types.
  5. The return value is then plugged into your model, or whatever your form does.

At point 3. forms.CharField and forms.DateTimeFieldbehaves 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

Related Questions