André Luiz
André Luiz

Reputation: 7282

Django - how to import from a .csv file in memory

I'm writing a page to upload a .csv file and import its content into my models. My current view:

class ContentImport(LoginRequiredMixin, PermissionRequiredMixin,View):
    permission_required = 'delivery.change_delivery' 

    def get(self, request, *args, **kwargs):             
        form = UploadFileForm()
        return render(request, 'delivery/content_import.html', { 'form': form })    

    def import_contents(self, f):
        reader = csv.reader(f)
        for row in reader:
            print row[0] 

    def post(self, request, *args, **kwargs):

        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            self.import_contents(request.FILES['file'].read())
            messages.add_message(self.request, messages.SUCCESS, "Contents deleted successfully.")
            return redirect(reverse('delivery:delivery-detail', args=[self.kwargs['delivery_id']])) 
        else:
            messages.add_message(self.request, messages.ERROR, "Select a file to upload.")
            return redirect(reverse('delivery:delivery-content-import', args=[self.kwargs['delivery_id']])) 

My question is about the import_contents method and the call for it self.import_contents(request.FILES['file'].read()). When I print row[0] I get the following error: list index out of range.

My idea with this view is to upload a file, not saving it in the server, read the .csv from the memory and create new records in my models. This read from .csv I got from other answers here in stackoverflow.

I think the problem is how I pass the file to the import_contents function or how I read from it. I just can't figure out. Can you help me? If you have a suggestion on how to do it in an easier way, or the right way, let me know.

Thanks for any help

Upvotes: 0

Views: 2135

Answers (1)

zEro
zEro

Reputation: 1263

This is your problem.

self.import_contents(request.FILES['file'].read())

csv.reader() expects a file like object, not its content.

This can definitely be construed as a related answer.

Upvotes: 3

Related Questions