在django 2.2中无法进行文件下载

时间:2019-06-14 01:34:28

标签: python html django python-3.x

我在django 2.2和python三中使用

am我有我的下载功能,并且在模型中获得下载功能,链接不起作用 缺少东西

下载功能

def download_product(request,slug,filename):
    product = Product.objects.get(slug=slug)
    if product in request.user.profile.ebooks.all():
        product_file = str(product.download)
        filepath = os.path.join(settings.PROTECTED_UPLOADS,product_file)
        wrapper = FileWrapper(open(filepath,'rb'))
        response = HttpResponse(wrapper,content_type=guess_type(product_file))
        response['Content-Diposition'] = 'attachment;filename=%s' %filename
        response['Content-Type'] = ''
        response['X-SendFile'] = filepath
        return response
    else:
        raise Http404

models.py

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 object in object_list %}
        <div class="col-sm-3">
            <p>{{ object.name }}</p>
            <p>Price: ${{ object.price }}</p>
            {% if object in user.profile.ebooks.all %}
            {% if object.download %}
            <p><a href='{{ object.download.url }}'>Download</a></p>
            {% endif %}
            <!-- add a button here to see the product -->
            You own this
            {% elif object in current_order_products %}
            <a href="{% url 'shopping_cart:order_summary' %}" class="btn btn-warning">Go to Cart</a>
            {% else %}
            <a href="{% url 'shopping_cart:add_to_cart' object.id %}" class="btn btn-warning">Add to Cart</a>
            {% endif %}
        </div>
    {% endfor %}

因此,在添加产品时,所有产品文件都将上载到受保护的文件夹,但是在首先下载时,链接指向媒体文件夹而不是受保护的文件夹(以为它们位于同一目录中)。 因此,点击下载按钮会显示404页面未找到

  

work \ static_cdn \ media \ work \ django.jpg”不存在

0 个答案:

没有答案