Django:更改管理员FileField输出?

我已经创建了一个模型,其中包含上传到自定义路径的文件(不在MEDIA_ROOT中).所以它有点像受保护的文件.

现在我需要在管理细节中更改它的表示.它显示了相对于MEDIA_URL的路径.我需要更改它,以显示生成适当URL的应用程序视图的URL.

那么,显示链接的最佳方式是什么,只有在admin中的对象详细信息中?

最佳答案 这是我做的方式:

models.py

class SecureFile(models.Model):
    upload_storage = FileSystemStorage(
        location=settings.ABS_DIR('secure_file/files/'))

    secure_file = models.FileField(verbose_name=_(u'file'),
                                   upload_to='images', storage=upload_storage)

widgets.py

from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe


class AdminFileWidget(forms.FileInput):
    """A FileField Widget that shows secure file link"""
    def __init__(self, attrs={}):
        super(AdminFileWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            url = reverse('secure_file:get_secure_file',
                          args=(value.instance.slug, ))
            out = u'<a href="{}">{}</a><br />{} '
            output.append(out.format(url, _(u'Download'), _(u'Change:')))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

admin.py

class SecureFileAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SecureFileAdminForm, self).__init__(*args, **kwargs)
        self.fields['secure_file'].widget = AdminFileWidget()

    class Meta:
        model = SecureFile


class SecureFileAdmin(admin.ModelAdmin):
    form = SecureFileAdminForm
点赞