在我的问题中,我使用inlineformset_factory在1个表单上使用2个关系模型。
在我的ciranta模型中;
错误是当我运行此代码时,我添加了多个ciranta模型,但最后一个正在保存。 。我该怎么解决?
我的form.py;
class CekForm(ModelForm):
class Meta:
model =cekler
exclude = ()
class CirantaForm(ModelForm):
class Meta:
model = ciranta
exclude = ()
CirantaFormSet = inlineformset_factory(cekler, ciranta,
form=CirantaForm, extra=1)
我的views.py;
class CekCreate(CreateView):
model = cekler
fields = ['borclu', 'borcluAdres', 'borclu_mail', 'borcluTelefon','tutar','kur','banka','cek_tarih']
class CirantaCreate(CreateView):
model = cekler
fields = ['borclu', 'borcluAdres', 'borclu_mail', 'borcluTelefon','tutar','kur','banka','cek_tarih']
success_url = reverse_lazy('home')
def get_context_data(self, **kwargs):
data = super(CirantaCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['cirantalar'] = CirantaFormSet(self.request.POST)
else:
data['cirantalar'] = CirantaFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
cirantalar = context['cirantalar']
with transaction.atomic():
self.object = form.save()
if cirantalar.is_valid():
cirantalar.instance = self.object
cirantalar.save()
return super(CirantaCreate, self).form_valid(form)
还有我的模板;
<table class="table">
<br>
{{ cirantalar.management_form }}
{% for form in cirantalar.forms %}
{% if forloop.first %}
<thead class="thead-light">
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" class ="btn btn-outline-primary btn-lg btn-block" value="Kaydet"/><br> <br>