Why Django DateField doesn't accept empty values? - django

I have a model with a DateField field with blank = True and null = True.
It seems that is not possibile save an object with an empty value for the Datefield.
class ProjectTask(models.Model):
actual_start_date = models.DateField(blank=True, null=True)
Then try with Python console:
p = ProjectTask.objects.all().last()
p.actual_start_date = ""
p.save()
The results is:
venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1273, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
I'm using Python 3.4, Django 1.9 and PostgreSQL.
Any suggestions?

Dates are not strings. If you want to pass a string, it needs to be converted to a date. Normally, your form would validate whether or not you had a valid date, but you've bypassed this by setting an empty string directly on the model.
If you don't want to set a value at all, then pass None.

Related

Django. Error saving empty string to DateTimeField(blank=True)

I have a model with a DateTimeField (blank=True, null=True). However, when I try to save an empty string in it, I get the following error:
>>> from courses.models import Event
>>> x = Event.objects.last()
>>> x.date_start = ""
>>> x.save()
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
I have never seen this, any ideas? All my migrations are up to date.
blank=True [Django-doc] has impact on modelforms, not on the model itself. It does not mean that the element accepts an empty string. blank=True simply means that the field is not required. In case the value is not specified, it will use the default value.
But at the model layer, nothing changes. Since your field has null=True [Django-doc], the default in case you do not fill in the value will be None, so you can use:
>>> from courses.models import Event
>>> x = Event.objects.last()
>>> x.date_start = None
>>> x.save()

saving submission.created_utc value and saving in django models.DateTimeField

Having an issue grabbing the submission.created_utc value and trying to store it in my django models.DateTimeField.
// here's my model's DateTimeField
red_created = models.DateTimeField(default=timezone.now, editable=False)
// this is how I try to save it
red_created = returnUtcDate(submission.created_utc)
// value of created_utc = 1589720741.0
def returnUtcDate(utcDate):
dt = datetime.fromtimestamp(int(utcDate))
newUtcDate = timezone.make_aware(dt, timezone.utc)
return newUtcDate // value being returned 2020-05-17 13:05:41+00:00
When I try to run that I get:
TypeError: expected string or bytes-like object
I know I need to convert the utc date before I store it but I don't know how or to what format. Tried searching but I'm assuming searching for the wrong terms.

Django CharField equal to evaluation

I have a model with Field like
key = CharField(max_length=100, blank=True)
when i check for the value after form submission like this.
if self.key is None:
the condition fails
But when i check for if self.key == '' it works.
My question is why it doesn't works when i evaluate it to None and works when i use ''.
The None condition works only when i assign the values like this.
key = CharField(max_length=100, null=True ,blank=True)
I read some posts where it states that when evaluating the CharField as blank=True an empty string '' is saved but they didn't shed any light why it does that. because as far i understand it should save a Null value.
null = True
is about database which means you can have an object from your model that the value of field is null.
blank= True
is about django forms and means when you fill a modelForm of this model you can pass empty string and its not necessary to fill this field in your form.
So when you add null = True for the objects that have no value for key in the database key is null and in consequence if self.key is None works but when you remove this option for the objects in the database that have no value for key in database the key is '' so your condition is not True.

unable to validate datetime field

I'm unable to validate datetime field. Is there something I missed?
from django import forms
class A(forms.Form):
a = forms.DateTimeField(widget=forms.DateTimeInput(format=('%Y-%m-%dT%H:%M')))
data = {'a':"2007-03-04T21:08"}
a = A(data)
print a.is_valid()
-> False
print a.errors
-> {'a': [u'Enter a valid date/time.']}
solution:
class A(forms.Form):
a = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'])
You've specified the format parameter to the widget, which describes how the existing value should be displayed. You need to provide the input_formats parameter to the field itself, which determines how the data is accepted.

How to save an empty datefield in django

I have an optional datefield in my form, when I save it and it's empty I got the validation error about the invalid format.
In my model, I wrote blank=True and null=True.
Model :
created = models.DateTimeField(blank=True,null=True)
Form :
class XxxForm(forms.ModelForm):
created=forms.DateField(required=False)
class Meta:
model = Xxx
Error :
u"" value has an invalid format. It must be in YYYY-MM-DD HH:MM format
Update :
I found the solution which is :
created = request.POST['created']
if not created:
created = None
It works that way ! thanks everyone
You need to use a DateTimeField in the form, not a DateField.
[EDIT]
Also try to drop created=forms.DateField(required=False) from your form declaration. It is not needed there since you have it in the model already.