0

We can save multiple files in one filefield, using multiple attribute in HTML input tag and using request.FILES.getlist() and for loop in views.
This works properly, but the question is:
When we save several files in one filefield of an object,‌ how can we access all of them in templates? I tried the same as the code below but it did not work:

{% for foo in obj.filefield %}
    {{ foo }}
{% endfor %}
  • You can't store multiple files in the same `FileField`. – Willem Van Onsem Oct 13 '20 at 14:50
  • This post explains how to save multiple files in same filefield: https://stackoverflow.com/questions/38257231/how-can-i-upload-multiple-files-to-a-model-field – Mehran Isapour Oct 13 '20 at 14:56
  • as the answer says, you define an extra model, where in the related model, the `FileField` each time stores *one* file. – Willem Van Onsem Oct 13 '20 at 14:57
  • so *no*, it is *not* saving it in the *same* filefield. – Willem Van Onsem Oct 13 '20 at 14:59
  • but all files are stored in the path of a file field of an object. – Mehran Isapour Oct 13 '20 at 15:05
  • no, in the accepted answer, you have a `Feed` model, and a `FeedFile` model. The `FeedFile` links to the `Feed`, and each `FeedFile` carries *one* file. You thus simply construct *multiple* `FeedFile`s that each link to the same `Feed` if you want to store multiple files related to a `Feed` object. The same concept is repeated in the other answers, although with different names, and slightly different details. – Willem Van Onsem Oct 13 '20 at 15:06
  • If you want to upload multiple files using one form field... : https://docs.djangoproject.com/en/3.1/topics/http/file-uploads/#uploading-multiple-files – Mehran Isapour Oct 13 '20 at 15:07
  • exactly, the form field can contain multiple files. But then in the view you see `... # Do something with each file.`, this is where you thus construct the different `FeedFile` objects in the answer. The document thus makes abstraction about how you *process* the uploaded files, and you can not store multiple ones in the same `FileField` of the model. – Willem Van Onsem Oct 13 '20 at 15:08
  • A *form field* deals with handling user input, but it does not deal with storing it in a database record, that is what model field are dealing with. – Willem Van Onsem Oct 13 '20 at 15:09

1 Answers1

2

You can't store multiple files in the same FileField [Django-doc]. You can only store one file. If you need to store multiple files, you make an extra model:

class MyModel(models.Model):
    # …
    pass

class MyModelFile(models.Model):
    my_model = models.ForeignKey(
        MyModel,
        related_name='files'
        on_delete=models.CASCADE
    )
    file = models.FileField()

So for a MyModel object, you can add multiple MyModelFiles that then each store one file.

You can then render these like:

{% for file in obj.files.all %}
    {{ file.file }}
{ %endfor %}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555