Thursday, October 28, 2010

Re: Import csv file in admin

>
> Hang on, what you're doing here is repeatedly setting the data values
> for each line to the *same* form_input model. Presumably what you
> actually want to do is to create new Data instances for each line in
> the CSV, with the place set to the value of the form.
>
> In this case, I'd recommend not to bother with a ModelForm at all.
> Instead, just use a standard Form, and create new Data instances in
> your for loop:
>
> class DataInput(forms.Form):
>     file = forms.FileField()
>     place = forms.ModelChoiceField(queryset=Places.objects.all())
>
>     def save(self):
>          records = csv.reader(self.cleaned_data[file])
>          for line in records:
>              data_obj = Data()
>              data_obj.time = datetime.strptime(line[1],
>                                        "%m/%d/%y %H: %M: %S")
>              data_obj.data_1 = line[2]
>              data_obj.data_2 = line[3]
>              data_obj.data_3 = line[4]
>              data_obj.save()
>
> --
> DR.

Daniel

The idea of using a form becomes a problem, because to replace the
standar modelform inside the admin with ModelAdmin.form i need another
modelform, according to this:
http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#adding-custom-validation-to-the-admin.
If there's any way to replace a modelform with a standar form inside
the admin view, i will appreciate some ideas.

When i replace the modelform with a standar form, arrise an
ImproperlyConfigured bug: DataAdmin.form does not inherit from
BaseModelForm at admin.py: admin.site.register(Data, DataAdmin)

But anyways i take your point of create new data instances inside the
for loop:

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

However i still got the AttributeError: 'NoneType' object has no
attribute 'save'.

Regards!

--
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.

No comments:

Post a Comment