У меня есть форма, которая генерируется динамически. Типы ввода могут варьироваться от файла, текста и таблицы (используя летнюю заметку). Когда я пытаюсь передать эти данные формы моему обработчику представления Django, данные файла не получаются.
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, [объектный файл]
где profile_image = имя поля ввода, а объектный файл - это файл ...
теперь, когда я передаю этот вызов ajax моему 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>