如何使用django项目

时间:2015-09-23 10:57:33

标签: python html 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()

它给了我这个错误:

  

回溯:文件   &#34; /home/manish/syserp/local/lib/python2.7/site-packages/django/core/handlers/base.py"   在get_response中     132.

     

response = wrapped_callback(request,* callback_args,** callback_kwargs)File&#34; /home/manish/syserp/ekomerz/inventory/views.py"在bulkInventory中     78. api.saveUploadedInventory(request.FILES [&#39; inventory_csv&#39;])文件&#34; /home/manish/syserp/local/lib/python2.7/site-packages/django/utils/datastructures。 PY&#34;   在 getitem     322.引发MultiValueDictKeyError(repr(key))

     

异常类型:/ product / inventory /中的MultiValueDictKeyError   例外价值:&#34;&#39; inventory_csv&#39;&#34;

1 个答案:

答案 0 :(得分:1)

为什么不在form.cleaned_data[''inventory_csv]

之后使用form.is_valid()

在此之前检查您要打印的内容form.cleaned_data['inventory_csv']

希望得到帮助