[英]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
: 在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;
}
}
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
: 在服务器端,然后将此端点映射到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. 但是,当对此端点发出请求并调用该视图时,发生内部服务器错误,状态码为500。
AttributeError: 'Request' object has no attribute 'senderId' AttributeError:“请求”对象没有属性“ senderId”
How can I make reference to the fields, senderId
and receiverId
on the django rest framework client side? 如何在Django senderId
Framework客户端上引用字段senderId
和receiverId
?
the request data is in data
field of request object. 请求数据在请求对象的data
字段中。
checkout http://www.django-rest-framework.org/api-guide/requests/#data 结帐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. request.data是一个python字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.