Django admin upload multiple images in 1 form
I dont want to use inlines so I figured I want to upload a bunch of images at the same time. Now I've been struggling for an entire day to get it working but it doesn't for some reason.
My first code:
Model
class LaptopInfoImages(models.Model):
laptop_info = models.ForeignKey(LaptopInfo, on_delete=models.CASCADE)
image = models.ImageField(upload_to=images_directory)
admin
class LaptopInfoImagesForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = LaptopInfoImages
fields = '__all__'
def save(self, commit=True):
instance = super().save(commit=False)
for image in self.cleaned_data['image']:
image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=image)
image_obj.save()
if commit:
instance.save()
return instance
This gives me the error:
AttributeError: 'bytes' object has no attribute '_committed'
So I changed the code to:
admin
class LaptopInfoImagesForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta:
model = LaptopInfoImages
fields = '__all__'
def save(self, commit=True):
instance = super().save(commit=False)
for image in self.cleaned_data['image']:
# Convert the image to a BytesIO object
bytes_io = BytesIO(image)
# Create an InMemoryUploadedFile from the BytesIO object
in_memory_file = InMemoryUploadedFile(
bytes_io, None, 'image.jpg', 'image/jpeg', len(image), None
)
# Save the image to the LaptopInfoImages model
image_obj = LaptopInfoImages(laptop_info=instance.laptop_info, image=in_memory_file)
image_obj.save()
if commit:
instance.save()
return instance
It doesnt give me any errors but it is uploading 9332 laptop info imagess and the images don't work.