[英]ImageField / FileField Django form Currently unable to trim the path to filename
我有一個存儲在AWS S3中的ImageField(類似於FileField)。 在表單中,它具有顯示圖像文件路徑的“當前”標簽。 我想修剪,只顯示文件名。
參考Django中的最新答案:在編輯模型時自定義FileField值 ,我仍然無法使其正常工作。
它顯示“當前”,其文件路徑名稱如下: https : //imgur.com/a/xkUZi
form.py
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.py
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.