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

3

18

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?

Emilio answered 10/11, 2011 at 13:31 Comment(0)
C
28

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

from django.utils.html import format_html

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

    def file_link(self):
        if self.file:
            return format_html("<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, ...]
Coston answered 14/11, 2011 at 8:8 Comment(1)
I have been looking for this solution for a while now. The list_display option is only available for ModelAdmin. If using an InlineModelAdmin then file_link needs to be in fields as well as readonly_fields.Pawl
L
4

you can simply do this by changing admin.py,

from django.contrib import admin
from app.models import *

class AppAdmin(admin.ModelAdmin):
    list_display = ('author','title','file_link')
    def file_link(self, obj):
        if obj.file:
            return "<a href='%s' download>Download</a>" % (obj.file.url,)
        else:
            return "No attachment"
    file_link.allow_tags = True
    file_link.short_description = 'File Download'

admin.site.register(AppModel , AppAdmin)
Lamoureux answered 7/1, 2017 at 10:19 Comment(0)
W
3

NOTE: This solution is only appropriate for development use.

Another solution is to simply add the following to your urls.py file:

from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This will allow the default link provided on the admin /change/ page to serve the file for download.

Docs here.

For information on how to serve these files in production see docs here.

Wrier answered 31/5, 2018 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.