1

Hi i'm trying to use Ajax to send a POST request(include json data) to my Django Rest Framework api after user click the save button on a form. I tried with postman and it worked but when i called it with ajax it raised RawPostDataException error

My api in views.py:

class FilterView(APIView):
    authentication_classes = [SessionAuthentication, JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        login_user = request.user
        paginator = ListPagination()
        queryset = Filter.objects.filter(user=login_user).all().order_by('-pk')
        context = paginator.paginate_queryset(queryset, request)
        serializer = FilterSerializer(context, many=True)

        return paginator.get_paginated_response(serializer.data)

    def post(self, request):
        login_user = request.user
        received_json_data=json.loads(request.body)
        valid_ser = FilterSerializer(data=received_json_data)
        if valid_ser.is_valid():
            post_data = received_json_data["data"]
            filter = Filter.objects.create(data=post_data, user=login_user)
            filter.save()

            return JsonResponse({'code':'200','data': filter.id}, status=200)
        else:
            return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400)

My Serializer:

class FilterSerializer(serializers.ModelSerializer):
    user = serializers.IntegerField(required=False, source="user.id")

    def validate_data(self, data):
        if type(data) is not dict:
            raise serializers.ValidationError("invalid JSON object")

    class Meta:
        model = Filter
        fields = ('__all__')
        extra_kwargs = {'data': {'required': True}}

And my ajax request in html:

$('#save').click( function(event) {
                event.preventDefault();
                var type = $('#type').val();
                var price_min = $('#price_min').val();
                var price_max = $('#price_max').val();
                var size_min = $('#size_min').val();
                var size_max = $('#size_max').val();
                var city = $('#city').val();
                var district = $('#district').val();
                var ward = $('#ward').val();
                var street = $('#street').val();
                var frontend_min = $('#front_end_min').val();
                var frontend_max = $('#front_end_max').val();
                var road = $('#road').val();
                var floor = $('#floor').val();
                var bedroom = $('#bedroom').val();
                var living_room = $('#living_room').val();
                var toilet = $('#toilet').val();
                var direction = $('#direction').val();
                var balcony = $('#balcony').val();
                var filter_data = {
                    'type': type,
                    'price_min': price_min,
                    'price_max': price_max,
                    'size_min': size_min,
                    'size_max': size_max,
                    'city': city,
                    'district': district,
                    'ward': ward,
                    'street': street,
                    'frontend_min': frontend_min,
                    'frontend_max': frontend_max,
                    'road': road,
                    'floor': floor,
                    'bedroom': bedroom,
                    'living_room': living_room,
                    'toilet': toilet,
                    'direction': direction,
                    'balcony': balcony,
                }
                // console.log(filter_data);
                $.ajax({
                    type: "POST",
                    url: "/api/filters/",
                    beforeSend: function (xhr) {    
                        xhr.setRequestHeader('X-CSRFToken', '{{csrf_token}}');
                    },
                    data: JSON.stringify({"data": filter_data}),
                    success: function (data) {
                        if (data.code == 200) {
                            alert("added filter");
                        }
                    }
                });
                return false;
            });

When i call using Ajax it return the following error on my django server:

raise RawPostDataException("You cannot access body after reading from request's data stream")
web_1       | django.http.request.RawPostDataException: You cannot access body after reading from request's data stream

I tried and it worked on my POSTMAN i don't know why it doesn't work on the ajax call

I read about this error and has alot of suggestions using request.data instead of request.body but when i used it in my views , at Ajax call it return:

TypeError: the JSON object must be str, bytes or bytearray, not 'QueryDict'

and on POSTMAN it return the error:

"detail": "Unsupported media type \"text/plain\" in request."

I'm kinda stuck on how to make this work on both POSTMAN and Ajax call, any helps would be nice

Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67
  • 1
    [this](https://stackoverflow.com/questions/19581110/exception-you-cannot-access-body-after-reading-from-requests-data-stream) is a good explanation for *why* this error happens in general, but I'm not sure in your specific case. – Lord Elrond Sep 30 '19 at 03:28

1 Answers1

0

i fixed it by changing request.body to request.data and also changed my ajax code

received_json_data= request.data

and ajax code:

$.ajax({
        type: "POST",
        url: "/api/filters/",
        beforeSend: function (xhr) {    
        xhr.setRequestHeader('X-CSRFToken', '{{csrf_token}}');
         },
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify({"data": filter_data}),
        success: function (data) {
        if (data.code == 200) {
             alert("added filter");
            }
         }
      });
Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67