Answer the question
In order to leave comments, you need to log in
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 %}
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();
});
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'})
Answer the question
In order to leave comments, you need to log in
Firstly:
...
'pk': box.attr('data-task-id')
...
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 questionAsk a Question
731 491 924 answers to any question