My problem is that I have a list of 'Assignment' objects which all have a field called 'status'. The status is either true or false, and the user can choose to change the value by clicking on a checkbox for a specific assignment.
This is what the frontend looks like, each assignment has a checkbox which is its 'status'
My current solution is this:
course-detail.html:
{% for assignment in assignments %}
<tr>
<td scope="row" style="text-align: center">
<form>
{% csrf_token %}
{% if assignment.status %}
<input type="checkbox" checked onclick='assignmentFinish("False","{{assignment.id}}")'>
{% else %}
<input type="checkbox" onclick='assignmentFinish("True","{{assignment.id}}")'>
{% endif %}
</form>
</td>
<td><h5><span class="badge badge-{{assignment.module.colour}}">{{assignment.module}}</span></td>
<td><a href="{{ assignment.assigmentFile.url }}">{{assignment.title}}</a></td>
<td>{{assignment.deadline}}</td>
...
</tr>
{% endfor %}
ajax code:
function assignmentFinish(value,assignment) {
link = "{% url 'uni:finish-assignment' %}";
$.ajax({
type:'POST',
url: link,
data:{
status: value,
assignmentID: assignment,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function(){
}
});
}
views.py:
def finishAssignment(request):
# Get the product that user has wished for
assignmentID = request.POST['assignmentID']
status = request.POST['status']
assignment = Assignment.objects.get(pk=assignmentID)
print(status)
if status == 'True':
print("saving to true")
assignment.status = True
else:
print("saving to false")
assignment.status = False
assignment.save()
return HttpResponse('')
enter code here
models.py
class Assignment(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
course = models.ForeignKey(Course, on_delete=models.CASCADE, default=None)
module = models.ForeignKey(Module, on_delete=models.CASCADE)
deadline = models.DateField()
assignmentFile = models.FileField(default=None)
status = models.BooleanField()
This solution will work once, but once the user clicks the checkbox again, it will not save the information in the database. For example, if the user clicks a checkbox which is initially unchecked repeatedly, the print statements will be this:
True
saving to true
[15/Jul/2020 16:11:51] "POST /uni/finishAssignment HTTP/1.1" 200 0
True
saving to true
[15/Jul/2020 16:11:52] "POST /uni/finishAssignment HTTP/1.1" 200 0
True
saving to true
It shows that the ajax request is being called, but the print statements should be alternating between true and false. The reason for this is probably because the information on the page which displays the checkbox is not updated after the new values are saved in the database after the first time. How do I fix this?