如何使用django项目上传csv文件

我正尝试在django中创建文件上传。

inventory.html:

我有两个按钮download_inventory按钮下载一个CSV文件。 我正尝试使用upload_inventory按钮上传文件。

<form method="POST" action="{% url 'bulkInventory' %}">
    {% csrf_token %}
        <div class="panel-body">
            <div class="pad-btm form-inline">
                <div class="row">
                    <div class="col-sm-6 table-toolbar-left">
                        <button name="download_inventory" id="download_inventory" class="btn btn-purple btn-labeled fa">Download Inventory</button>
                        &nbsp;&nbsp;
                        <input type="file" class="btn btn-purple" name="inventory_csv" >
                        &nbsp;&nbsp;
                        <button name="upload_inventory" id="upload_inventory" class="btn btn-purple btn-labeled fa dropzone" >Upload Inventory</button>
                    </div>
                    .....

urls.py:

方法bulkInventory与行动bulkInventory映射。

urlpatterns = patterns('',
                    url(r'^$', views.inventory, name='inventory'),
                    url(r'^product.html/', views.product, name='product'),
                    url(r'^update/', views.updateSingle, name='update'),
                    url(r'^inventory/', views.bulkInventory, name='bulkInventory'),)

views.py:

def bulkInventory(request):
    api = APIMethods()
    if request.method == 'POST' and 'download_inventory' in request.POST:
        api.downloadInventory()
        inv_file = open('inventory_sheet.csv', 'rb')
        response = HttpResponse(inv_file, content_type='application/csv')
        response['Content-Disposition'] = "attachment; filename=inventory_sheet.csv"
        os.system('rm inventory_sheet.csv')
        return response

    if request.method == 'POST' and 'upload_inventory' in request.POST:
        form = forms.UploadFile(request.POST, request.FILES)
        print form.is_valid()
        api.saveUploadedInventory(request.FILES['inventory_csv'])    #  this method saves the content of file
        return HttpResponseRedirect(reverse('inventory'))

forms.py:

class UploadFile(forms.Form):
    inventory_file = forms.FileField()

它给了我这个错误:

Traceback:在get_response 132中的文件“/home/manish/syserp/local/lib/python2.7/site-packages/django/core/handlers/base.py”。

响应= wrapped_callback(请求,* callback_args,** callback_kwargs)文件“/home/manish/syserp/ekomerz/inventory/views.py”in bulkInventory 78. api.saveUploadedInventory(request.FILES ['inventory_csv'])File“/ home / manish / syserp / local / lib / python2.7 / site-packages / django / utils / datastructures.py“中的值。raise MultiValueDictKeyError(repr(key))

异常类型:/ product / inventory /中的MultiValueDictKeyError异常值:“'inventory_csv'”


为什么form.cleaned_data[''inventory_csv] form.is_valid()之后去form.cleaned_data[''inventory_csv]

在此之前,检查你得到什么打印form.cleaned_data['inventory_csv']

希望有帮助

链接地址: http://www.djcxy.com/p/55913.html

上一篇: How to upload csv file using django project

下一篇: Upgrade Django and NoReverseMatch password Error