![](/img/trans.png)
[英]Django admin: Add a “remove file” field for Image- or FileFields
[英]Remove Checkbox for the django image field
我有一个如下的模型
class Book(models.Model):
name = models.CharField(max_length=56)
picture = ImageField(upload_to='/max/')
因此,从下面的模板编辑Book模型时
<form enctype="multipart/form-data" action="{% url 'edit_book' book_id %}" method="post">
{% csrf_token %}
{{book_form.name}}
{{book_form.picture}}
</form>
如果图书记录已经有图像,则会有一个额外的html复选框
Currently:
<a href="/media/product138ba6ccf0d1408d968577fa7648e0ea/assets/bubble.png">media/product138ba6ccf0d1408d968577fa7648e0ea/assets/bubble.png</a>
<input id="picture-clear_id" name="picture-clear" type="checkbox" /> <label for="picture-clear_id">Clear</label><br />Change:
<input id="selectedFile" name="picture" type="file" />
因此,如果图书在创建时已有图像,那么它前面还有一些checkbox
和标签,以便如何避免该复选框?
编辑
forms.py
class BookForm(ModelForm):
class Meta:
model = Book
def __init__(self, *args, **kwargs):
super(BookForm, self).__init__(*args, **kwargs)
self.fields['picture'].widget.attrs = {'id':'selectedFile'}
老实说,我有点惊讶,因为你描述的内容看起来像ClearableFileInput
小部件 ,而根据文档 ,它是用作默认小部件的FileInput
。
仍然。 尝试显式选择FileInput
:
from django.forms import ModelForm, FileInput
class BookForm(ModelForm):
class Meta:
model = Book
widgets = {
'picture': FileInput(),
}
def __init__(self, *args, **kwargs):
super(BookForm, self).__init__(*args, **kwargs)
self.fields['picture'].widget.attrs = {'id':'selectedFile'}
更新:我不再感到惊讶了。 我调查了这个问题,结果发现Django Docs中有一个错误, 现在已经纠正了 。 ClearableFileInput
是默认小部件,因此您需要显式设置FileInput
,如上所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.