0

I'd like to delete objects when the table row is checked in Django. After following answers on Stackoverflow, I've got the code below. However, it doesn't delete the objects of the model. I log the code; the onclick delete button works. It calls delete_test function, but the test model isn't delete. The terminal says

Forbidden (CSRF token missing or incorrect.): /test-management/delete_test/

Thank in advance!

urls.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)

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=request.POST.getlist('items')).delete()
        return HttpResponseRedirect('/test-management/test/')

test_list.html

</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>
</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},
    })
});
</script>
2

2 Answers 2

2

You need to pass a csrfmiddlewaretoken along with the POST data. You can do this by including the template tag {% 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>
Sign up to request clarification or add additional context in comments.

Comments

0

The error is solved by passing a csrfmiddlewaretoken along with the POST data. You can do this by including the template tag {% csrf_token %}

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

I also get to delete object of the model when row's checkbox is checked and delete button is click- by editing:

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/')

Thanks!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.