是否可以使用相同的上传按钮上传多张照片?我知道有一个额外的小部件,您可以向modelformset_factory
添加一定数量的图像,但是我正在寻找一种方法,让用户决定要上传多少张照片。如果我将extra=3
添加到表单集,则一切正常。但我想完全消除这一点。一些用户想要上传3张图片,一些用户想要上传25张图片。
我的观点
def list_home(request):
image_form_set = modelformset_factory(Images, form=ImageForm)
if request.method == "POST":
listing_form = ListingForm(request.POST)
formset = image_form_set(request.POST, request.FILES, queryset=Images.objects.none())
if listing_form.is_valid() and formset.is_valid():
post = listing_form.save(commit=False)
post.user = request.user
post.save()
for form in formset.cleaned_data:
if form:
image = form['image']
photo = Images(listing=post, image=image)
photo.save()
return render(request, 'success.html')
我的表格
ListingForm(forms.ModelForm)类:
class Meta:
model = Listing
exclude = ('user', 'longitude', 'latitude', 'pub_date')
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image', widget=ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = Images
fields = ['image']
我的图片模型
class Images(models.Model):
image = models.ImageField(upload_to=get_image_filename, verbose_name='Image')
listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
def __str__(self):
return str(self.image)
答案 0 :(得分:0)
为什么不以一种形式上传多个文件:
<form action="/pic_upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
<tr>
<td>select file to upload: </td><td><input name="files" type="file" size="50" accept="image/*" multiple> </td><td>
<button type="submit"> Upload </button> </td>
</tr>
</table>
</form>
然后查看功能应类似于:
def pic_upload(request):
for afile in request.FILES.getlist('files'):
if afile.content_type not in ("image/png","image/jpeg"):
continue
pic = Images()
pic.image= afile
pic.save()
return redirect(......)