Django上传'文件名'错误

时间:2016-11-10 02:03:09

标签: python django csv

代码只是上传CVS文件并将数据转换为LIST。

当用户上传csv文件时,不会强制执行单个用户使用的文件名。我希望能够使用用户用于csv文件的任何文件名。

我收到此错误:

  

在upload_file中的文件" views.py",第35行       phone_list = handle_uploaded_file(request.FILES [' phonelistfile'])

     

文件" views.py",第17行,在handle_uploaded_file中       打开(settings.MEDIA_URL +' documents /' + str(filename),' wb')作为目的地:

     

NameError:name' filename '未定义

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

回答: 我找到了答案。现在,我可以通过添加以下代码获取用户上传的CSV文件的文件名;从而使用以下方法将views.py中的两个函数折叠为一个:

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....   

这就是诀窍...... - fil = request.FILES [' phonelistfile']

1 个答案:

答案 0 :(得分:0)

在以下行中,您永远不会定义filename是什么:

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

Django不知道那是什么。您需要将其设置为某个值。