Tuesday, October 26, 2010

Import csv file in admin

I'm trying to poblate a database with a csv file using the modelform
in Admin site. Here's the files:

Models.py:

class Data(models.Model):
place = models.ForeignKey(Places)
time = models.DateTimeField(blank=True)
data_1 = models.DecimalField(max_digits=3, decimal_places=1,
blank=True)
data_2 = models.DecimalField(max_digits=3, decimal_places=1,
blank=True)
data_3 = models.DecimalField(max_digits=4, decimal_places=1,
blank=True)

Forms.py:

import csv
from datetime import datetime

class DataInput(ModelForm):
file = forms.FileField()

class Meta:
model = Data
fields = ("file", "place")

def save(self, commit=True, *args, **kwargs):
form_input = super(DataInput, self).save(commit=False, *args,
**kwargs)
self.place = self.cleaned_data['place']
self.file = self.cleaned_data['file']
records = csv.reader(self.file)
for line in records:
self.time = datetime.strptime(line[1], "%m/%d/%y %H:%M:
%S")
self.data_1 = float(line[2])
self.data_2 = float(line[3])
self.data_3 = float(line[4])
form_input.save()

test.csv (it's only one line for test purposes, the real file has much
more lines):
1,5/18/10 11:45:00,1.2,2.7,205.

When i put the file got an IntegrityError: datas_data.time may not be
NULL ; and the problem is in Forms.py line: form_input.save()

What i'm missing?!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate