在多个formset中使用带有django的ajax

时间:2013-12-30 05:17:29

标签: javascript jquery python ajax django

我尝试使用django中的formset动态添加多个表单。我使用ajax发送客户端添加表单的请求。我创建了一个add_another按钮来添加formset。每当用户单击此按钮时,将进行计数增量,并通过ajax将请求发送到服务器(到我的django的视图)。我的代码如下所示:

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>

我总是得到失败警报,当从views.py打印formcount的值时,即使单击该按钮,我总是得到值1.

1 个答案:

答案 0 :(得分:1)