Django:选中复选框时删除对象

时间:2018-06-25 08:37:00

标签: javascript jquery ajax django

在Django中检查表格行时,我想删除对象。在遵循Stackoverflow的答案之后,我得到了下面的代码。但是,它不会删除模型的对象。我记录了代码; onclick删除按钮起作用。它调用delete_test函数,但是测试模型不是delete。终端机上说

  

禁止(CSRF令牌丢失或不正确。):   / test-management / delete_test /

提前谢谢!

urls.py

$string = substr_replace($string, '', strrpos($string, ','), 1);

views.py

from test_management.views import (test_list, add_test
                                    , delete_test)

urlpatterns = [url(r'^test-management/test/', test_list, name='test'),
    url(r'^test-management/add_test/', add_test, name='add_test'),
    url(r'^test-management/delete_test/', delete_test, name='delete_test'),]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

test_list.html

def delete_test(request):
    if request.is_ajax():
        selected_tests = request.POST['test_list_ids']
        selected_tests = json.loads(selected_tests)
        for i, test in enumerate(selected_tests):
            if test != '':
                Test.objects.filter(id__in=request.POST.getlist('items')).delete()
        return HttpResponseRedirect('/test-management/test/')

2 个答案:

答案 0 :(得分:1)

您需要将csrfmiddlewaretoken与POST数据一起传递。您可以通过添加模板标签{% csrf_token %}来实现此目的。

</button>
    <button class="btn btn-round delete-btn" data-toggle="modal">
  <i class="material-icons" action >delete</i>   Delete
</button>

<div class="table-container">
            <table id="fresh-table" class="table table-striped test-list">
                    <thead class="thead-table-list">
                      <tr>
                        <th scope="col">
                          <div class="form-check">
                              <label class="form-check-label">
                                <input class="form-check-input" id="checkall" type="checkbox" value="">
                                <span class="form-check-sign">
                                  <span class="check"></span>
                                </span>
                              </label>
                          </div>
                        </th>
                        <th scope="col">#</th>
                        <th scope="col">Test</th>
                        <th scope="col">Type</th>
                        <th scope="col">Test Date</th>
                      </tr>
                    </thead>
                    <tbody>
                        {% for test in tests %}
                        <tr data-id="{{ test.id }}">
                            <td>
                                <div class="form-check">
                                    <label class="form-check-label">
                                        <input class="form-check-input check-ele" type="checkbox" value="">
                                        <span class="form-check-sign">
                                        <span class="check"></span>
                                        </span>
                                    </label>
                                  </div>
                            </td>
                            <td>{{ test.id}}</td>
                            <td>{{ test.test_name}}</td>
                            <td>{{ test.test_type}}</td>
                            <td>{{ test.test_date}}</td>  
                        </tr>      
                        {% endfor %}
                    </tbody>
                  </table>
{% csrf_token %}
</div>

<script type='text/javascript'>
$(".delete-btn").click(function(){

  var selected_rows=[];

  $('.test-list').find('tr').each(function(){
    var row=$(this);
    console.log(row.find('input[type="checkbox"]').is(':checked'));
    if (row.find('input[type="checkbox"]').is(':checked')) {
        console.log(row.attr('data-id'));
        selected_rows.push(row.attr('data-id'));
        };
    });
    var selected_rows = JSON.stringify(selected_rows);
    $.ajax({
        url: "{% url 'delete_test' %}",
        type: 'POST',
        data: {'test_list_ids': selected_rows,'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()},
    })
});
</script>

答案 1 :(得分:1)

通过传递csrfmiddlewaretoken和POST数据来解决错误。您可以通过添加模板标签{% csrf_token %}

来完成此操作
$.ajax({
        url: "{% url 'delete_test' %}",
        type: 'POST',
        data: {'test_list_ids': selected_rows,'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()},
    })

通过编辑行的复选框并单击删除按钮,还可以通过编辑来删除模型的对象:

views.py

def delete_test(request):
    if request.is_ajax():
        selected_tests = request.POST['test_list_ids']
        selected_tests = json.loads(selected_tests)
        for i, test in enumerate(selected_tests):
            if test != '':
                Test.objects.filter(id__in=selected_tests).delete()
        return HttpResponseRedirect('/test-management/test/')

谢谢!