Django模型formsets和Ajax

时间:2014-03-07 18:45:50

标签: javascript jquery ajax django

我正在尝试使用Ajax提交我的压缩格式集。当请求不是ajax时,代码可以正常工作。但每当我尝试实现Ajax时,我都会得到 ValidationError:[u'ManagementForm数据丢失或被篡改']

我的观点:

def App(request):
    lectures = Lecture.objects.all()
    TopicFormSet = modelformset_factory(Topic, extra=0)
    SummaryFormSet = modelformset_factory(Summary, extra=0)
    tquery = Topic.objects.all()
    squery = Summary.objects.all()
    #saving formsets:
    if request.method == 'POST' and request.is_ajax():
        t_formset = TopicFormSet(request.POST)
        s_formset = SummaryFormSet(request.POST) #formset instances
        if t_formset.is_valid() and s_formset.is_valid():
            t_formset.save() and s_formset.save()
            zipped = zip(t_formset.forms, s_formset.forms) #saving them with new data
        else:
                return HttpResponse("not valid formsets, dude") # for testing purposes
    else: #request=GET
        t_formset = TopicFormSet(queryset = tquery)
        s_formset = SummaryFormSet(queryset = squery)
        zipped = zip(t_formset.forms, s_formset.forms)
    return render (request, "app.html", {"lectures" : lectures, "zipped" : zipped, "t_formset" : t_formset, "s_formset" : s_formset})

我的Javascript代码:

$(document).ready(function(){
$(".mygt").click(function(){ // it's a button
    serializedData = $("#id_form-0-name").serialize(); // I didn't know how to "catch" all forms in formset so I am only serializing the first one
    $.ajax({
        url: "/app/",
        type: "post",
        data: serializedData,
        csrfmiddlewaretoken:'{{ csrf_token }}',
        success: alert(serializedData)
    })
    event.preventDefault();
});

});

P.S。我还在本文中包含了csrf cookie:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax和{%csrf_token%}出现在表单附近。

编辑:我的HTML:

<form action = "http://127.0.0.1:8000/app/" method = "POST">
        {% csrf_token %}
        <!-- t_formset.management_form -->
        {{ t_formset.management_form }}
        <!-- t_formset.management_form -->
        {{ s_formset.management_form }}
        <!-- formsets -->
        {% for topic, summary in zipped %}
        <div id="topic">{{ topic }}</div>
        <br>
        <input type="submit" value="Submit" class="mygt" />
        <br>
        <div id="summary">{{ summary }}</div>
        <br>
        <input type="submit" value="Submit" class="mygt" />
        {% endfor %}

2 个答案:

答案 0 :(得分:5)

问题是我不知道如何序列化所有formset,我只是序列化第一个字段(用于测试目的)。我不知道Django发送所有formset,而不是像我想的那样发送一个字段。所以我替换了

serializedData = $("#id_form-0-name").serialize();

使用:

serializedData = $("form").serialize();

代码有效!

答案 1 :(得分:1)

您是否在here所描述的模板中添加了{{t_formset.management_form}}{{s_formset.management_form}}?我遇到了同样的问题,并得到了相同的答案here