Matthias
Matthias

Reputation: 223

How to upload multiple files in Django

I've been trying to find a solution to add multiple files using a drag and drop form. I'm using Django's Rest API and React.

This is what i have been trying so far but it seems like this will only do for one file at a time:

class FileCollection(models.Model):
    Name = models.CharField(max_length=150, null=True, blank=True)
    Files = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[
        FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])])

How can i make it so i can upload multiple files at once with the rest api? I only found some answers on here regarding images.

Upvotes: 2

Views: 1034

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83517

Since you only show the model in your question, I assume you are asking about how to create a model that stores multiple files. Your current Files field is actually only a single file since you declare it as a FileField. To have multiple files, you need to use multiple FileFields:

class FileCollection(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)
    file1 = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[
        FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])])
    file2 = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[
        FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])])

Now this will have 2 files. If you want an arbitrary number of files, you first need to have a model that stores one file and use a ForeignKey to add that file to a collection:

class FileCollection(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)

class File(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)
    file = models.FileField(upload_to='videos_uploaded', null=True, blank=True, validators=[
        FileExtensionValidator(allowed_extensions=['mp4', 'm4v', 'mov', 'mpg', 'mpg2', 'mpeg'])])
    collection = models.ForeignKey(FileCollection)

If you want to add a file to multiple collections, you can use ManyToManyField instead of ForeignKey.

This only addresses the model since that is all you posted in your question. You will also need to create a view for this. Note that REST API doesn't really allow for file uploads. You will likely need to use a multipart form instead of a REST API.

Side note: fields should start with lower case in python. For example, use name instead of Name.

Upvotes: 2

Related Questions