Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert NULL into Django's DateField?

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!

like image 687
user1261774 Avatar asked Dec 11 '22 09:12

user1261774


2 Answers

The Python representation of database null is None:

self.cleaned_data['award_grant_date'] = None
like image 115
Peter DeGlopper Avatar answered Dec 22 '22 17:12

Peter DeGlopper


NULL value has an invalid date format. It must be in YYYY-MM-DD format

If you want to store Null value into model use model_field = None

Solution:

registration_date = request.POST.get('registration_date')

if not registration_date:
    registration_date = None

#StudentInfo is my model
student = StudentInfo(name=request.POST.get('name'), std=request.POST.get('std'), registration_date=registration_date)

#Now you can save your model data
student.save()
like image 34
Viraj Wadate Avatar answered Dec 22 '22 15:12

Viraj Wadate