Django + Ajax w/jQuery :序列化和解码

Django + Ajax w/jQuery : Serialize & Decode

我正在尝试将对 POST 数据的第一个 Ajax 调用写入 Django 视图。对于我的一生,我无法确定我哪里有错误。我认为问题在于我无法确定应该在 Django 视图中的何处处理 json 数据转储。提前致谢!

代码如下:

Django 视图:

if request.method == 'POST' and request.is_ajax():

        u = mod.Applicant.objects.get(id = pulled_Applicant_ID)
        new_joint_owner = forms_a.AssetJointOwnerForm(request.POST.get('asset_owner'))

        if new_joint_owner.is_valid():
            new_joint_owner.save(commit=False)
            new_joint_owner.applicant= u
            new_joint_owner.save()

            return HttpResponse(json.dumps({'success': True}), mimetype='application/json')

        else:
            errors = new_joint_owner.errors
            return HttpResponse(json.dumps(errors))

我的jQuery/Ajax:

$(document).on('click', '.joint_owner_submit_btn', function(e){
    e.preventDefault(e);
    var current_div = $(this).parents('.joint_owner_workspace');
    var form_to_hide = $(this).parents('div#content').children('form#form_entry_input');
    //var details = $('form#joint_owner_add_form').serializeArray();
    $.ajax({

        type: 'POST',
        url: '/input/assets/joint_owner/',
        dataType: 'json',
        data: {'asset_owner' : $('form#joint_owner_add_form').serializeArray() },

        success: function(){
            form_to_hide.slideUp();
            current_div.slideDown();
            },

        fail: function (forms) {
            $('form#joint_owner_add_form').html(forms);
            console.log(forms);
            },
        });
    return false;
    });

您似乎没有通过 CSRF token。您会在 django 文档中找到一个脚本片段。 您可能还想查看 django-restframework。

我正在阅读你的 django 视图,我看到一堆语法错误:

        new_joint_owner.applicant= u
        new_joint_owner.save()here

如果它们在您的代码中,请先尝试修复它们。看看500是否持续。

好吧,我本身并没有找到答案,但我确实找到了一种方法来解决我的实际问题。我认为我遇到的问题是处理序列化表单的输出。 POST 数据如下所示:

<QueryDict: {'asset_owner': ['csrfmiddlewaretoekn=@#$.......&first_name=bob%middlename=""%last_name="smith"']}

所以我将 JS/jQuery 更改为以下内容:

var data_to_go = {}
data_to_go['first_name'] = $('input#id_first_name').val();
data_to_go['middle_name'] = $('input#id_middle_name').val()
data_to_go['last_name'] = $('input#id_last_name').val()
$.ajax({

    type: 'POST',
    url: '/input/assets/joint_owner/',
    dataType: 'json',
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    data: {"asset_owner" : JSON.stringify(data_to_go) },

POST 数据现在看起来像:

<QueryDict{'asset_owner' : {"first_name" : "bob", "middle_name": "", "last_name" : "smith"}}

然后我可以通过

简单地将数据保存在视图中
    a = json.loads(request.POST.get('asset_owner'))
    new_joint_owner = forms_a.AssetJointOwnerForm(a)

不确定为什么我会在序列化表单中得到这样的 crsf-token,但我可能应该在以后弄清楚它。

问题是,您发送的似乎是 json 字符串作为整个表单的负载。这肯定会让您的表单处理程序感到困惑。您有两种选择:要么让浏览器端发送普通表单数据,要么将其转换为 json 并将其反序列化为 Python 对象,然后再发送到您的 django 表单 class.