V
V
Vlad Ilnitskiy2016-03-10 00:20:57
JavaScript
Vlad Ilnitskiy, 2016-03-10 00:20:57

Set up ajax for checkboxes in Django?

There is a list of tasks (tasks) that are displayed on the main page, and each is characterized by the status "completed / not completed".
Task: set up ajax-auto-update, so that when you click on the checkbox, the state of the task changes and is entered into the database.

home.html

{% extends "base.html" %}
{% for task in tasks %}
        <div class="task-box">
         <input type="checkbox" data-task-id="{{ task.id }}" {% if task.checkbox == True %} checked="1"{% endif %}/>
         {% if task.checkbox == True %}<del>{{ task.name }}</del><hr>
         {% else %} {{ task.name }}<hr>
         {% endif %}
        </div>
    {% endfor %}


main.js
function initJournal() {
 $('.task-box input[type="checkbox"]').click(function (event) {
  var box = $(this);
  var myurl = "/home/";
  $.ajax({
   type: 'POST',
   async: true,
   dataType: 'json',
   url: myurl,
   data: {
    'pk': box.data('task-id')
   },
   error: function (xhr, status, error) {
    alert(error);
   },
   success: function (data, status, xhr) {
    alert(data['key']);
   }
  });
 });
}

 $(document).ready(function(){
 initJournal();
 });


views.py
class ....
 def post(self, request, *args, **kwargs):
        #turn super(TaskCreateView, self).post(request, *args, **kwargs)
        data = request.POST
        task = Task.objects.get(pk=data['pk'])
        task.checkbox = True
        task.save()
        return JsonResponse({'status': 'success'})


But for some reason it does not work, and when you click on the checkbox, the "Not Found" alert is displayed.
I would be grateful for any help, I have already tried a bunch of different options, nothing works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Voronkov, 2016-03-10
@DmitryVoronkov

Firstly:

...
'pk': box.attr('data-task-id')
...

This is to find the right task.
But now a 403 error will be thrown, for this you need:
in views.py
from django.views.decorators.csrf import csrf_exempt
class Any(FormView):
...

any = csrf_exempt(Any.as_view())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question