How to insert NULL into Django's DateField?

user1261774 picture user1261774 · Dec 16, 2013 · Viewed 6.9k times · Source

I have an optional datefield in my django model:

award_grant_date = models.DateField(null=True, blank=True)

When the user leaves the date field blank, NULL is inserted into the DateField, otherwise the date is inserted.

However, if the user does enter a date into the DateField, and the user has selected some other specific data in the form, then I want to insert NULL into the DateField.

So, in my form I have the following code:

    class AwardGrantDetailsForm(forms.Form):
    ...
    award_grant_date = forms.DateField(
    widget=forms.DateInput(attrs={'id':'id_award_grant_date'}),
    input_formats=settings.DATE_INPUT_FORMATS,
    label=_('Date'),
    required=False)
    ...
    elif cd_agdf['award_grant_type'] == 8888 or cd_agdf['award_grant_type'] == 9999:

        self.cleaned_data['award_grant_type_description'] = ''
        self.cleaned_data['award_grant_date'] = 'NULL' //this is the issue here! 

The error I am getting is:

[u"'NULL' value has an invalid date format. It must be in YYYY-MM-DD format."]

I cannot seem to get the syntax correct to enter the NULL in to the award_grant_date date field.

I am using bootstrap datepicker and django 1.4.

How do I write the code self.cleaned_data['award_grant_date'] = '' to insert the required NULL? I have set the models field to null=True, blank=True!

Answer

Peter DeGlopper picture Peter DeGlopper · Dec 16, 2013

The Python representation of database null is None:

self.cleaned_data['award_grant_date'] = None