Please help! I uploaded multiple images but got only one

I uploaded multiple images but can only get one image upload instead of the multiple images and when i printed out in my console, i can see only one image and also i printed out my form validation and it says that my form is not valid.

Here are my codes;

models.py

from django.db import models

class ImageUpload(models.Model):
image = models.FileField(upload_to=‘images/’)
uploaded_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
  return f"Image uploaded at {self.uploaded_at}"

views.py

from django.shortcuts import render, redirect
from .forms import ImageUploadForm
from .models import ImageUpload

def upload_images(request):
if request.method == ‘POST’:

form = ImageUploadForm(request.POST, request.FILES)
images = request.FILES.getlist('image')

if form.is_valid():
  print('Valid Form')
else:
  print('Form not Valid')
  
for img in images:
  print(img)
  ImageUpload.objects.create(image=img)
  return redirect('upload_images')

else:
form = ImageUploadForm()

images = ImageUpload.objects.all()
return render(request, ‘upload_images.html’, {‘form’: form, ‘images’: images})

forms.py

from django import forms
from .models import ImageUpload

class ImageUploadForm(forms.ModelForm):

image = forms.FileField(widget=forms.ClearableFileInput(attrs={‘multiple’: False})),

class Meta:
model = ImageUpload
fields = [‘image’]

upload_images.html

Upload Images

Upload Images

<form action="" method="post" enctype="multipart/form-data">
  
  {% csrf_token %}
  
  {{form.as_p}}

  <button type="submit">Submit</button>
</form>


<h2>Uploaded Images</h2>
<div>
    {% for image in images %}
      <img src="{{ image.image.url }}" alt="Image" style="max-width: 200px;"/>
    {% endfor %}
</div>

Please format your code properly and post your validation errors. Also, here is a helpful read for your to understand multiple image upload with django https://coffeebytes.dev/en/how-to-upload-multiple-images-in-django/

1 Like

models.py

from django.db import models

class ImageUpload(models.Model):
  image = models.FileField(upload_to='images/')
  uploaded_at = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return f"Image uploaded at {self.uploaded_at}"

views.py

from django.shortcuts import render, redirect
from .forms import ImageUploadForm
from .models import ImageUpload

def upload_images(request):
  
  if request.method == 'POST':
    
    form = ImageUploadForm(request.POST, request.FILES)
    images = request.FILES.getlist('image')

    if form.is_valid():
      print('Valid Form')
    else:
      print('Form not Valid')
      
    for img in images:
      print(img)
      ImageUpload.objects.create(image=img)
      return redirect('upload_images')
   
  else:
    form = ImageUploadForm()
    
  images = ImageUpload.objects.all()
  return render(request, 'upload_images.html', {'form': form, 'images': images})

forms.py

from django import forms
from .models import ImageUpload

class ImageUploadForm(forms.ModelForm):

  image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': False})),

  class Meta:
    model = ImageUpload
    fields = ['image']
    

upload_images.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Upload Images</title>
</head>
<body>
  <h1>Upload Images</h1>
    
  <form action="" method="post" enctype="multipart/form-data">
      
    {% csrf_token %}

    {{form.as_p}}

    <button type="submit">Submit</button>

  </form>


  <h2>Uploaded Images</h2>
  
  <div>
    {% for image in images %}
      <img src="{{ image.image.url }}" alt="Image" style="max-width: 200px;"/>
    {% endfor %}
  </div>
</body>
</html>

validation Error Messages from the terminal

[22/Sep/2024 16:09:28] "GET /media/images/agent-1.jpg HTTP/1.1" 304 0
Form not Valid------(This is the validation error i set from the views)
mini-testimonial-2.jpg-------(uploaded only one image)

Your multi-image field can’t be the model field, it’s not one model. The file upload field must be a regular form field, and then you create the multiple instances of that model from the images in that field.

Also see the rest of the requirements with the example at File Uploads | Django documentation | Django

Thanks for your answer and I really appreciate. Please, make me understand better by providing the right code needed :pray:

I would really appreciate the more

Did you read any of the links we sent?!

Try to remove the extra comma after the image field definition:

and post your error or your question here. :slight_smile:

1 Like

Please, am still battling with this multiple uploads even after i formatted my pc and reinstalled everything from anew.

I keep getting this ValueError: ValueError: ClearableFileInput doesn’t support uploading multiple files.

views.py

from django.shortcuts import render, redirect
from .forms import ProductForm, ProductImageForm
from .models import Product, ProductImage


# Create your views here.

def homepage(request):
    products = Product.objects.all()
    productImages = ProductImage.objects.all()

    context = {
        'products': products,
        'productImages': productImages
    }
    return render(request, 'home.html', context)


def create(request):
    if request.method == 'POST':
        product_form = ProductForm(request.POST)
        image_form = ProductImageForm(request.POST, request.FILES)
        if product_form.is_valid() and image_form.is_valid():
            product = product_form.save()
            images = request.FILES.getlist('image')  # Get the list of uploaded images
            for img in images:
                ProductImage.objects.create(product=product, image=img)
            return redirect('homepage')
    else:
        product_form = ProductForm()
        image_form = ProductImageForm()

    return render(request, 'create.html', {'product_form': product_form, 'image_form': image_form})


def details(request):
    return render(request, 'details.html')

models.py

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self):
        return self.name


class ProductImage(models.Model):
    product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='product_images/')
    description = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return f"Image for {self.product.name}"

forms.py

from django import forms
from .models import Product, ProductImage

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'description']

class ProductImageForm(forms.ModelForm):
    image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = ProductImage
        fields = ['image', 'description']

Error from my terminal

  File "C:\Users\Stanley\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\forms\widgets.py", line 425, in __init__
    raise ValueError(
    ...<2 lines>...
    )
ValueError: ClearableFileInput doesn't support uploading multiple files.

Please help!!!

The docs show how to create a subclass of forms.ClearableFileInput that allows multiple file uploads: File Uploads | Django documentation | Django

1 Like

Okay thanks…i got it

I viewd the documentation link and got it right. Thanks

In case it helps for future errors, I found that answer by googling for the error message:

ValueError: ClearableFileInput doesn't support uploading multiple files.

And then reading a couple of the first Stack Overflow questions. Always worth a try!

Thanks for your help and also to all the contributors here.