关于将下载链接作为新字段添加到详细信息页面有两个答案,这比在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>
就是这样!