【问题标题】:Django : Files not passed in the request even after setting enctype=multipart/form-data?Django:即使在设置 enctype=multipart/form-data 之后,文件也没有在请求中传递?
【发布时间】:2019-10-06 11:07:26
【问题描述】:

我有一个动态生成的表单。输入类型可以是文件、文本和表格(使用夏季注释)。当我尝试将此表单数据传递给我的 Django 视图处理程序时,未收到文件数据。

request.FILES 为空。

这是我进行 Ajax 调用的 Javascript 函数 -

function saveTagInputs() {
  //   debugger;
  formData.append(getTagName[getTagId], $("#" + getTagId).get(0).files[0]);
  formData.append("tagdict", JSON.stringify(tagDict));
  formData.append("tagnames", JSON.stringify(getTagName));
  formData.append("tempid", tempData.selectedTemp);

  var $thisURL = window.location.href;
  if ($thisURL.charAt($thisURL.length - 1) == "#") {
    // alert("");
    $thisURL = $thisURL.substring(0, $thisURL.length - 1);
  }

  for (var pair of formData.entries()) {
    console.log(pair[0] + ", " + pair[1]);
  }
  //ajax call passing template id's and taginput dictionary containing tag id and it's value
  $.ajax({
    url: $thisURL + "savetaginput/",
    type: "POST",
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    success: function(data) {
      console.log("Tags saved successfully !");
    }
  });
  debugger;
}

当我在控制台中记录这些数据时,这会显示在文件输入字段中-

profile_image,[目标文件]

其中 profile_image = 输入字段的名称,目标文件是文件...

现在,当我将此 ajax 调用传递给我的 Django 时,我会查看我的请求。 FILES 为空。

这是我的 Django 视图 -

def generate_taginputs(request):
    if request.method == "POST":
        #get temp id and tag inputs from the request
        # import pdb; pdb.set_trace()
        files = request.FILES
        tempid = request.POST['tempid']
        taginputs = json.loads(request.POST['tagdict'])
        tagnames = json.loads(request.POST['tagnames'])

        print(tempid, taginputs)
        #load the template from id
        template = Dtemplates.objects.filter(id=tempid)
        temp_jsn = json.loads(serializers.serialize('json', template))
        print(temp_jsn)

        #save each tag input value along with it's section, template and user id
        for key, value in taginputs.items():
            tag = Snotetags.objects.get(id=key)
            # tag_jsn = json.loads(serializers.serialize('json', tag))
            if value[1] == 'file':
                try:
                    section = Dsections.objects.get(tags=tag)
                    taginput = TagInputs(
                        user=request.user.id,
                        template_id=tempid,
                        section_id=section.id,
                        tag_id=key,
                        value=request.FILES[tagnames[key]])
                    taginput.save()
                    print('Input data saved succesfully')

                except:
                    print('tag not from this section')
            try:
                section = Dsections.objects.get(tags=tag)
                print(section)
                taginput = TagInputs(
                    user=request.user.id,
                    template_id=tempid,
                    section_id=section.id,
                    tag_id=key,
                    value=value[0])
                print(taginput)
                taginput.save()
                print('Input data saved succesfully')
            except:
                print('tag not from this section')

        return JsonResponse({'message': 'success'})

供参考,这是 HTML 格式 -

<form method="POST" enctype="multipart/form-data" id="taginputdata">
                            <input type="hidden" name="csrfmiddlewaretoken" value="h2O7NBSuw7UgfFswEQtyq3tGj5kaVJdQdBnuENMjo3yePRiliH34KNhvoCycya44">
                            <div id="tag_inputs"><input class="tagInputs" type="file" id="5" name="profile_image" onchange="enableTxt(this)"> 
 <label>@profile_image</label> 

        <input class="tagInputs" type="text" id="4" name="price" onchange="enableTxt(this)"> 
         <label>@price</label>
        <button class="btn btnList" onclick="saveTagInputs()">Save Inputs</button></div>

【问题讨论】:

    标签: javascript python html django django-views


    【解决方案1】:

    想象这是你的文件,,,

    <input type="file" name="image" id="image" />
    

    现在,,,

    $('#someelement').click(function() {
    
            var image = $('#image')[0].files[0]; // this will return your image object
            var form = new FormData();
            form.append('image', image);
            console.log('fire');
    
            $.ajax({
                url: '<your_url>',
                method: 'POST',
                data: form,
                processData: false,
                contentType: false,
                success: function(result) {
    
                }
            })
        })
    

    在服务器上,您的request.FILES 将被InMemoryUploadedFile 对象填充。这就是你想要的。 (恕我直言)。

    【讨论】:

    • 我应用了这个线程中显示的方法 - stackoverflow.com/questions/20822823/…
    • 您的建议会产生更多错误,例如 - AttributeError: 'NoneType' object has no attribute 'decode' 好几次......
    • 我更新了我的答案,,它对我来说 100% 有效。希望对你有帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2023-04-01
    • 2023-04-03
    相关资源
    最近更新 更多