Django: create a download link

I have a File model that stores the path to the path file in the file system. All files are stored in MEDIA_ROOT / files

In the template, I want to create a download link for the File object. What is the best way to do this? Should I use static file handling in django?

TIA!

UPD

File model

 class File(models.Model): item = models.ForeignKey(Item) file = models.FileField(upload_to = os.path.join(MEDIA_ROOT,'items')) format = models.CharField(max_length = 255) 

In the View element, I do the following:

files = File.objects.filter(item_id = id)

and pass files to the template

in the template, I use files.1.file.url , for example, and still have a bad url, for example site.com/home/dizpers/...

UPD2

Question related to us

Decision

My problem was in the file model, in the File field. In the upload_to parameter, I use the absolute path, but should use the relative path:

file = models.FileField(upload_to = 'items')

+6
source share
3 answers

I'm not sure what exactly you mean by β€œcreate a download link”, but for just a link to a file just use {{ some_file.url }} as your href .

+7
source

In models.py :

 import os from django.conf import settings from django.db import models class File(models.Model): ... (your existing File model) @property def relative_path(self): return os.path.relpath(self.path, settings.MEDIA_ROOT) 

(using the relpath method to remove MEDIA_ROOT from self.path )

In your template file_detail.html (or equivalent):

 <a href='{{ MEDIA_URL }}{{ file.relative_path }}'>{{ file.name }}</a> 

NB, as Chris says, it's best to use FileField here. The above, we hope, will work for your specific situation, but if you are not determined to arrange this, I suggest moving on to the highlighted area.

+4
source

try using href="{{ STATIC_URL }}/files/somefile" or href="{{ MEDIA_URL }}/files/somefile" for user-uploaded content

+3
source

Source: https://habr.com/ru/post/922405/


All Articles