【问题标题】:How can I add a link to download a file in a Django admin detail page?如何在 Django 管理详细信息页面中添加链接以下载文件?
【发布时间】:2018-07-24 06:50:13
【问题描述】:

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

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

【问题讨论】:

  • in the admin form 是什么意思?在管理员列表页面还是在管理员详细信息页面?
  • 管理员详细信息页面,我可以在其中编辑模型字段并保存更改。
  • @Selcuk 我需要在管理员详细信息页面中添加按钮,而不是在列表页面中。

标签: python django django-models django-admin


【解决方案1】:

您可以按照以下方式进行:

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

【讨论】:

  • 您能否详细说明admin:applabel_modelname_download-file 的作用?
  • 这是reverseurl 模板标签使用的视图名称。 common admin views follow that the applabel_modelname_viewname pattern。这就是我使用它的原因。
  • 我收到No Reverse match 错误。我使用Model.__meta.app_label 值作为applabelmodelname 小写的实际型号名称。我和你一样写了download-file。我错过了什么吗?
  • 我也做了同样的事情,但是现在,当我尝试添加一个对象时,我得到了No Reverse match
  • 对于所有在添加新对象时没有反向数学的人:在download_link函数中输入if obj.id is not None then return link,否则返回"-"
【解决方案2】:

在该应用程序的 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', )

【讨论】:

  • 似乎我还需要将fieldname_download 添加到fields 属性,知道为什么吗?。
  • 如果您在该模型的自定义管理中定义了fields 选项,那么您需要将fieldname_download 添加到它。 docs.djangoproject.com/en/2.0/ref/contrib/admin/…
【解决方案3】:

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

实现这一点的方法是:

1models.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 ')

2views.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 管理员.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 下载文件输入.html

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

就是这样!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2020-09-08
    • 2023-04-03
    • 1970-01-01
    • 2020-12-06
    相关资源
    最近更新 更多