Django APIView data format from AJAX

Viewed 39

I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format:

const data = {
        group_designation: [
            {id: 1},
            {id: 2},
            {id: 3},
        ]
    }

I run an insomnia app and it only accepts this kind of format:

{
"group_designation": [
    {"id": 1},
    {"id": 2},
  ]
}

However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab:

group_designation[0][id]: 1
group_designation[1][id]: 2
group_designation[2][id]: 3

In Django, this is the request.data result:

<QueryDict: {
'group_designation[0][id]': ['1'], 
'group_designation[1][id]': ['2'],
'group_designation[2][id]': ['3']
}>

My code in Django:

    def post(self, request):
        temp_objects = []
        new_data_format = {'group_designation': temp_objects}
        
        serializer = GroupSerializer(data=new_data_format, many=True)
        if serializer.is_valid(raise_exception=True):
            group_data_saved = serializer.save()

        return Response({
            "success": "success!!!"
        })

I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you!

0 Answers
Related