Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload multiple files to a model field?

Tags:

I want to upload multiple files through a ModelForm,with all files to be assigned to a file field of the Model.I have gone through the docs and I saw an example on it and I ve implemented it here but I can only get my form to pick multiple files but only one get saved and assigned to filesfield.Below are my codes

models.py

class Feed(models.Model):     user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='feeds')     text=models.TextField(blank=False,max_length=500)     files = models.FileField(upload_to="files/%Y/%m/%d") 

forms.py

class FeedForm(ModelForm):     class Meta:         model=Feed         fields=('text','auth','files')         widgets={"files":forms.FileInput(attrs={'id':'files','required':True,'multiple':True})} 

and views.py

def post_feed(request):     form_class = FeedForm     if request.method == 'POST':         form = form_class(request.POST,request.FILES)         if form.is_valid():             feed = form.save(commit=False)             feed.user = User.objects.get(pk=1)             feed.pub_date=timezone.now()             #instance = Feed(files=request.FILES['files'])            # feed.files=request.FILES['files']             feed.save()             return redirect('home')     else:         form = form_class()         return render(request, 'post_feed.html', {'form': form,})  from django.views.generic.edit import FormView from .forms import FeedForm  class FileFieldView(FormView):     form_class=FeedForm     template_name='post_feed.html'  '''success_url=???   #I dont know what to write here.I thought of putting this render(request, 'post_feed.html', {'form': form,}) because I just want  to reload the page but it gave an error,so I removed it entirely.'''      def post_feed(self,request,*args,**kwargs):         form_class=self.get_form_class()         form=self.get_form(form_class)         filez=request.FILES.getlist('files')         if form.is_valid():             for f in filez:                 f.save()             return self.form_valid(form)              else:             return self.form_invalid(form)  

Kindly help me out,Thanks in advance.

like image 646
Bolaji Avatar asked Jul 08 '16 00:07

Bolaji


People also ask

Does Python Django support multiple file upload?

The Django documentation for File Uploads, gives a brief understanding of the workflow of how to upload a single file using forms and importing in views. In a similar way, we can also tweak it to upload multiple files using forms and views.

How do I upload multiple documents to one field?

What can I do? To upload multiple documents to one field, you will need to combine multiple documents into one file. Text documents: Copy the text from all files into a single document. If you are including photos, use the “Insert picture” function instead of “Copy/Paste”.

How many PDF files can I upload per field?

When you save a PDF file, use a low resolution (96 dpi) to keep the document under 4MB. You can only upload one 4MB file per field. If you try to upload multiple files in the same field, only one will be saved. Was this answer useful? Thank you for your feedback.

Is it possible to add a file type field in PowerApps?

If you want to add a File type field in your CDS Entity, and want to upload file within your Model-Driven app through this File type field, I afraid that there is no way to achieve your needs in PowerApps currently. Currently, the File data type is only available to canvas apps and flows. Please check the following article for more details:

Should I use filefield or imagefield?

You can change FileField to ImageField it’s up to you since this tutorial covers multiple files and images, FileField is probably the right choice for now.


2 Answers

You have to create a separate model for the files and connect them with a foreign key:

class Feed(models.Model):     user=models.ForeignKey(User, on_delete=models.CASCADE, related_name='feeds')     text=models.TextField(blank=False, max_length=500)   class FeedFile(models.Model):     file = models.FileField(upload_to="files/%Y/%m/%d")     feed = models.ForeignKey(Feed, on_delete=models.CASCADE, related_name='files') 

I hope this helps.

like image 108
Carlos Mermingas Avatar answered Nov 02 '22 05:11

Carlos Mermingas


Phew, it took me a whole day to figure out this. My goal was to assign multiple files to one instance of a class, like a Blog instance can have multiple Images. First things first, you cannot do this with one models.FileField inside a model (for example inside Blog class), because this field was not designed to save multiple files. So the solution is to create separate model for the files and connect them with One-to-Many Relationship (Foreign Key) as it was answered by @Carlos Mermingas. Enough words, here is the code for the above situation:

# models.py class Feed(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) text=models.TextField(blank=False, max_length=500)  class FeedFile(models.Model): file = models.FileField(upload_to="files/%Y/%m/%d") feed = models.ForeignKey(Feed, on_delete=models.CASCADE)  # forms.py ... from django.forms import ClearableFileInput ... class FeedModelForm(forms.ModelForm):     class Meta:         model = Feed         fields = ['text']  class FileModelForm(forms.ModelForm):     class Meta:         model = FeedFile         fields = ['file']         widgets = {             'file': ClearableFileInput(attrs={'multiple': True}),         }         # widget is important to upload multiple files  # views.py from .models import FeedFile ... def create_to_feed(request):     user = request.user     if request.method == 'POST':         form = FeedModelForm(request.POST)         file_form = FileModelForm(request.POST, request.FILES)         files = request.FILES.getlist('file') #field name in model         if form.is_valid() and file_form.is_valid():             feed_instance = form.save(commit=False)             feed_instance.user = user             feed_instance.save()             for f in files:                 file_instance = FeedFile(file=f, feed=feed_instance)                 file_instance.save()     else:         form = FeedModelForm()         file_form = FileModelForm()      # the rest is the basic code: template_name, context, render etc.   # in your template.html <form> tag must include enctype="multipart/form-data" 

Bonus: if you want to see uploaded files in admin panel, you can use InlineModelAdmin objects. Here is the code:

# admin.py of your app from django.contrib import admin from .models import Feed, FeedFile  class FeedFileInline(admin.TabularInline):     model = FeedFile   class FeedAdmin(admin.ModelAdmin):     inlines = [         FeedFileInline,     ]  admin.site.register(Feed, FeedAdmin) 

For the more details on file upload, Model Forms, how to include widget in Model Form

like image 29
karjaubayev Avatar answered Nov 02 '22 04:11

karjaubayev