无法上传多个图像 django - ajax
Posted
技术标签:
【中文标题】无法上传多个图像 django - ajax【英文标题】:cant upload multiple images djago - ajax 【发布时间】:2021-12-07 16:52:22 【问题描述】:我正在尝试使用 ajax 请求上传多张图片,我正在使用 modelformset_factory
上传多张图片,这是我的代码:
class Document(models.Model):
booking =models.ForeignKey(Booking,on_delete=models.PROTECT)
docs = models.ImageField(upload_to=upload_docs)
我的表单.py
class UploadDocumentsForm(forms.ModelForm):
class Meta:
model = Document
fields = ['docs']
我的意见.py
@login_required
def add_new_image(request,id):
obj = get_object_or_404(Booking,id=id)
if request.is_ajax() and request.method == 'POST':
images = UploadDocumentFormSet(request.POST,request.FILES)
if images.is_valid():
for img in images:
if img.is_valid() and img.cleaned_data !=:
img_post = img.save(commit=False)
img_post.booking = obj
img_post.save()
return JsonResponse('success':'success')
else:
messages.error(request,_('error message'))
images = UploadDocumentFormSet(queryset=Document.objects.none())
return render(request,'booking/add_img.html','obj':obj,'images':images)
这是我的模板,包括 html 和 ajax
$('#addButton').click(function()
var form_dex1 = $('#id_form-TOTAL_FORMS').val();
$('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1));
$('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1);
);
const formData = new FormData()
formData.append('csrf',document.getElementsByName('csrfmiddlewaretoken').value);
formData.append('docs0',document.getElementById('id_form-0-docs').files[0]);
formData.append('docs1',document.getElementById('id_form-1-docs').files[0]);
formData.append('docs2',document.getElementById('id_form-2-docs').files[0]);
formData.append('docs3',document.getElementById('id_form-3-docs').files[0]);
const form = document.getElementById('docs-uploader-form')
form.addEventListener("submit",submitHanler);
function submitHanler(e)
e.preventDefault();
$.ajax(
type:'POST',
url:"% url 'booking:add_new_image' id=2222 %".replace(/2222/,parseInt(obj.id)),
data:formData,
dataType:'json',
success:successFunction,
)
function successFunction(data)
// console.log(data)
form.reset();
alertify.success('added new image')
<button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl">
% trans "add new image" %
</button>
<form action="" method="POST" enctype="multipart/form-data" dir="ltr" id="docs-uploader-form">% csrf_token %
% for form in images.forms %
form.id
images.management_form
<div class="form-group mt-3" id="images">
form.docs | add_class:'form-control-file'
</div>
% endfor %
<div class="form-group mt-3" id="formset" style="display: none;">
images.empty_form.docs | add_class:'form-control-file'
</div>
<button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">% trans "submit" %</button>
</form>
请问我有什么需要改变的吗,或者没有更好的方法来实现它吗?先感谢您 。非常感谢您的帮助..
【问题讨论】:
您遇到了什么问题? 我无法保存图片 【参考方案1】:你必须得到这样的文件:
images = request.FILES.getlist('images')
for image in images:
photo = Photo(
name='test',
image=image,
)
photo.save()
【讨论】:
谢谢,但我认为问题不在于它与我认为的 ajax 请求有关【参考方案2】:在您的 ajax 代码中,您错过了将 contentType 和 processData 设置为 false,当您将 FormData 对象与 jQuery.ajax 一起使用时需要这样做
$.ajax(
type:'POST',
url:"% url 'booking:add_new_image' id=2222 %".replace(/2222/,parseInt(obj.id)),
data:formData,
dataType:'json',
processData: false,
contentType: false,
success:successFunction
);
【讨论】:
感谢您的回复,仍然无法正常工作,甚至在我使用preventDefault()
时重新加载页面以上是关于无法上传多个图像 django - ajax的主要内容,如果未能解决你的问题,请参考以下文章