1

我有一个像下面这样的模型

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之前也有一些和标签,那么如何避免该复选框?

编辑

表格.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'} 
4

1 回答 1

3

老实说,我有点惊讶,因为您描述的内容看起来像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是默认的widget,所以需要FileInput显式设置,如上图。

于 2013-10-31T15:57:55.760 回答