在Android客户端,我向身体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;
}
}
使用改造我将此对象作为请求正文传递:
@POST("friendship/create-friend-request/")
Call<Void> sendRequest(@Body ContactRequest contactRequest);
在服务器端,我将此端点映射到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)
但是,当向此端点发出请求并且调用视图时,会发生内部服务器错误,状态代码为500。
AttributeError:'Request'对象没有属性'senderId'
如何在django rest框架客户端上引用字段senderId
和receiverId
?
答案 0 :(得分:1)
请求数据位于请求对象的sender = User.objects.get(pk=request.data.get('senderId'))
字段中。
结帐http://www.django-rest-framework.org/api-guide/requests/#data
你必须使用:
{{1}}
request.data是一个python字典。