Reputation: 2541
I've made a formset that will update a model Client and a model ClientData,my problem is that instead of rendering a formset, it renders it 3 times and i can't identify why.
views.py
def client_data(request):
data = dict()
if request.method == "POST":
form = ClientForm(request.POST)
if form.is_valid():
client = form.save(commit=False)
formset = ClientFormSet(request.POST, instance=client)
if formset.is_valid():
client.save()
formset.save()
return redirect(reverse_lazy('core:index'))
else:
form = ClientForm()
formset = ClientFormSet()
data['form'] = form
data['formset'] = formset
return render(request, 'core/test.html', data)
forms.py
class ClientForm(ModelForm):
class Meta:
model = Client
fields = '__all__'
exclude = ['user', ]
class ClientDataForm(ModelForm):
class Meta:
model = ClientData
fields = '__all__'
exclude = ['client', ]
ClientFormSet = inlineformset_factory(Client, ClientData, fields=[
'language',
'type',
])
template
<form method="POST">{% csrf_token %}
{{ form.as_p }}
{{ formset }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
Upvotes: 0
Views: 607
Reputation: 426
You build your formset with inlineformset_factory, according to the documentation, in inlineformset, extra option by default, is 3.
Try this :
inlineformset_factory(Client, ClientData, fields=[
'language',
'type',
],
extra=1)
https://docs.djangoproject.com/en/1.11/ref/forms/models/#inlineformset-factory
Upvotes: 2