Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Multiple File Field

Tags:

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.

like image 979
Dave Avatar asked Jul 17 '12 19:07

Dave


People also ask

What is request files in Django?

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.


2 Answers

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) 
like image 121
MrKsn Avatar answered Nov 13 '22 03:11

MrKsn


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.

like image 41
Yuji 'Tomita' Tomita Avatar answered Nov 13 '22 03:11

Yuji 'Tomita' Tomita