Python ModelFormSet上的额外表单
对于我的Django项目,我正在我的模板中呈现模型formsetPython ModelFormSet上的额外表单,python,html,django,django-forms,django-templates,Python,Html,Django,Django Forms,Django Templates,对于我的Django项目,我正在我的模板中呈现模型formsetelection\u formset=modelformset\u工厂(election,exclude=('Complete',),formset=BaseElectionFormSet): <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} <div clas
election\u formset=modelformset\u工厂(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.management_form}
{formset%中表单的%s}
名称
{{form.Name}
视频
{{form.FlipGrid}
Description
{{form.Description}
允许注册:{form.CandidateReg}
允许投票:{form.VotingOpen}
{%endfor%}
当表单集呈现时,表单末尾会显示一个额外的空白表单。我只希望表单显示现有记录的实例。为什么会有一个额外的空白表单集?我如何防止它?试试这个
election_formset = modelformset_factory(
Election,
exclude=('Complete',),
formset=BaseElectionFormSet,
extra=0
)
extra
关键字默认为1,否则(请参阅):
如果formset中有一些初始数据,请尝试使用参数限制exta:
election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, max_num=1)
从文档中:
如果初始数据中的项目数超过max_num,则无论max_num的值如何,都将显示所有初始数据表单,并且不会显示额外的表单
election_formset = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, max_num=1)