How to show download link for attached file in FileField in Django Admin?

SkyFox picture SkyFox · Nov 10, 2011 · Viewed 14.7k times · Source

I have FileField in my django model:

file = models.FileField(upload_to=FOLDER_FILES_PATH)

In Django admin section for changing this model I have full path to this file (by default):

Currently: /home/skyfox/Projects/fast_on_line/order_processor/orders_files/mydog2_2.jpg 

How can I show link for downloading this file for my admin panel users?

Answer

Lapin-Blanc picture Lapin-Blanc · Nov 14, 2011

If you have a model "Case" for example, you could add a method to your class which "creates" the link to the uploaded file :

class Case(models.Model)
    ...
    file = models.FileField(upload_to=FOLDER_FILES_PATH)
    ...

    def file_link(self):
        if self.file:
            return "<a href='%s'>download</a>" % (self.file.url,)
        else:
            return "No attachment"

    file_link.allow_tags = True

then, in your admin.py

list_display = [..., file_link, ...]