我有一个存储在AWS S3中的ImageField(类似于FileField)。在表单中,它具有显示图像文件路径的“当前”标签。我想修剪,只显示文件名。
谈到Django : customizing FileField value while editing a model的最新答案,我仍然无法让它发挥作用。
它显示“Currently”,文件路径名如下:https://imgur.com/a/xkUZi
form.朋友
class CustomClearableFileInput(ClearableFileInput):
def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
logging.debug("CustomClearableFileInput %s",value) <-- it never came here
return {
'initial': conditional_escape(path.basename(value.name)),
'initial_url': conditional_escape(value.url),
}
class CompanySettingEdit(forms.ModelForm):
display_companyname = forms.CharField(max_length=50, required=True)
company_logo = forms.ImageField(widget=CustomClearableFileInput)
class Meta:
model = Company
fields = ("display_companyname","company_logo")
model.朋友
class Company(models.Model):
display_companyname = models.CharField(max_length=50)
company_logo = models.ImageField(upload_to=upload_to('company_logo/'), blank=True, null=True, storage=MediaStorage())
我怎么能有这样的东西:目前:filename.jpg
仅供参考 - ImageField / FileField,我试过它并没有什么区别。我使用Django == 1.11.7
在Django 1.11.x中,get_template_substitution_values
已被弃用。 CustomClearableFileInput
的新实施可以如下:
class CustomClearableFileInput(ClearableFileInput):
def get_context(self, name, value, attrs):
value.name = path.basename(value.name)
context = super().get_context(name, value, attrs)
return context