1
votes

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

2
I think it should not be form.save(). You want to save every file instead. - Amine Messaoudi
Hi, I searched for another way to save but I can´t find anything different besided form.save(), can you suggest me another way?Thanks for your help - Jorge López
Please check my answer. I'm not sure if it will work or not because I have never dealed with class based forms. - Amine Messaoudi

2 Answers

0
votes

You might need to save every file individually, using FileSystemStorage

from django.core.files.storage import FileSystemStorage
...

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():
                fs = FileSystemStorage()
                for file in files:
                    fs.save(file.name, file)
                return render(request, 'photoadmin/index.html')
            else:
                return self.form_invalid(form)
0
votes

So, this is finally the solution.

views.py

class UploadView(generic.CreateView):
form_class = UploadImages
model = PostSession
template_name = 'photoadmin/upload.html'
success_url = reverse_lazy('upload')

def form_valid(self, form):
    object = form.save(commit=False)
    form.save()
    if self.request.FILES:
        for afile in self.request.FILES.getlist('picture'):
            img = object.images.create(picture=afile)

    return super(UploadView, self).form_valid(form)

with that you are able to iterate

models.py

class PostSession(models.Model):
session_name = models.CharField(max_length=25)

def __str__(self):
    return str(self.session_name)


class Images(models.Model):
    name = models.ForeignKey(
        PostSession, related_name='images', on_delete=models.CASCADE, null=True, blank=True)
    picture = models.ImageField(upload_to='pictures')

Hope this helps the community!