Is there a model field that can handle multiple files or multiple images for django? Or is it better to make a ManyToManyField to a separate model containing Images or Files?
I need a solution complete with upload interface in django-admin.
A view handling this form will receive the file data in request. FILES , which is a dictionary containing a key for each FileField (or ImageField , or other FileField subclass) in the form. So the data from the above form would be accessible as request. FILES['file'] . Note that request.
For guys from 2017 and later, there is a special section in Django docs. My personal solution was this (successfully works in admin):
class ProductImageForm(forms.ModelForm): # this will return only first saved image on save() image = forms.ImageField(widget=forms.FileInput(attrs={'multiple': True}), required=True) class Meta: model = ProductImage fields = ['image', 'position'] def save(self, *args, **kwargs): # multiple file upload # NB: does not respect 'commit' kwarg file_list = natsorted(self.files.getlist('{}-image'.format(self.prefix)), key=lambda file: file.name) self.instance.image = file_list[0] for file in file_list[1:]: ProductImage.objects.create( product=self.cleaned_data['product'], image=file, position=self.cleaned_data['position'], ) return super().save(*args, **kwargs)
No there isn't a single field that knows how to store multiple images shipped with Django. Uploaded files are stored as file path strings in the model, so it's essentially a CharField
that knows how to be converted to python.
The typical multiple image relationship is built as a separate Image model with an FK pointing to its relevant model, such as ProductImage -> Product
.
This setup makes it very easy to add into the django admin as an Inline
.
An M2M field would make sense if you it's truly a many to many relationship where say GalleryImages
are referenced from 1 or more Gallery
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With