How can I upload multiple files in to a Django model?

1.3k Views Asked by At

I'm trying to make an LMS system with Django and now I need to upload multiple pdf files to the curriculum of the class. I can upload one file with the OnetoOne field in the Django model but not more. When I try to add another material for the same class it says Upload materials with this Uploaded class already exists. This is my model code.

class UploadMaterials(models.Model):
    name = models.CharField(max_length=255)
    uploaded_class = models.OneToOneField(Class, on_delete=models.CASCADE, related_name='upload_materials')
    upload_material = models.FileField(upload_to=rename, null=True)

    class Meta:
        verbose_name_plural = "Materials"

I need to upload the materials and be able to view them in the template. like......

{% for material in class.materials %}
<h1>{{ material.name }}</h1>
{% endfor %}

I tried the Django ForeignKey instead of OnetoOne and was able to create multiple materials for the same class but could not figure out how to access them from the template.

What I want to know is how to upload multiple files to the same class and how to access them in the template.

Thank you!

1

There are 1 best solutions below

1
On

You can try insert this pattern on your code:

file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

It's send multiple files upload.

https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/#uploading-multiple-files