2

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this helped a lot. I found out that there is also a multipart parser for DRF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.