首页 > 解决方案 > 如何在 django 模板中传递产品下载链接

问题描述

如果特定产品可下载,我如何通过链接下载产品

模型.py

protected_loc = settings.PROTECTED_UPLOADS

def download_loc(instance,filename):
    return "%s/%s" %(instance.slug, filename)
    # if instance.user.username:
    #     return "%s/download/%s" %(instance.user.username,filename)
    # else:
    #     return "%s/download/%s" %("default",filename)


class Product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    name = models.CharField(max_length=120)
    description = models.CharField(max_length=500,null=True,blank=True)
    download = models.FileField(upload_to=download_loc,storage=FileSystemStorage(location=protected_loc),null=True,blank=True)
    price = models.DecimalField(max_digits=60,decimal_places=2)
    sale_price = models.DecimalField(max_digits=60,decimal_places=2,null=True,blank=True)
    slug= models.SlugField()

    def __str__(self):
        return self.name

模板

 {% for order in my_orders %}
        <tr>
          <td>{{ order.date_ordered }}</td>
          <td>{{ order.ref_code }}</td>
          <td>
            {% for item in order.items.all %}
                {{ item.product.name }}

            {% endfor %}
          </td>
          <td>${{ order.get_cart_total }}</td>
          {% if product.download %}
          <td><a href='{{ product.download|filename }}'>Download</a></td>
          {% endif %}

        </tr>
      {% empty %}
        <tr>
          <td colspan= 4> You have no orders.</td>
        </tr>
      {% endfor %}

我在这里遗漏了什么吗?尽管下载功能很好,但我无法使下载链接正常工作。我的意图是,如果购买了产品-----> 转到我的用户配置文件,如果它是可下载的产品,用户可以在配置文件中下载它。帮忙。

标签: pythondjangodjango-modelsdjango-views

解决方案


你应该使用{{ product.download.url }}


推荐阅读