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 ImagesUpload 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>