Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: generate download link

I have a File model, which store path field - path in the filesystem to file. All files are stored in MEDIA_ROOT/files

In template I want generate download link for 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 item's View I do the following:

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

and the pass files to the template

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

UPD2

Related question

Solution

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

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

like image 201
Dmitry Belaventsev Avatar asked Aug 08 '12 18:08

Dmitry Belaventsev


2 Answers

I'm not sure what exactly you mean by "generate download link", but to simply link to the file, just use {{ some_file.url }} as your href.

like image 102
Chris Pratt Avatar answered Oct 16 '22 01:10

Chris Pratt


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 strip MEDIA_ROOT from the value of self.path)

In your file_detail.html (or equivalent) template:

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

NB as Chris says, it's better to use a FileField here. The above will hopefully work for your exact situation, but unless you're deeply committed to arranging things that way, I'd suggest changing to the dedicated field.

like image 28
supervacuo Avatar answered Oct 16 '22 03:10

supervacuo