4

I am using django-restframework, I use postman POST json data to my project but I got the error like tittle, I have set raw and application/json here is the code from postman.

POST /account/post/reply/ HTTP/1.1
Host: localhost:8000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a0c7bd93-631e-4c7a-8106-87f018eaf7da

{
    "user": "michael",
    "userid": "1",
    "ihelpid": 6,
    "tittle": "6",
    "info": "6",
    "label": "3",
    "tel": "dxy970525",
    "picture1": null,
    "picture2": null
}

my code is really easy only like :

from rest_framework.parsers import JSONParser,ParseError

class ReplyViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """

    pagination_class=PageNumberPagination
    queryset = Forum_reply.objects.all()
    serializer_class = ReplySerializer

    #filter
    filter_backends = (DjangoFilterBackend, )
    filter_fields = ['postID',]
    def create(self, request, *args, **kwargs):
        print(request.data)
        data = JSONParser().parse(request)
        return HttpResponse("ok")

After I use viewsets,this error occur,I have print it on shell but it is no problem

Michael Porter
  • 71
  • 1
  • 1
  • 3
  • Hey, can you debug by checking out what the variable `request` is? JSONParser should work if `request` is a JSON string. Seems like it's not so in this case. – rdas Mar 31 '19 at 09:55
  • You should instead use `parser_classes = (JSONParser,)` (google it). This will automatically parse request data for you, so you can access it in `request.data` – mariodev Mar 31 '19 at 12:38
  • If i print request,I get `` – Michael Porter Mar 31 '19 at 14:57
  • Thinks for telling me print request but not request.data.. – Michael Porter Mar 31 '19 at 15:04
  • please check your function where you are sending requests. I was facing same issue, i resolved it by changing this.http.delete(this.APIUrl + '/website', val) to this.http.delete(this.APIUrl + '/website',{body:val}). – abduljalil Oct 21 '21 at 07:27

6 Answers6

5

I actually had the same error, you need to use JSON.stringify(data) like the following in case you are using ajax :

datato= {
    "id" : 3,
    "title" : "level up",
    "author" : "jason rock"

}

$.ajax({
    method:'POST',
    url:"/home/api",
    data : JSON.stringify(datato),

})

@SeriForte 's answer pointed me in the right way

El Bachir
  • 111
  • 1
  • 4
2

I have solved this problem,I can access data now

I changed my older code

print(request.data)
data = JSONParser().parse(request)

this will get an error. If I code like below:

print(request)
data = JSONParser().parse(request)

Then I can access data in the dictionary.

So, I did not know why but the issue is fixed

Art
  • 2,836
  • 4
  • 17
  • 34
Michael Porter
  • 71
  • 1
  • 1
  • 3
2

In my case, i was not sending a correct json in the data. So please check that.

MrSoloDolo
  • 406
  • 5
  • 10
0

if you use a Javascript fetch request, you have to stringify the JSON Data object like so

let data = {
            "key1": 1,
            "key2": "text"
          }
fetch(url, {
            method: 'POST',
            headers: {
              'content-type': 'application/json',
              'X-CSRFToken': csrftoken
            },
            body: JSON.stringify(data) // <-- do not include the Json array directly
          }).then(function (response) {
            // ...
            console.log(response);
            return response.json();
          }).then(function (body) {
            // ...
            console.log(body);
          }).catch(err => {
              console.log(err)
          })
SeriForte
  • 630
  • 7
  • 13
0

If you're using postman it's not possible to put comments in the body > raw section.
Like this enter image description here

So it is better to remove the commented part out.
HTH

Mebatsion Sahle
  • 409
  • 2
  • 9
0

You need to send the data in json format as well, for example, if your serializer looks something like this -

class exampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = example
        fields = ('title', 'content')

so when you're creating a new object of the above class you need to send data in the format below -

{"title": "first","content": "hey"},

This solved the bug for me!

kakou
  • 636
  • 2
  • 7
  • 15
Jayri
  • 1
  • 1