使用Django处理上传的文件

时间:2016-11-17 19:12:50

标签: python django file-upload

我正在尝试使用Django处理上传的CSV文件。我如何执行此操作的主要逻辑在models.pyviews.py脚本中表达。我上传文件后,我无法处理任何内容(在我的views.py中)。这是两个脚本,但如果我能提供更多信息,我会很高兴。

在我的models.py文件中,我有两个类,一个用于文档本身,另一个用于文件中的字段。

models.py:

from django.db import models

import os

class Document(models.Model):
    docfile = models.FileField(upload_to='documents')

class DocumentEntry(models.Model):
    document = models.ForeignKey(Document, on_delete=models.CASCADE)
    field = models.CharField(max_length=250, default="TEST")

接下来,在我的views.py中,我获取通过request.FILES['docfile']上传的文件,并将其传递给handle_files()函数。但是,当我尝试遍历阅读器时,我无法访问上传文件中的任何元素。

views.py:

from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

import csv

from .models import Document, DocumentEntry
from .forms import UploadFileForm


def process_file(request):
    # Handle file upload
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():

            handle_files(request.FILES['docfile'])

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('process_files'))
    else:
        form = UploadFileForm()  # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'upload/process_files.html',
        {'documents': documents, 'form': form}
    )


def handle_files(csv_file):

    newdoc = Document(docfile=csv_file)
    newdoc.save()

    reader = csv.DictReader(open(csv_file))
    for row in reader:
        field = row['field']
        entry = DocumentEntry(document=newdoc, field=field)
        entry.save()

2 个答案:

答案 0 :(得分:2)

<强>更新

这是处理函数的完整示例:

def handle_files(csv_file):

   newdoc = Document(docfile=csv_file)
   newdoc.save()

   with open(newdoc.docfile.name) as f:
      reader = csv.DictReader(f)
      for row in reader:
         field = row['field']
         entry = DocumentEntry(document=newdoc, field=field)
         entry.save()

答案 1 :(得分:1)

open()需要文件的路径,而不是request.FILES['docfile']中包含的实际文件数据。

替换:

reader = csv.DictReader(open(csv_file))

使用:

import io
io_file = io.TextIOWrapper(csv_file.file)
reader = csv.DictReader(io_file)