我试图返回多个具有相同名称的表单元素,但是我只获得最后一个元素而不是所有元素。在我的视图中它可以工作并显示所有元素,一旦我点击提交仅返回最后一个元素(在这种情况下为3次)。那是为什么?
forms.py:
class GroupAddForm(forms.ModelForm):
email = forms.EmailField(label='' ,widget=forms.HiddenInput(attrs={'class': 'form-control'}))
page_name = forms.CharField(label='' ,widget=forms.HiddenInput(attrs={'rows': '4', 'class': 'form-control'}))
page_street = forms.CharField(label='' ,widget=forms.HiddenInput(attrs={'rows': '4', 'class': 'form-control'}))
add_button = forms.BooleanField(label='', required=False, widget=forms.CheckboxInput(attrs={'rows': '4', 'class': 'form-control'}))
class Meta:
model = GroupManagement
fields = ['email', 'page_name', 'page_street', 'add_button']
View.py
for items in locationdata:
show_name.append(items[1])
show_street.append(items[2])
name = items[1]
street = items[2]
form = GroupAddForm(request.POST or None, initial={"page_name": name, "page_street": street, "email": email})
forms.append(form)
for item in forms:
if item.is_valid():
email = item.cleaned_data.get("email")
page_name = item.cleaned_data.get("page_name")
page_street = item.cleaned_data.get("page_street")
add_button = item.cleaned_data.get("add_button")
if add_button == true:
//// do stuff
context = {
'names': names,
'street': street,
'group_name_form': group_name_form,
'locationdata': locationdata,
'forms': forms,
}
模板:
<div class="modal-body">
<div class="col-md-12">
<form method="POST" action=""> {% csrf_token %}
{{group_name_form.as_p}}
<div class="col-md-6 pull-left">
{% for items in names %}
<p style="text-align:left;"> {{items.0}} {{items.1}} </p>
{% endfor %}
</div>
<div class="col-md-6">
{% for items in forms %}
{{items.as_p}}
{% endfor %}
</div>
</div>
<input type="submit" class="btn btn-success" value="Gruppe erstellen"></form>
</div>