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.
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
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/'),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With