skip to Main Content
[SOLUTION]I needed to make the {{ product.pdf }} to {{ product.pdf.url }}

I am trying to create a button to download PDFs as a begginer. This is the code:
index.html:

<a href="{{ product.pdf }}" download>
 <button class="text-bg-success rounded mx-auto border-0 shadow rounded" style="width: 100%;height: 100%; margin-top: 30px;">
  Download
 </button>
</a>

models.py:

class Product(models.Model):
  pdf = models.FileField(upload_to='uploads/pdfs/', blank=False, null=False ,  validators=[FileExtensionValidator(allowed_extensions=["pdf","epub"])])

When I inspect the button it shows the wright file:

<a href="uploads/pdfs/BOOK.pdf" download="">
 <button class="text-bg-success rounded mx-auto border-0 shadow rounded" style="width: 100%;height: 100%; margin-top: 30px;">
  Download
 </button>
</a>

But when I click it, it opens a new tab and does nothing.
I am thinking of instead making a link to a blank page that when opened starts a download since that might work better, but I have no knowledge of what that would require. Or maybe there is a form for this type of stuff. It would be especially useful to find another way since I might need to present it on older computers without newer browser versions.

I tried to click the download button for a product with no pdf file attached to it and it downloaded the html code for the page itself.
It is not the browser version since it worked with the w3school model provided by them.
I also tried to remove the button or replace {{}} with {%%} and it did nothing.
I use bootstrap for the front-end, but I do not think it has anything to do with it.

2

Answers


  1. You should give the download a default name for the file. Like

    <a href="xxx.pdf" download="newfilename"><button>DownLoad</button></a>
    
    Login or Signup to reply.
  2. Try using an anchor tag instead,

    <a href="{{ product.pdf.url }}" download class="text-bg-success rounded mx-auto border-0 shadow rounded" style="width: 100%; height: 100%; margin-top: 30px;">
      Download
    </a>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search