1

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.

1
  • Is this if f.is_valid(): a typo just below f = myformset()? If it is, that's the problem, the server is returning a 500 error. Commented Dec 30, 2013 at 6:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.