Я попытался перенести два набора форм на одну страницу, и когда я ввожу несколько входов на втором, он сохраняет только первый вход - я проверил len(formset)
, который всегда возвращает 1
, даже когда их больше.
views.py:
def create_inq_with_sets_and_parts(request):
if request.method == 'GET':
inquiry_form = InquiryModelForm(request.GET or None)
setts_form = SRFormset(queryset=SettRelation.objects.none())
parts_form = PRFormset(queryset=PartRelation.objects.none())
elif request.method == 'POST':
inquiry_form = InquiryModelForm(request.POST)
setts_form = SRFormset(request.POST)
parts_form = PRFormset(request.POST)
if inquiry_form.is_valid() and setts_form.is_valid() and parts_form.is_valid():
i = inquiry_form.save()
for form in setts_form:
s = form.save(commit=False)
s.inquiry = i
s.save()
print(len(parts_form)) # <-- always gives back 1
for form in parts_form:
p = form.save(commit=False)
p.inquiry = i
p.save()
return redirect("inquiry-list")
return render(request, "gap/add_inquiry.html", {"inquiry": inquiry_form,
"setts": setts_form,
"parts": parts_form, })
Формы очень похожи:
PRFormset = modelformset_factory(PartRelation,
fields=("part", "qty", ),
widgets={'part': forms.Select(attrs={'class': 'form-control'}),
'qty': forms.NumberInput(attrs={'class': 'form-control', })})
SRFormset = modelformset_factory(SettRelation,
fields=("sett", "qty", ),
widgets={'sett': forms.Select(attrs={'class': 'form-control'}),
'qty': forms.NumberInput(attrs={'class': 'form-control', })})
The models.py :
class PartRelation(models.Model):
part = models.ForeignKey(PartBase, on_delete=models.CASCADE)
qty = models.PositiveIntegerField("Quantity")
sett = models.ForeignKey(Sett, related_name='sets', on_delete=models.SET_NULL, blank=True, null=True)
inquiry = models.ForeignKey(Inquiry, related_name='inq_part', on_delete=models.SET_NULL, blank=True, null=True)
class SettRelation(models.Model):
sett = models.ForeignKey(Sett, on_delete=models.CASCADE)
qty = models.PositiveIntegerField("Quantity")
inquiry = models.ForeignKey(Inquiry, related_name="inq_set", on_delete=models.SET_NULL, null=True)
Форма ввод с некоторыми java, но в основном выглядит так:
{{ setts.management_form }}
{% for sett in setts %}
{{ sett.sett }}
{{ sett.qty }}
{% endfor %}
{{ parts.management_form }}
{% for part in parts %}
{{ part.part }}
{{ part.qty }}
{% endfor %}