1

If user adds another form to formset, but has already typed something in first form, then the input will be lost, as new form was created. User now has 2 empty forms. Is there a way to add new form to formset but not lose user input?

forms.py

class Form(forms.Form):
    client = forms.CharField(label='Client', required=False)
    end_client = forms.CharField(label='End client', required=False)
    product = AutoCompleteSelectField(lookup_class=ProductLookup, label='Model', required=False)

views.py

def get(self, request):
    request.session['form_count'] = 1

    FormSet = formset_factory(Form)
    formset = FormSet()

    return render(request, self.template_name, {'formset': formset} )

def post(self, request):
    if "add-form" in request.POST:
        form_count = request.session['form_count']
        print("There are " + str(form_count) + " forms")

        form_count = form_count + 1
        request.session['form_count'] = form_count
        print("Form count increased by 1, form count is: " + str(form_count))

        FormSet = formset_factory(Form, extra=int(form_count))
        formset = FormSet()  **<-- if I put request.POST in here, new form will not be created**

        return render(request, self.template_name, {'formset': formset})

html file

<div class="content">
  <form method="post">
    {% csrf_token %} {{ formset.management_form }}
    <div class="form-group">
      {% for form in formset.forms %}
      <table class='no_error'>
        {{ form.as_table }}
      </table>
      <br>
      <br> {% endfor %}
    </div>
    <input class="btn btn-primary" type="submit" value="Submit order" />
    <input name="add-form" class="btn btn-primary" type="submit" value="Add new product" />
  </form>
</div>
Sander Lepik
  • 65
  • 1
  • 9

0 Answers0