如果用户向formset添加了另一个表单,但是已经在第一个表单中输入了某些内容,则输入将会丢失,因为新表单已创建。用户现在有2个空表格。有没有办法将新表单添加到formset但不会丢失用户输入?
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文件
<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>
答案 0 :(得分:0)
得到了我的问题的答案。起初我只想用Django做这件事,但我发现了一个更简单的方法,用jQuery做了。
以下是问题的解决方案: Dynamically adding a form to a Django formset with Ajax