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']