0

The code is simply to upload CVS file and convert data to a LIST.

When users upload a csv file, the filename individual users use is not enforced. I will like to be able to work with any filename users uses for the csv file.

I am getting this error:

File "views.py", line 35, in upload_file phone_list = handle_uploaded_file(request.FILES['phonelistfile'])

File "views.py", line 17, in handle_uploaded_file with open(settings.MEDIA_URL+'documents/'+str(filename),'wb') as destination:

NameError: name 'filename' is not defined

Views.py

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponseRedirect
from .models import Upload
from .forms import UploadFileForm 
import csv
import io

# Imaginary function to handle an uploaded file.
#from somewhere import handle_uploaded_file

def handle_uploaded_file(f):
    with open(settings.MEDIA_URL+'documents/'+str(filename),'wb') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
    #csvfile = f
    csvfile = io.TextIOWrapper(f) # Python 3 Only
    #dialect = csv.sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024))
    dialect = csv.sniffer().sniff(csvfile.read(1024), delimiter=";,")
    #csvfile.open()
    csvfile.seek(0)
    #csvreader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect)
    csvreader = csv.reader(csvfile, dialect)
    return list(csvreader)

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            phone_list = handle_uploaded_file(request.FILES['phonelistfile'])
            upload_phone_list = Upload()
            upload_phone_list.name = request.name
            upload_phone_list.phonelistfile = request.FILES['file'].file
            upload_phone_list.phonelist = phone_list
            #form.save()
            upload_phone_list.save()

            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})

models.py

from django.db import models
#from django.forms import ModelForm
from django.db import models
from django.contrib.postgres.fields import ArrayField

class Upload(models.Model):
    name = models.CharField(max_length=50)
    phonelistfile = models.FileField("phonelistfile", upload_to="media/%Y/%m/%d/")
    upload_date = models.DateTimeField(auto_now_add =True)
    phonelist = ArrayField(models.TextField())

Forms.py

from django import forms
from .models import Upload
from django.forms import ModelForm

# FileUpload form class.
class UploadFileForm(ModelForm):
    #name = forms.CharField(max_length=100)
    #phonelistfile = forms.FileField("phonelistfile", allow_empty_file=True, required=False)
    class Meta:
        model = Upload
        fields = ('name', 'phonelistfile')

Answered: I have been able to find the answer. Now, I can get the filename of the CSV file uploaded by users by adding the code below; thereby collapsing the two functions in views.py into one using:

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            fil = request.FILES['phonelistfile']
            with open('f', 'wb+') as destination:
                for chunk in fil.chunks():
                    destination.write(chunk)
                    destination.close()
            csvfile = io.TextIOWrapper(open('f', 'rb')) # Python 3 Only
            #Do something with he file....   

This does the trick.... - fil = request.FILES['phonelistfile']

1 Answer 1

1

In the following line, you never define what filename is:

with open(settings.MEDIA_URL+'documents/'+str(filename),'wb') as destination:

Django has no idea what that is. You need to set it as a value somewhere.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Jade. I agree. But how do I write the code in such a way that the filename is not explicitly stated, since my users can use any name for their csv file for upload.
@Divino I'm assuming the f variable passed into your function is the file? If yes, instead of str(filename), you can do str(f.name).
@Jade, I will try that.
I have been able to find the answer. By collapsing the two functions in views.py into one using:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.