[Django]-Save Multiple Files from Django Forms to Model

7👍

Here is a way that worked for me. I loop each occurrence of an InMemoryUploadedFile in request.FILES and re-assign it back onto request.FILES, then save each one by one.

forms.py

class PhotosForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta:
        model = Photos
        fields = ['file']

views.py

def photos(request):
    photos = Photos.objects.all()
    if request.method == 'GET':
        form = PhotosForm(None)
    elif request.method == 'POST':
        for _file in request.FILES.getlist('file'):
            request.FILES['file'] = _file
            form = PhotosForm(request.POST, request.FILES)
            if form.is_valid():
                _new = form.save(commit=False)
                _new.save()
                form.save_m2m()
    context = {'form': form, 'photos': photos}
    return render(request, 'app/photos.html', context)
👤Sazzy

Leave a comment