Mocktheduck
Mocktheduck

Reputation: 1423

Download local file link in html django template

Basically I have a django template from which I show data about a document and I want a link to download the file. I tried something like this but it is not working:

<div class="metadata-container">
        <div class="metadata-title">
            <div>Version</div>
            <div>Author</div>
            <div>File</div>
        </div>
        <div class="metadata-content">
            <div>{{ document.version }}</div>
            <div>{{ document.author }}</div>
            <a href=document.file download><div>{{ document.file }}</div>
        </div>
    </div>

The filename in format '/documents/2017/filename.txt' is in document.file variable or however it's called. How can I use it in the ? or how can I make it work?

Upvotes: 2

Views: 3294

Answers (1)

Alexander Tyapkov
Alexander Tyapkov

Reputation: 5017

You should write a method inside your Document model a method which should return the correct link to the file.

Similar to:

  def get_document_url(self):
    if self.file:
      return '/documents/2017/ + self.file.name + ".txt"

And then inside html you can get it with:

<a href={{document.get_document_url}}>Link</a>

Upvotes: 3

Related Questions