How to create multiple instances for initializing a FileField with "multiple" option on?

Hello,
I read the offical documentation, searched the Internet but I’m still having trouble creating an edit view for a filefield (with “multiple” option in widgets on) using modelform.
I have created the following models:

class News(models.Model):
    title = models.CharField(max_length=1000, unique=True)

    def __str__(self):
        return self.title


class NewsImages(models.Model):
    news = models.ForeignKey(News,
                             null=True,
                             blank=True,
                             on_delete=models.CASCADE)
    image_content = models.ImageField(blank=True,
                                      null=True,
                                      upload_to='img/%Y/%m/%d/',
                                      storage=news_storage)

And my forms are as follows:

class NewsForm(forms.ModelForm):
    class Meta:
        model = News 
        fields = ['title',]


class NewsImageForm(forms.ModelForm):
    class Meta:
        model = NewsImages
        fields = ['image_content',]
        widgets = {
            'image_content': forms.ClearableFileInput(attrs={'multiple': True})
        }

I figure out how to write the creation view, but have trouble with the edit view:

@login_required
def news_create_view(request, id=None):
    images = request.FILES.getlist('image_content')

    form = NewsForm(request.POST or None)
    image_form = NewsImageForm(request.POST or None, request.FILES or None)

    context = {
        "form": form,
        "imageform": image_form,
        "created": False,
    }

    if form.is_valid() and image_form.is_valid():
        news_obj = form.save()
        context['created'] = True
   
        if images:
            for image in images:
                NewsImages.objects.create(news=news_obj, image_content=image)

        return redirect('/news/manage/')
    return render(request, "news/create.html", context=context)


@login_required
def news_edit_view(request, id):
    images = request.FILES.getlist('image_content')
    news_to_edit = get_object_or_404(News, pk=id)
    images_to_edit = NewsImages.objects.filter(news=news_to_edit)

    form = NewsForm(request.POST or None, instance=news_to_edit)
    image_form = NewsImageForm(request.POST or None, request.FILES or None, instance=???)

I cannot pass multiple objects to parameter “instance”, I wonder how I can do this / bypass this using modelform. Please help me :slight_smile:

A single instance of a FileField can store one image.

If you need to store multiple images, you need to create multiple instances of your NewsImages model - one for each image.

You then need to process the submission as a regular form, not a model form and build your NewsImages instances from the form data submitted.

1 Like

Thank you for your answer! I’ll try using a regular form.