Reputation: 2910
I tried to make dynamically add multiple forms using formset in django. I used ajax to send the request for add the form by the client. I made an add_another button to add the formset. Whenever the user clicks this button an increment to count is made and the request is send through ajax to the server(to the views of my django).My code looks as follows:
views.py
def trial_balance(request):
formcount = 1
if request.is_ajax():
count = request.POST.get('mycount', formcount)
formcount = count
myformset = formset_factory(DateRangeForm,extra=formcount)
if request.method == "POST":
f = myformset()
if f.is_valid():
else:
f = myformset()
args['formcount'] = formcount
args['myformset'] = f
return render(request, 'trial_balance.html', args)
trial_balance.html
<script>
$(document).ready(function(){
$("#add_another").click(function(){
count = {{ formcount }};
count++;
alert(count);
$.ajax({
url: "/report/trial-balance",
data: { 'mycount' : count}
}).done(function() {
alert("DONE");
}).fail(function() {
alert("FAIL");
});
});
});
</script>
<div>
<form action="" method="POST"> {% csrf_token %}
{{ myformset.as_p }}
<button id="add_another">add another</button>
<input type = "submit" value = "See Results" id = "daterangeresult">
</form>
I always get fail alert and when printing the value of formcount from views.py I always get the value 1 even though the button is clicked.
Upvotes: 1
Views: 3588
Reputation: 2553
look at dynamically-adding-a-form-to-a-django-formset-with-ajax or Dynamically adding forms to a formset with jQuery in Django this might help you
Upvotes: 1