Mic*_*ael 3 python django django-models django-admin
我想创建一个包含字符串的文件,并允许用户在单击管理详细信息页面中的按钮时下载该文件。有任何想法吗?
可能将html添加到表单中?但是我该怎么做呢?我是 Django 的新手。
您可以按照以下方式进行:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5347 次 |
| 最近记录: |