Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a link to download a file in a Django admin detail page?

I want to create a file containing a string and allow the user to download the file when they click a button in the admin detail page. Any ideas?

Probably add html to the form? But how can I do that? I am new to Django.

like image 789
Michael Avatar asked Dec 07 '22 14:12

Michael


2 Answers

You can go along the following lines:

class YourAdmin(ModelAdmin):   
     # add the link to the various fields attributes (fieldsets if necessary)
    readonly_fields = ('download_link',)
    fields = (..., 'download_link', ...)

    # add custom view to urls
    def get_urls(self):
        urls = super(YourAdmin, self).get_urls()
        urls += [
            url(r'^download-file/(?P<pk>\d+)$', self.download_file, 
                name='applabel_modelname_download-file'),
        ]
        return urls

    # custom "field" that returns a link to the custom function
    def download_link(self, obj):
        return format_html(
            '<a href="{}">Download file</a>',
            reverse('admin:applabel_modelname_download-file', args=[obj.pk])
        )
    download_link.short_description = "Download file"

    # add custom view function that downloads the file
    def download_file(self, request, pk):
        response = HttpResponse(content_type='application/force-download')
        response['Content-Disposition'] = 'attachment; filename="whatever.txt"')
        # generate dynamic file content using object pk
        response.write('whatever content')
        return response
like image 105
user2390182 Avatar answered Dec 10 '22 03:12

user2390182


In your models.py field for that application, add the following piece of code

from django.utils.safestring import mark_safe

def fieldname_download(self):
    return mark_safe('<a href="/media/{0}" download>{1}</a>'.format(
        self.fieldname, self.fieldname))

fieldname_download.short_description = 'Download Fieldname'

Then in your admin.py, add this field to your readonly_fields for that model

readonly_fields = ('fieldname_download', )

In your settings.py file you need to specify a root path to a directory where to serve the files from and a base url for accessing them:

MEDIA_ROOT=(str, 'path/to/your/media/directory/'),
MEDIA_URL=(str,'/media/'),
like image 40
Mehak Avatar answered Dec 10 '22 04:12

Mehak