我创建了一个模型,其中包含上传到自定义路径的文件(不在MEDIA_ROOT中)。所以它有点像受保护的文件。 现在我需要在管理细节中更改它的表示。它显示了相对于MEDIA_URL的路径。我需要更改它,以显示一个生成正确URL的应用程序视图的URL。
那么,显示链接的最佳方式是什么,只有在admin中的对象详细信息?
答案 0 :(得分:2)
这是我做的方式:
<强> 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
答案 1 :(得分:0)
也许这个链接可以帮助您,这是关于自定义路径。
http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/