M. Fil
M. Fil

Reputation: 17

Django not accepting parsed csv date input even though it follows the YYYY-MM-DD format. What is the problem?

I'm trying to populate my existing Django model with values from a csv file. I've tried to use datetime.strptime() but it also has not worked.

This is the code I'm trying to run from the Django python manage.py shell loadcsv.py

import csv
from dashboard.models import Checkin
with open('foo.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    for row in csv_reader:
        new_checkin = Checkin(date=row[0],project_id=row[1],manager_id=row[2],user_id=row[3],hours=row[4])
        new_checkin.save()
        # # row[0] = date;
        # # row[1] = project
        # # row[2] = manager
        # # row[3] = user
        # # row[4] = hours
        

models.py (dashboard.models)

from django.db import models

# Create your models here.
class Checkin(models.Model):
    date = models.DateField(blank=False)
    project_id = models.IntegerField(blank=False)
    manager_id = models.IntegerField(blank=False)
    user_id = models.IntegerField(blank=False)
    hours = models.DecimalField(max_digits=5, decimal_places=2)
    

foo.csv sample entry

date,project_id,manager_id,user_id,hours
2019-09-11,134,1,1,3
2019-09-11,201,1,1,5
2019-12-23,14,8,2,0.46
2019-12-23,14,8,2,0.46

The error I'm getting

django.core.exceptions.ValidationError: ['“date” value has an invalid date format. It must be in YYYY-MM-DD format.']

I can save to the database when I manually create a single object in the shell like so:

from dashboard.models import Checkin

new_checkin = Checkin(date="2012-01-01", manager_id="5", project_id="5",user_id="3", hours="0.75")
new_checkin.save()

Upvotes: 0

Views: 71

Answers (1)

Naveen
Naveen

Reputation: 36

You need to skip headers while reading csv. Django is complaining about the header “date” which is not in date format. You can use either next or DictReader to skip headers.

Upvotes: 2

Related Questions