I have been trying to code a Multi Upload for Images, my code only uploads 1 image even though more than 1 is selected, I don´t know how to iterate through, I did a print once the files were selected and my multiple images selected are printed, but when I save the form it only saves one image.
I basically trying to use the code that appear in the Django documentation.
models.py
class Images(models.Model):
picture = models.ImageField(upload_to='media/photoadmin/pictures')
forms.py
class UploadImages(forms.ModelForm): class Meta: model = Images fields = ('picture',) widgets = {'picture': forms.ClearableFileInput( attrs={'multiple': True})}
views.py
class Upload(FormView):
form_class = UploadImages
template_name = 'photoadmin/upload.html'
success_url = 'photoadmin/'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('picture')
if form.is_valid():
form.save()
for f in files:
file_instance = Images(picture=f)
file_instance.save()
return render(request, 'photoadmin/index.html')
else:
return render(request, 'photoadmin/index.html')
html
{% extends 'base.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p><a href="{% url 'index' %}">Return to home</a></p>
{% endblock %}
This code write in the DB but do not uploads the file to the static folder
form.save()
. You want to save every file instead. - Amine Messaoudi