Lelo
Lelo

Reputation: 335

Convert uploaded csv file into list in Django

I'm having a problem when I'm trying to convert the the first column of the uploaded csv file in django into a list. Originally, my code was like this without using django:

with open("export.csv") as f:
    my_list = [row["BASE_NAME"] for row in DictReader(f)]

But when developing the user interface using django, I'm not having the required my_list like above, what am I doing wrong? I tried many methods that you can see in the commented codes:

Here is my view.py:

def handle_csv_data(csv_file):

    logging.warning('Watch out!')  # will print a message to the console
    #print(csv_file)
   # with open(csv_file) as f:
    #    my_list = [row["BASE_NAME"] for row in DictReader(f)]
    users = []
    for row in csv_file:
        users.append(row)

    return (users)

def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)
        if img.is_valid():
            logging.warning('Watch out!')  # will print a message to the console
           # paramFile = request.FILES['pic']
            paramFile =TextIOWrapper(request.FILES['pic'].file).read()
            portfolio1 = csv.DictReader(paramFile)

          #  portfolio = csv.DictReader(request.FILES['pic'].file)
           # csv_file = request.FILES['pic'].file
           # with open(default_storage.path('images/' + "500 clusters.csv"), 'wb+') as destination:
           #     for chunk in csv_file.chunks():
           #         destination.write(chunk)
           # ifile = open("500 clusters.csv", "r")
          #  data = [row for row in DictReader(csv_file.read().splitlines())]
           # print(users)
          #  paramFile = csv_file.read()
          #  portfolio1 = csv.DictReader(paramFile)
            #ifile = open('sample.csv', "r")
            #read = csv.reader(ifile)
            #for row in read:
             #   print(row)
            #data = [row for row in DictReader(csv_file.read().splitlines())]
          #  for row in portfolio:
           #    my_list = [row["BASE_NAME"]]

            #print(my_list)
            portfolio= handle_csv_data(portfolio1)
            print(portfolio)
           # my_list = portfolio

           # return HttpResponseRedirect(reverse('portfolio'))
            return render(request, 'home.html', {'portfolio': portfolio})
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'home.html',{'form':img,'images':images})

Here is my model.py:

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField("pic", upload_to="images/")
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload
    fields = '__all__' 

I appreciate the help.

Upvotes: 4

Views: 1401

Answers (2)

Alex Hall
Alex Hall

Reputation: 36033

The problem with your code is here:

paramFile =TextIOWrapper(request.FILES['pic'].file).read()
portfolio1 = csv.DictReader(paramFile)

DictReader expects an iterable of strings (usually a file object), where each string represents a line. Because you called .read(), paramFileis a string, which is an iterable of strings but each yielded string is a character, not a line. Remove the .read().

Upvotes: 5

Lelo
Lelo

Reputation: 335

   paramFile =io.TextIOWrapper(request.FILES['pic'].file)
   portfolio1 = csv.DictReader(paramFile)
   print(type(paramFile))
    users = []
    users = [row["BASE_NAME"] for row in portfolio1]
    print(len(users))

Somehow I was able to fix it with the above, by looking at the local variables in the local host page.

Upvotes: 0

Related Questions