4

我需要上传并读取 CSV,然后保存到数据库。我是一个初学者,下面是我到目前为止使用'django-adaptors'(http://django-adaptors.readthedocs.org/en/latest/index.html)所取得的成就我知道它不是很多,但我'我这样做是为了了解更多信息:)

我在代码的视图中苦苦挣扎(如下)。我不知道如何上传然后将文件读入 CodeCSvModel() 函数?谁能帮忙解释一下?非常感谢。:)

视图.py

from django.template import RequestContext
from django.shortcuts import render_to_response
from web.forms import codeUploadForm
from web.csvTools import CodeCSvModel


def codeImport(request):
    # If we had a POST then get the request post values.
    if request.method == 'POST':
        form = codeUploadForm(request.POST, request.FILES)
      # handle_uploaded_file(request.FILES['file'])

                ====[HELP HERE]=====

        #form = codeUploadForm(request.POST)

        CodeCSvModel.import_from_file(form['file'])



    else:
         form = codeUploadForm()
         context = {'form':form}
         return render_to_response('import.html', context, context_instance=RequestContext(request))  

表格.py

class codeUploadForm(forms.Form):

    file = forms.FileField()
    place = forms.ModelChoiceField(queryset=Incentive.objects.all())

csv工具.py

from datetime import datetime
from adaptor.fields import *
from adaptor.model import CsvModel, CsvDbModel, ImproperlyConfigured,\
    CsvException, CsvDataException, TabularLayout, SkipRow,\
    GroupedCsvModel, CsvFieldDataException
from web.models import *



class CodeCSvModel(CsvModel):

    codeid = CharField()
    remotecode = CharField()
    active = BooleanField()
    created = DateField()
    modified = DateField()
    incentiveid = CharField()

    class Meta:
        delimiter = ";"
        dbModel = Code
4

2 回答 2

5

Django 仅将上传的文件保留在内存中,如果它是 2.5MB 或更小,否则它会写入临时位置。

您缺少的步骤是您实际将文件从内存/临时位置写入某个磁盘的位置,例如

if request.method == 'POST':
    form = MyForm(request.POST, request.FILES)
    if form.is_valid():
        uploaded_file = request.FILES['html-file-attribute-name']

        # Write the file to disk
        fout = open("path/to/save/file/to/%s" % uploaded_file.name, 'wb')
        for chunk in uploaded_file.chunks():
            fout.write(chunk)
        fout.close()

如果文件非常大,分块是要走的路,因为 Django 会在写入磁盘之前将文件的每个块读入内存。如果您改用 read(),它会将整个文件读入内存,因此块是您最好的选择。

于 2013-01-05T01:43:42.693 回答
2

所以这行得通,我几乎就在那里:

 file = request.FILES['file']
        CodeCSvModel.import_from_file(file)
        return render_to_response('import.html', context_instance=RequestContext(request))
于 2013-01-04T17:25:38.287 回答