0

I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link.

models.py

class Orders(models.Model):

...

order_file = models.FileField(upload_to='web_unit', null=True, blank=True)

...
    def __str__(self):
        return self.reference

index.html

<div class="table-responsive">
<table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%">
  <thead>
    <tr>
      ....
  </thead>

  <tbody>

    {% for orders in orders %}

    <tr>

      <td>
        <!-- Update book buttons -->
      <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}">
        <span class="fa fa-pencil"></span>
      </button>
      </td>

   ....

      <td><a href="{{ orders.order_file }}">Download</a></td> #this is the link

    </tr>
    {% endfor %}


  </tbody>
</table>

When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this happen.

This has been marked as a duplicate a few times now - but I don't believe it is. The link that I have been referred to only shows a view. I don't understand how I am to trigger that view using a url since there will be many download links in the same screen. How does the view know which file link I have clicked on? Wouldn't that need to leverage the URL somehow?

GXM100
  • 417
  • 6
  • 20

1 Answers1

1

First, don't do {% for orders in orders %}; instead do {% for order in orders %}

Then this should work (assuming order_file is the field name you didn't show in the model)

<td><a href="{{ order.order_file.url }}">Download</a></td>
HenryM
  • 5,557
  • 7
  • 49
  • 105
  • Ok I did that but I am receiving an error ```The 'order_file' attribute has no file associated with it.``` I don't understand what this means, there is certainly a file loaded here? I can see it in the admin panel. – GXM100 Aug 14 '19 at 19:28
  • I've updated to this: ```Download``` and I'm no longer receiving that error, but now I'm just receiving a 404 error when I click the Download linke @henrym – GXM100 Aug 14 '19 at 20:09