ImageField/FileField Django表单当前无法修剪文件名的路径 [英] ImageField / FileField Django form Currently unable to trim the path to filename
问题描述
我有一个存储在AWS S3中的ImageField(类似于FileField).在表单中,它具有显示图像文件路径的当前"标签.我想修剪一下,只显示文件名.
I have a ImageField that stores in AWS S3 (similar to FileField). In the form, it has this "Currently" label that shows the image file path. I would like to trim and just show the filename.
请参考 Django中的最新答案:自定义FileField值在编辑模型时,我仍然无法使它正常工作.
referring to the latest answer in Django : customizing FileField value while editing a model, I still cant get it to work.
显示当前",其文件路径名称如下: https://imgur.com/a/xkUZi
It shows "Currently" with the file path name like this: 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
How can I have something like this: Currently: filename.jpg
仅供参考-ImageField/FileField,我尝试了两者都没有影响. 我正在使用Django == 1.11.7
FYI - ImageField / FileField, I tried both it doesnt make a difference. Im using Django==1.11.7
推荐答案
在Django 1.11.x中已弃用get_template_substitution_values
. CustomClearableFileInput
的新实现如下:
In Django 1.11.x get_template_substitution_values
is deprecated. New implementation of CustomClearableFileInput
could be as follow:
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
这篇关于ImageField/FileField Django表单当前无法修剪文件名的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!