对于我的Django项目,我在模板中渲染模型formset election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet)
:
<form method="post" action="">
{{ formset.management_form }}
{% for form in formset %}
<div class='card'>
<div class='card-body w-75 mx-auto'>
<div class='row'>
<div class='col-6 text-center'>
<p>Name<br>{{form.Name}}</p>
</div>
<div class='col-6 text-center'>
<p>Videos<br>{{form.FlipGrid}}</p>
</div>
</div>
<div class='row'>
<div class='col-12 text-center'>
<p>Description<br>{{form.Description}}</p>
</div>
</div>
<div class='row'>
<div class='col-6 text-center'>
<p>Allow registration: {{form.CandidateReg}}</p>
</div>
<div class='col-6 text-center'>
<p>Allow voting: {{form.VotingOpen}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
</form>
当formset呈现时,表单末尾会显示一个额外的空白表单。我只希望表单显示为现有记录的实例。为什么还有一个额外的空白表格集,如何防止它呢?
答案 0 :(得分:2)
如果formset中有一些初始数据,请尝试使用max_num
参数来限制exta:
election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, max_num=1)
来自文档:
如果初始数据中的项目数超过max_num,则无论max_num的值如何,都将显示所有初始数据表格,并且不会显示任何额外的表格。
答案 1 :(得分:1)
试试这个
election_formset = modelformset_factory(
Election,
exclude=('Complete',),
formset=BaseElectionFormSet,
extra=0
)
extra
关键字默认为1(请参阅docs):
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet, extra=1, can_delete=False,
can_order=False, max_num=None, fields=None, exclude=None,
widgets=None, validate_max=False, localized_fields=None,
labels=None, help_texts=None, error_messages=None,
min_num=None, validate_min=False, field_classes=None):