How to display multiple formsets in one another?
On the Site Form is used to give data to a case but since there can be multiple on a site it is made as a formset. In addition, each case can have multiple m2m relations, which are also a formset. The second formset therefore can be used for each of the first formsets.
But how to GET and POST data there? Can prefixes made dynamically or is there a whole other way around?
My current approach is to have both formsets as such but have the second one with an iterated prefix.
view.py
def rezept_lookup(request, my_id):
b = Auftrag.objects.filter(id=my_id).first().messung_auftrag.all().count()
InhaltFormSet = formset_factory(InhaltForm, extra=5)
FormulierungFormSet = formset_factory(FormulierungForm, extra=0)
q = Auftrag.objects.filter(id=my_id).first().messung_auftrag.all()
b = [x.messung_rezept for x in q]
formset = FormulierungFormSet(request.POST or None, prefix="rezept", initial=[{'bindemittel_name': x.bindemittel_name,
'messung_id': x.messung_id,
'bindemittel_menge': x.bindemittel_menge,
'untergrund_name': x.untergrund_name,
'schichtdicke': x.schichtdicke,
'isActive': x.isActive,
'rezept_name': x.rezept_name } for x in b])
formset_inline = InhaltFormSet(request.POST or None, prefix=[f"inhalt_{n}" for n in range(0,5,1)])
if request.method == "POST":
if formset.is_valid():
for form in formset:
temp = form.save(commit=False)
temp.save()
context = {
"formset":formset,
"formset_inline":formset_inline,
}
return render(request, "template.html", context)
template.html
<form method="post" action="{% url 'Farbmetrik:rezept_lookup' my_id=my_id %}"> {% csrf_token %}
{{ formset.management_form }}
{{ formset.non_field_errors }}
{{ formset_inline.management_form }}
{{ formset_inline.non_field_errors }}
<div class="main_form">
{% for p in formset %}
<table border="1">
<tr>
<th>{{ p.rezept_name }}</th>
<th>{{ p.messung_id }}</th>
</tr>
<tr>
<th>Bindemittel Name: </th>
<th>Bindemittel Menge: </th>
<th>Untergrund: </th>
<th>Schichtdicke: </th>
<th>Aktiv: </th>
</tr>
<tr>
{{p.id}}
{{p.ORDER}}
{{p.DELETE}}
{{p.user_name}}
{{p.usergroup_name}}
<th>{{ p.bindemittel_name }}</th>
<th>{{ p.bindemittel_menge }}</th>
<th>{{ p.untergrund_name }}</th>
<th>{{ p.schichtdicke }}</th>
<th>{{ p.isActive }}</th>
</tr>
{% for q in formset_inline %}
<tr>
<th>{{ q.produkt }}</th>
<th>{{ q.menge }}</th>
</tr>
{% endfor %}
</table>
<p></p>
{% endfor %}
</div>
{% for dict in formset.errors %}
{% for error in dict.values %}
{{ error }}
{% endfor %}
{% endfor %}
<input class="button_w" type="submit" value="Speichern"/>
</form>