Multiple files upload to a post

Hello! I am trying to upload multiple files to a post but I have an error in models.py:
ValueError: ClearableFileInput doesn’t support uploading multiple files.

models.py:

from django.db import models

# Create your models here.
class Post(models.Model):
    title = models.TextField()
    description = models.TextField()

class PostImage(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to='content/static/images/')

forms.py (Please check PostForm):

from django import forms
from .models import *

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField()

class RegisterForm(forms.Form):
    username = forms.CharField()
    email = forms.EmailField()
    password = forms.CharField()

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            'title',
            'description'
        ]

class PostImageForm(forms.ModelForm):
    forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

views.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from .forms import *
from django.contrib import messages
from django.contrib.auth.models import User

# Create your views here.
def index(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)
        image_form = PostImageForm(request.FILES)
        if post_form.is_valid() and image_form.is_valid():
            post = post_form.save(commit=False)
            post.save()
            for image in request.FILES.getlist('image'):
                new_image = PostImage(post=post, image=image)
                new_image.save()
    else:
        post_form = PostForm()
        image_form = PostImageForm()
    context = {
        'post_form': post_form,
        'image_form': image_form
    }
    return render(request, 'index.html', context)

Welcome @Giorgi-2095 !

Django does not directly handle uploading multiple files in model forms, and does not support multiple files in one file field in a model.

When you accept multiple files being uploaded, it’s up to you to create a separate instance of your PostImage model for each file being uploaded. See the docs and the examples at File Uploads | Django documentation | Django

Using ClearableFileInput only makes sense if you create a formset for the PostImage set of files, with one input form for each file that exists.

1 Like