[英]View to Download FileField From Django
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. 我有保存到MEDIA_ROOT的文件-我正在UI的表中将文件路径显示为URL。 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. 但是,发生这种情况时,我会得到一个错误,因为我没有定义URL或View来处理此问题。 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. 下面是我的模型,以及显示表和链接的.html。
models.py 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 的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. 单击表中的链接后-我想下载文件-我需要有关如何定义URL和视图的帮助,以实现此目的。
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? 那不需要以某种方式利用URL吗?
First, don't do {% for orders in orders %}
; 首先,请勿执行{% for orders in orders %}
; instead do {% for order in orders %}
而是执行{% for order in orders %}
Then this should work (assuming order_file is the field name you didn't show in the model) 然后这应该工作(假设order_file是您未在模型中显示的字段名称)
<td><a href="{{ order.order_file.url }}">Download</a></td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.