如何在Django管理员详细信息页面中添加链接以下载文件?

时间:2018-07-24 06:50:13

标签: python django django-models django-admin

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

可能将html添加到表单中?但是我该怎么办呢?我是Django的新手。

3 个答案:

答案 0 :(得分:2)

您可以遵循以下几行:

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(GmPromotionAdmin, 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

答案 1 :(得分:1)

在该应用程序的models.py字段中,添加以下代码

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'

然后在您的admin.py中,将该字段添加到该模型的readonly_fields

readonly_fields = ('fieldname_download', )

答案 2 :(得分:1)

关于将下载链接添加为详细信息页面的新字段,有两个答案,这比在AdminFileWidget内添加下载链接更容易。如果有人需要在AdminFileWidget内添加下载链接,我会写这个答案。 最终的结果是这样的:

enter image description here

实现此目标的方法是:

1 models.py

class Attachment(models.Model):
    name = models.CharField(max_length=100,
                            verbose_name='name')
    file = models.FileField(upload_to=attachment_file,
                            null=True,
                            verbose_name='file ')

2 views.py:

class AttachmentView(BaseContextMixin, DetailView):
    queryset = Attachment.objects.all()
    slug_field = 'id'

    def get(self, request, *args, **kwargs):
        instance = self.get_object()
        if settings.DEBUG:
            response = HttpResponse(instance.file, content_type='application/force-download')
        else:
            # x-sendfile is a module of apache,you can replace it with something else
            response = HttpResponse(content_type='application/force-download')
            response['X-Sendfile'] = instance.file.path
        response['Content-Disposition'] = 'attachment; filename={}'.format(urlquote(instance.filename))
        return response

3 urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('attachment/<int:pk>/', AttachmentView.as_view(), name='attachment'),
]

4 admin.py

from django.urls import reverse
from django.contrib import admin
from django.utils.html import format_html
from django.contrib.admin import widgets


class DownloadFileWidget(widgets.AdminFileWidget):
    id = None
    template_name = 'widgets/download_file_input.html'

    def __init__(self, id, attrs=None):
        self.id = id
        super().__init__(attrs)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        print(self, name, value, attrs, self.id)
        context['download_url'] = reverse('attachment', kwargs={'pk': self.id})
        return context

class AttachmentAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', '_get_download_url']
    search_fields = ('name',)
    my_id_for_formfield = None

    def get_form(self, request, obj=None, **kwargs):
        if obj:
            self.my_id_for_formfield = obj.id
        return super(AttachmentAdmin, self).get_form(request, obj=obj, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        if self.my_id_for_formfield:
            if db_field.name == 'file':
                kwargs['widget'] = DownloadFileWidget(id=self.my_id_for_formfield)

        return super(AttachmentAdmin, self).formfield_for_dbfield(db_field, **kwargs)

    def _get_download_url(self, instance):
        return format_html('<a href="{}">{}</a>', reverse('attachment', kwargs={'pk': instance.id}), instance.filename)

    _get_download_url.short_description = 'download'

admin.site.register(Attachment, AttachmentAdmin)

5 download_file_input.html

{% include "admin/widgets/clearable_file_input.html" %}
<a href="{{ download_url }}">Download {{ widget.value }}</a>

仅此而已!

相关问题