我将这些变量称为:srodki(具有2个值的简单列表),roles(具有某些角色的数组的数组)和formset(具有某些formset的数组的数组),我之所以将它们分开是因为 我希望模板看起来像这样:
srodki.name
role
formset
问题是,我的代码像这样迭代:
srodki.name
role
formset
formset
这些表单集有一些初始值传递给他们,但没有输出正确的表单集,而是仅显示了它们两者,因为我不知道在另一个for循环中同时迭代其中的2个(即遍历srodki ) 我虽然要使用字典,但无法正确实现
我的观点:
def EventSily(request, event_id):
event = Event.objects.get(pk=event_id)
srodki = SiSvalue.objects.filter(event=event)
roles_count = 0
SilyFormset = modelformset_factory(EventWork, fields=('event', 'role', 'worker', 'start_time', 'end_time'))
roles = []
formsets = []
for each in srodki:
roles_array = []
formsets_array = []
srodki_sis = each.sis
role_srodka = Roles.objects.filter(srodek=srodki_sis)
for role in role_srodka:
roles_array.append(role.name)
roles_count += 1
print(role)
formset = SilyFormset(initial=[{'event' : event, 'role' : role}])
formsets_array.append(formset)
roles.append(roles_array)
formsets.append(formsets_array)
if request.method == "POST":
for formset in formsets:
formset = SilyFormset(request.POST)
mylist = zip(srodki, roles, formsets)
context = {
'event' : event,
'mylist' : mylist
}
return render(request, 'events/event_sily.html', context)
我的模板
{% extends 'events/base.html' %}
{% block content %}
<h1>Środki eventu: {{ event.name }} </h1>
<form method="POST">
{% csrf_token %}
{% for srodek, roles_array, formsets_array in mylist %}
<h2>{{ srodek.sis }}</h2>
{% for role in roles_array %}
<h3>{{ role }}</h3>
{% for formset in formsets_array %}
{{ formset.as_p }}
{% endfor %}
{% endfor %}
{% endfor %}
<button class="inputs" type="submit" name="add">Dodaj</button>
</form>
{% endblock %}
感谢帮助!