当尝试提交我的ModelFormSet时,我得到一个MultiValueDictKeyError。错误消息不是很具描述性,所以我不确定为什么会抛出错误。
以下是观点:
def admin_tools(request):
ElectionFormSet = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, extra=0)
if request.method == 'POST':
if 'new_election' in request.POST:
new_election = NewElectionForm(request.POST)
if new_election.is_valid():
election = new_election.save(commit=False)
election.save()
messages.add_message(request, messages.SUCCESS, 'Election created')
return redirect(reverse('elections:home'))
elif 'edit_elections' in request.POST:
formset = ElectionFormSet(request.POST)
if formset.is_valid():
formset.save()
messages.add_message(request, messages.SUCCESS, 'Election settings saved')
return redirect(reverse('elections:home'))
else:
new_election_form = NewElectionForm()
formset = ElectionFormSet()
return render(request, 'admin/admin_tools.html',{
'new_election': new_election_form,
'formset': formset,
})
以下是模板的相关部分:
<div class="card-body">
<h4>Toggle election settings:</h4>
<form method="post" action="">
{{ formset.management_form }}
{% for form in formset %}
{% csrf_token %}
<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 %}
<div class='text-center'>
<br><button type="submit" class='btn btn-outline-dark' name='edit_elections'>Save</button>
</div>
</form>
</div>
错误为raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'form-0-id'"
并在视图的if formset.is_valid():
行标记。
如何解决此错误并使formset正确提交和更新模型中的数据?