4

我制作了一个模型,其中包含上传到自定义路径(不在 MEDIA_ROOT 中)的文件。所以它有点像受保护的文件。现在我需要更改它在管理详细信息中的表示。它显示了相对于 MEDIA_URL 的路径。我需要更改它,以向生成正确 URL 的应用程序视图显示 URL。

那么,显示链接的最佳方式是什么,并且仅在管理员的对象详细信息中?

4

1 回答 1

2

这是我的做法:

模型.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)

小部件.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))

管理员.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
于 2013-10-24T09:03:25.620 回答