如何在Django管理员详细信息页面中添加链接以下载文件? [英] How can I add a link to download a file in a Django admin detail page?

查看:288
本文介绍了如何在Django管理员详细信息页面中添加链接以下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含字符串的文件,并允许用户单击管理员详细信息页面中的按钮时下载该文件。有任何想法吗?

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?

可能在表单中添加html吗?但是我该怎么做呢?我是Django新手。

Probably add html to the form? But how can I do that? I am new to 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

这篇关于如何在Django管理员详细信息页面中添加链接以下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆