【问题标题】:How to post data of checkbox by ajax Django?如何通过ajax Django发布复选框数据?
【发布时间】:2021-10-18 01:44:43
【问题描述】:

如何使用 ajax 将 is_read 复选框字段提交到数据库中? 当我尝试勾选复选框字段时,我收到此错误core.models.Article.DoesNotExist: Article matching query does not exist.

models.py

class Article(models.Model):
    title = models.CharField(max_length=300)
    is_read = models.BooleanField(default=False)

views.py

@csrf_exempt
def Story_status_update(request):
    if request.method == 'POST':
        pk = request.POST.get('pk')
        item = Article.objects.get(id=pk)
        print(item)
        item.is_read = True
        item.save()
        return JsonResponse({'succes': True}, status=200)
    else:
        return JsonResponse({'succes': False, 'errors': []}, status=400)

HTML

<tbody>
    {% for object in articles %}
    <tr data-pk="{{ object.id }}">
        <td>{{ object.title }}</td>
        <td><input type="checkbox" data-id="{{ object.id }}" name="is_read" id="id_is_read" /></td>
    </tr>
    {% endfor %}
</tbody>

ajax.js

    $("#id_is_read").click(function () {
        var pk = $('tr').attr("data-pk");
        $.ajax({
            type: "Post",
            contentType: "application/json;",
            url: "{% url 'status-update' %}",
            data: { pk: pk },
            dataType: "json",
            success: function (response) {
                console.log(response)
            },
        });
    });

【问题讨论】:

    标签: javascript python jquery django ajax


    【解决方案1】:

    我不确定 Django 部分,但是

    对于 Html,您正在创建多个具有相同 id 的复选框,这是无效的,请改用一个类。

    <tbody>
        {% for object in articles %}
        <tr data-pk="{{ object.id }}">
            <td>{{ object.title }}</td>
            <td><input type="checkbox" data-id="{{ object.id }}" name="is_read" class="class_is_read" /></td>
        </tr>
        {% endfor %}
    </tbody>
    

    对于 JavaScript,使用类作为选择器并选择正确的行。
    此外,内容类型错误,因为您没有发送 JSON,因此请删除 contentType

    $(".class_is_read").click(function () {
        var pk = $(this).closest('tr').attr("data-pk"); // select the correct row
        $.ajax({
            type: "POST",
            url: "{% url 'status-update' %}",
            data: { pk: pk },
            dataType: "json",
            success: function (response) {
                console.log(response)
            },
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2014-09-04
      • 2018-12-03
      • 1970-01-01
      • 2019-08-26
      • 2021-05-25
      相关资源
      最近更新 更多