Formset factory finds the number of forms in the max_num , extra or form-TOTAL_FORMS in request.POST (or data) from the control form.
In your case, request.POST['form-TOTAL_FORMS'] has a number that does not include an additional form. Therefore, when creating a set of forms, it does not add an additional form.
One solution would be to increase this number by one when your condition is met. eg.
data = None if request.POST: data = request.POST.copy() #required as request.POST is immutable if request.POST.has_key('siguiente'): data['form-TOTAL_FORMS'] = int(data['form-TOTAL_FORMS']) + 1 #now use data instead of request.POST formset = LineaHojaSet(data, queryset=lineas) ....
However, there are some drawbacks to manipulating a set of forms in this way. When you check a set of forms, an additional form will show errors if there are any required fields.
The best solution would be to create the form set again before submitting it with one additional form and set of queries. Most likely, when formet is valid, you will save any new objects that will be added to queryset. Thus, your page will display newly added objects and one additional form.
lineas = Linea.objects.filter(hoja=alt).order_by('id') LineaHojaSet = modelformset_factory(Linea, can_delete=True,) formset = LineaHojaSet(request.POST or None, queryset=lineas) if request.method=='POST': # process formset if formset.is_valid: #saved and done with formset. if request.POST.has_key('siguiente'): LineaHojaSet = modelformset_factory(Linea, can_delete=True, extra=1) formset = LineaHojaSet(queryset=lineas) ... return render_to_response('template.html', {'formset':formset}, context_instance=RequestContext(request))
source share