不为空时更改为ImageField显示的默认文本
我有以下字段:
photo = models.ImageField(null=True,blank=True,upload_to="product_images")
我在 forms.py
中为此字段定义了以下布局:
I have defined the following layout in forms.py
for this field:
self.fields['photo'].label = "Asset Image"
self.helper.layout = Layout(
'photo',
HTML("""{% if form.photo.value %}
<img height="80"
width="160"
class="pull-left"
src="{{ MEDIA_URL }}{{ form.photo.value }}">
{% endif %}""", ),
现在,我可以上传与此特定字段相关的图像了.但是,当我尝试更新图像时,我在模板中看到以下内容:
Now I can upload images associated with this particular field just fine. However when I try to update the image I see the following in my template:
有什么方法可以更改布局,以便在图像字段不为空时仅显示浏览按钮和现有图像?换句话说,删除文本当前:product_images/km_2.jpeg清除更改:
Is there any way I can change the layout so that only the browse button and existing image are shown when the image field is not empty? In other words, remove the text Currently: product_images/km_2.jpeg Clear Change:
我很确定 ImageField
使用 ClearableFileInput
来呈现HTML.
I'm pretty sure ImageField
uses ClearableFileInput
in order to render the HTML.
因此,要摆脱当前:...清除"内容,您需要将 ClearableFileInput
子类化,并修改 template_with_clear
和/或 template_with_initial
成员.
So to get rid of the "Currently: ... Clear" stuff you need to subclass the ClearableFileInput
and modify the template_with_clear
and/or template_with_initial
members.
from django.forms import ClearableFileInput
class MyClearableFileInput(ClearableFileInput):
template_with_initial = '%(input_text)s: %(input)s'
随后,您使用 MyClearableFileInput
,例如:
class MyForm(ModelForm):
class Meta:
model = MyModel
widgets = {
"file": MyClearableFileInput(),
}
我使用 FileField
对此进行了测试,但是我很确定它也可以与 ImageField
一起使用.
I tested this with a FileField
, but I'm pretty sure it will also work with an ImageField
.