value has an invalid date format. It must be in YYYY-MM-DD format
Question:
I am new to python and django. I was trying to make a todo app but i got error in my date field. I’ve tried searching in google for solutions but I couldn’t get a solution for my problem.
models:
class Task(models.Model):
name = models.CharField(max_length=250)
priority = models.IntegerField()
date = models.DateField(blank=True,null=True)
def __str__(self):
return self.name
views.
def demo(request):
task1 = `Task.objects.all()
if request.method == 'POST':
name = request.POST.get('task', '')
priority = request.POST.get('priori`ty', '')
date = request.POST.get('date', '')
task = Task(name=name, priority=priority, date=date)
task.save()
return render(request, 'index.html', {'task1': task1})
# def details(request):
return render(request, 'detail.html', {'task': task})
Answers:
As defined in the model, the date could be null, in which case, depending on the date returned by the request, if it is null, it returns an empty string. But django accepts None, but not "".
Maybe it’s a date format problem. Note that we don’t see the left of the error message, that’s where it shows what’s causing it.
In the view, below the next line:
date = request.POST.get('date', '')
the following could work:
formatted_date = None if date == '' else datetime.strptime(date, '%Y-%m-%d') # (ISO-8601) Replace with the appropiate format
I am new to python and django. I was trying to make a todo app but i got error in my date field. I’ve tried searching in google for solutions but I couldn’t get a solution for my problem.
models:
class Task(models.Model):
name = models.CharField(max_length=250)
priority = models.IntegerField()
date = models.DateField(blank=True,null=True)
def __str__(self):
return self.name
views.
def demo(request):
task1 = `Task.objects.all()
if request.method == 'POST':
name = request.POST.get('task', '')
priority = request.POST.get('priori`ty', '')
date = request.POST.get('date', '')
task = Task(name=name, priority=priority, date=date)
task.save()
return render(request, 'index.html', {'task1': task1})
# def details(request):
return render(request, 'detail.html', {'task': task})
As defined in the model, the date could be null, in which case, depending on the date returned by the request, if it is null, it returns an empty string. But django accepts None, but not "".
Maybe it’s a date format problem. Note that we don’t see the left of the error message, that’s where it shows what’s causing it.
In the view, below the next line:
date = request.POST.get('date', '')
the following could work:
formatted_date = None if date == '' else datetime.strptime(date, '%Y-%m-%d') # (ISO-8601) Replace with the appropiate format