当使用django readonly_fields
类的新ModelAdmin
属性时,我发现如果我将FileField
中定义为readonly_fields
的字段的名称放在{{1}}中,它没有显示工作链接,它只显示相对路径。我想要一个可下载的链接。
答案 0 :(得分:2)
虽然Django Admin
问题仍未解决,但
我使用这个小部件作为穷人解决上述问题的方法:
#your_app/models.py
class ModelWithFileField(models.Model):
...
file = models.FileField(upload_to='dir/')
#your_app/admin.py
import os
from django import forms
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.html import escape
class ReadonlyFileInput(forms.Widget):
def __init__(self, obj, attrs=None):
self.object = obj
super(ReadonlyFileInput, self).__init__(attrs)
def render(self, name, value, attrs=None):
if value and hasattr(value, "url"):
return mark_safe(u'<p><a href="%s">%s</a></p>'\
% (escape(value.url),\
escape(force_unicode(os.path.basename(value.path)))))
else:
return ''
class ModelWithFileFieldForm(forms.ModelForm):
class Meta:
model = ModelWithFileField
def __init__(self, *args, **kwargs):
super(ModelWithFileFieldForm, self).__init__(*args, **kwargs)
self.fields['file'].widget = ReadonlyFileInput(self.instance)
# If you are paranoid enough, you can override the clean() method as well,
# to be sure that no one has been messing with your beloved file by
# maliciously manipulating the POST data. If you don't expect compete
# strangers to be using your admin site, this is not an issue.
class ModelWithFileFieldAdmin(admin.ModelAdmin)
form = ModelWithFileFieldForm
...
def get_readonly_fields(self, request, obj=None):
return [...] #The 'file' field should not be present in this list