How to update a list of To-Do items with checkboxes and save changes using React and Django?

I am trying to update a list of To-Do items using React for the frontend and Django for the backend. Each item has a checkbox to mark it as complete or incomplete. When I click the "Save" button, I want the updated data to be sent to the backend via a PUT request. However, I am facing issues with updating the items properly.

Here’s my React handleSave function that triggers the PUT request:


    const handleSave = async (e) => {
      e.preventDefault();
      console.log('handleSave called');

      const updatedItems = items.map((item) => {
        const checkbox = e.target[`c${item.id}`];
        console.log(`Processing item id ${item.id}, checkbox value:`, checkbox?.checked);
        return {
          id: item.id,
          todolist: 1,
          text: item.text,
          complete: checkbox ? checkbox.checked : false,
          duration: item.duration,
        };
      });

      try {
        console.log('Payload to send:', updatedItems);
        const response = await axios.put(
          `${import.meta.env.VITE_API_URL}/todo-items/1`, // Update the endpoint if needed
          updatedItems,
          {
            headers: { 'Content-Type': 'application/json' }, // Set proper headers
          }
        );
        console.log('Items updated successfully:', response.data);
      } catch (error) {
        console.error('Error updating items:', error.message, error.response?.data);
      }
    };

Here’s the Django view handling the request:

@api_view(['GET', 'PUT'])
def todo_items(request, id):
    try:
        ls = ToDoList.objects.get(id=id)
    except ToDoList.DoesNotExist:
        return Response({"error": "List not found"}, status=404)

    if request.method == 'GET':
        incomplete_items = ls.item_set.filter(complete=False)
        complete_items = ls.item_set.filter(complete=True)
        items = incomplete_items.union(complete_items, all=True)
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)

    if request.method == 'PUT':
        if not isinstance(request.data, list):
            return Response({"error": "Invalid data format, expected a list."}, status=400)

        errors = []
        for item_data in request.data:
            try:
                item = Item.objects.get(id=item_data["id"])
                item.complete = item_data["complete"]
                item.save()
            except ObjectDoesNotExist:
                errors.append({"id": item_data["id"], "error": "Item not found."})
            except KeyError:
                errors.append({"id": item_data.get("id", None), "error": "Missing fields."})

        if errors:
            return Response({"message": "Partial update completed with errors.", "errors": errors}, status=207)

        return Response({"message": "Items updated successfully!"})

right now the payload is {id: 1, todolist: 1, text: 'respond to emails', complete: false, duration: '02:00:00'} 1 : {id: 2, todolist: 1, text: 'wash the dishes', complete: false, duration: '00:30:00'} 2 : {id: 3, todolist: 1, text: 'finish chemistry homework', complete: false, duration: '03:00:00'} 3 : {id: 4, todolist: 1, text: 'set the table', complete: true, duration: '00:05:00'} 4 : {id: 5, todolist: 1, text: 'clean the table', complete: true, duration: '00:05:00'} 5 : {id: 7, todolist: 1, text: 'eat the oranges', complete: true, duration: '03:00:00'} length : 6" and this matches the format of the db on the api side so im not sure why theres an error

    PUT http://127.0.0.1:8000/api/todo-items/1 500 (Internal Server Error)
dispatchXhrRequest @ axios.js?v=48ceec0d:1653
xhr @ axios.js?v=48ceec0d:1533
dispatchRequest @ axios.js?v=48ceec0d:2008
_request @ axios.js?v=48ceec0d:2223
request @ axios.js?v=48ceec0d:2120
httpMethod @ axios.js?v=48ceec0d:2252
wrap @ axios.js?v=48ceec0d:8
handleSave @ App.jsx:46
processDispatchQueue @ react-dom_client.js?v=48ceec0d:11577
(anonymous) @ react-dom_client.js?v=48ceec0d:11988
batchedUpdates$1 @ react-dom_client.js?v=48ceec0d:2539
dispatchEventForPluginEventSystem @ react-dom_client.js?v=48ceec0d:11683
dispatchEvent @ react-dom_client.js?v=48ceec0d:14608
dispatchDiscreteEvent @ react-dom_client.js?v=48ceec0d:14589Understand this errorAI
App.jsx:55 Error updating items: Request failed with status code 500"
Вернуться на верх