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

前端 未结 3 1329
独厮守ぢ
独厮守ぢ 2020-12-15 08:42

I have FileField in my django model:

file = models.FileField(upload_to=FOLDER_FILES_PATH)

In Django admin section for changing this model I

相关标签:
3条回答
  • 2020-12-15 09:16

    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.

    0 讨论(0)
  • 2020-12-15 09:19

    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, ...]
    
    0 讨论(0)
  • 2020-12-15 09:26

    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)
    
    0 讨论(0)
提交回复
热议问题