我有一个动态生成的表单。输入类型可以是文件、文本和表格(使用夏季笔记)。当我尝试将此表单数据传递给我的 Django View 处理程序时,未收到文件数据。
request.FILES 为空。
这是我的 Javascript 函数进行 Ajax 调用 -
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, [object File]
其中 profile_image = 输入字段的名称,目标文件是文件...
现在,当我将此 ajax 调用传递给我的 Django View 时,我的请求。文件变空。
这是我的 Django View -
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>
最佳答案
想象这是你的文件,,,
<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
对象。这就是你想要的。 (恕我直言)。
关于javascript - Django : Files not passed in the request even after setting enctype=multipart/form-data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56214831/