How can i submit the is_read
checkbox field into database using ajax? when i try to chick the checkbox field i am getting this error 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)
},
});
});
I'm not sure about the Django part but
For the Html, you are creating multiple checkboxes with the same id, which is invalid, use a class instead.
<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>
And for the JavaScript use the class as the selector and select the correct row.
Also, the content type is wrong since you're not sending JSON so remove 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)
},
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.