简体   繁体   中英

How to access request body model fields on DRF server side?

On the android client side, I make a request to a server endpoint with a body of ContactRequest :

public class ContactRequest {

    @SerializedName("senderId")
    @Expose
    private int senderId;

    @SerializedName("receiverId")
    @Expose
    private int receiverId;

    public ContactRequest(int senderId, int receiverId) {
        this.senderId = senderId;
        this.receiverId = receiverId;
    }
}

Using retrofit I pass this object as the request body:

@POST("friendship/create-friend-request/")
Call<Void> sendRequest(@Body ContactRequest contactRequest);

On the server side, I then map this endpoint to the CreateFriendRequestView :

class CreateFriendRequestView(views.APIView):

    def post(self, request, *args, **kwargs):
        sender = User.objects.get(pk=request.senderId)
        receiver = User.objects.get(pk=request.receiverId)
        Friend.objects.add_friend(sender, receiver)
        return Response({'status': 'Request sent'}, status=201)

However when the request is made to this endpoint and when the view is called, an internal server error, status code 500 occurs.

AttributeError: 'Request' object has no attribute 'senderId'

How can I make reference to the fields, senderId and receiverId on the django rest framework client side?

the request data is in data field of request object.

checkout http://www.django-rest-framework.org/api-guide/requests/#data

You have to use:

sender = User.objects.get(pk=request.data.get('senderId'))

request.data is a python dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM