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")
模型.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屋!