Tuesday, October 23, 2012

Re: Import csv file in admin

On Wednesday, 3 November 2010 09:34:38 UTC+5:30, Jorge wrote:
Jirka & Everybody

Back to basics is always a good advice. With your help and this guy:
http://www.beardygeek.com/2010/03/adding-views-to-the-django-admin/
I can create a form to upload csv files and input their records into
the database.

Short history:

Forms.py:
class DataInput(forms.Form):
    file = forms.FileField()
    place = forms.ModelChoiceField(queryset=Place.objects.all())

    def save(self):
        records = csv.reader(self.cleaned_data["file"])
        for line in records:
            input_data = Data()
            input_data.place = self.cleaned_data["place"]
            input_data.time = datetime.strptime(line[1], "%m/%d/%y %H:
%M:%S")
            input_data.data_1 = line[2]
            input_data.data_2 = line[3]
            input_data.data_3 = line[4]

This form was imported in a view:

@staff_member_required
def import(request):
    if request.method == "POST":
        form = DataInput(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            success = True
            context = {"form": form, "success": success}
            return render_to_response("imported.html", context,
            context_instance=RequestContext(request))
    else:
        form = DataInput()
        contexto = {"form": form}
        return render_to_response("imported.html", context,
            context_instance=RequestContext(request))

And add  the url pattern & some little changes to the admin index
template, and everything works the way i want.

Thanks guys!
 
Hi!
I am using this code but gives errror as " 'DataInput' object has no attribute 'cleaned_data'
Can you please suggest me why this occurs? And the form.is_valid() is not working it always return false.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/toQMoqwWeBQJ.
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