如何在Django中将上传文件的名称显示为下载链接

时间:2021-02-09 07:38:19

标签: python-3.x django

在我的 Django 项目中,我想将下载链接显示为上传文件的名称。

这是我的models.py

class QuoteList(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    
    attached_file = models.FileField(upload_to='documents/QuoteList/%s/'%owner, blank=True) 
    
    def __str__(self):
        return self.owner.email

views.py 中,我只是查询一个对象并将其发送到模板:

def quote_details(request, quote_id):

    quote = get_object_or_404(QuoteList, id=quote_id)
    
    quote.is_opened = True
    quote.save(update_fields=['is_opened', ])
    
    context = {
        'quote': quote,
    }
    return render(request, 'basket/quote_details.html', context)

在模板中我使用以下代码生成下载链接:

{% if quote.attached_file %}
    <div class="">
        <a role="button" 
            href="{{ quote.attached_file.url }}"
            download="{{ quote.attached_file.url }}"
            class="btn btn-light text-dark ml-0">
            Download attachment          <========== the name which is showing to the user
        </a>
    </div>
{% endif %}

如何将Download attachment更改为上传文件的名称?

0 个答案:

没有答案
相关问题