2013-10-22 81 views
2

我製作了一個上傳到自定義路徑的文件(不在MEDIA_ROOT中)。所以它有點像受保護的文件。 現在我需要在管理員詳細信息中更改它的表示形式。它顯示相對於MEDIA_URL的路徑。我需要改變它,以顯示一個URL來生成一個適當的URL的應用程序視圖。Django:更改管理FileField輸出?

那麼,什麼是最好的方式來顯示鏈接,並且只有在管理對象的細節?

回答

1

這是我做的方式:

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