Hello,
I have a to do app that I’m working on and I have 3 models, a custom user model, a list model, and an item model. The item model represents list items that can be on a specific list. The item has a foreign key relationship to a list and a list is mapped to a specific user.
In my item model I have a field for “completed”, which defaults to False, but I would like this to be updated to True if a user clicks a checkbox. I would like to do this in JavaScript, but I’m unsure about how to properly update a model with JS. As a note, I haven’t serialized my models, but if this would make it easier than just updating a model directly, then I would certainly look into that.
Here is my JS code that I’ve written, and you can see from the photo I’ve added at the bottom, I’m getting a response in the console, which is great, but the url route is not what I was expecting from my fetch request in my JS code.
// function to mark list item as completed.
document.addEventListener('DOMContentLoaded', function() {
let checkboxes = document.querySelectorAll('#completed')
checkboxes.forEach(checkbox => {
checkbox.onclick = function() {
const pk = checkbox.dataset.id
fetch(`/${pk}/item`, {
method: 'PUT',
body: JSON.stringify({
completed: (completed ? false : true)
})
})
}
});
});
Here is my urls.py file. (I’ve excluded the imports, but i’ve imported my views)
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('<int:pk>/todolists/', ToDoListView.as_view(), name='todolists'),
path('list_new/', ToDoListCreateView.as_view(), name='list_new'),
path('<int:pk>/item_new/', item_new_view, name='item_new'),
path('<int:pk>/delete/', ToDoListDeleteView.as_view(), name='list_delete'),
path('<int:pk>/item', mark_item_as_completed_view, name='item_completed')
]
Here is the specific view that is going to handle the fetch. I’ve worked on this bit the least:
def mark_item_as_completed_view(request, pk):
if request.method == "PUT":
return JsonResponse({
"success: completed"
})