如何在Django模型中使用jQuery/Ajax正确发布 [英] How to correctly post with jQuery / Ajax in Django model

查看:65
本文介绍了如何在Django模型中使用jQuery/Ajax正确发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery/Ajax将 POST 数据发布到与Django相关的模型中.尽管经历了有关该主题的许多问题,但我还是无法完成将数据发布到表中的工作.

I am trying to POST data using jQuery/Ajax to my Django related models. Despite going through a number of questions on the subject I am somehow not able to complete the job of posting data in the tables.

如果我使用正常格式 submit ,数据将保存在两个表中,但是在使用 ajax 时,我会不断收到 400(错误请求).

If I use normal form submit the data gets saved in both the tables, however while using ajax I keep getting 400 (Bad Request).

我处理 ajax 请求的视图是:

def ajxCreateRtp(request):
    if request.is_ajax and request.method == "POST":
        form = RtpCreateForm(request.POST)

        if form.is_valid():
            instance = form.save(commit=False)
            formset = CreateRtpFormset()
            if formset.is_valid():
                formset_instance = formset.save()
                instance = form.save()

                ser_instance = serializers.serialize('json', [ instance, formset_instance, ])
                return JsonResponse({"instance": ser_instance}, status=200)
            else:
                return JsonResponse({"error": form.errors}, status=400)

    return JsonResponse({"error": ""}, status=400)

控制台中的错误内容如下:

POST http://127.0.0.1:8000/.../.../.../rtp/ajax/add/ 400(错误请求)发送@ jquery-3.4.1.js:9837 ajax @ jquery-3.4.1.js:9434(匿名)@(索引):1011派遣@ jquery-3.4.1.js:5237 elemData.handle @jquery-3.4.1.js:5044

POST http://127.0.0.1:8000/.../.../.../rtp/ajax/add/ 400 (Bad Request) send @ jquery-3.4.1.js:9837 ajax @ jquery-3.4.1.js:9434 (anonymous) @ (index):1011 dispatch @ jquery-3.4.1.js:5237 elemData.handle @ jquery-3.4.1.js:5044

注意:如果我从视图 ajxCreateRtp 中删除 .formset 部分,则会保存标题表单中输入的数据到父模型.

Note: If I remove the .formset parts from the view ajxCreateRtp, the entered data in the header form gets saved to the parent model.

模板中的 jQuery/Ajax 脚本是:

$(function() {
    $('#rtpForm').submit(function(e) {
        e.preventDefault();
        var data = $(this).serialize();
        // console.log(data);
        
        $.ajax({
            type: 'POST',
            url: "{% url 'ajax_add_rtp' %}",
            data: data,
            success: function(response) {
                console.log('Data Saved');
            },
            error: function (response) {
                console.log('Problem encountered');
            }
        });
    });
});

有人可以让我摆脱这个麻烦吗?

Could somebody get me out of this problem plase?

推荐答案

似乎未正确处理 form.is_valid()为False 的情况.添加另一个return语句以包含表单的错误,并调整另一个以包含表单集的错误似乎更合适.它应该为您提供信息以继续在网络中进行调试->浏览器开发人员工具的响应面板.

It looks like the case of form.is_valid() is False is not being properly handled. Adding another return statement to include the form's errors and adjusting the other to include the formset's errors seems more appropriate. It should provide you with the information to continue debugging in the Network -> Response panel of the browser's developer tools.

def ajxCreateRtp(request):
    if request.is_ajax and request.method == "POST":
        form = RtpCreateForm(request.POST)

        if form.is_valid():
            instance = form.save(commit=False)
            formset = CreateRtpFormset()
            if formset.is_valid():
                formset_instance = formset.save()
                instance = form.save()

                ser_instance = serializers.serialize('json', [ instance, formset_instance, ])
                return JsonResponse({"instance": ser_instance}, status=200)
            else:
                return JsonResponse({"error": formset.errors}, status=400)
        return JsonResponse({"error": form.errors}, status=400)

    return JsonResponse({"error": "Invalid request type."}, status=400)

这篇关于如何在Django模型中使用jQuery/Ajax正确发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆