Django Rest frameworks: request.Post vs request.data?

前端 未结 2 1598
无人共我
无人共我 2021-02-12 23:01

The Django Rest Frameworks has this to say about POST, quoting a Django dev

Requests

If you\'re doing REST-based web service stuff ...

2条回答
  •  离开以前
    2021-02-12 23:37

    I think some users get redirected here when trying to get data from the POST body in vanilla Django (when they aren't using the Django REST framework). In case you're using a basic Django endpoint you use request.body to get data from the body of the request so long as it isn't form data that's being sent to the server (in that case use request.POST). This is different from the request.data attribute that is needed for accessing data with Django REST framework.

    from json import loads
    def login(request):
        json = loads(request.body)
        print(json['username']) # Prints the value associated with 
    

    loads(request.body) is needed because request.body returns a byte string. loads will convert that byte string into a dictionary.

    request.BODY, request.data, and request.DATA are all undefined for Django's default request object.

    https://docs.djangoproject.com/en/3.1/ref/request-response/

    Notice there is no .data attribute under HttpRequest which differs from the Django REST framework request.

    (This doesn't answer the original question but might help users that end up here who aren't using the REST framework)

提交回复
热议问题