I am building a drf backend api for my android app. I need the API to be able to send friend requests to the relevant users from a user. To do this I am using the django-friendship library. In their documentation they say:
Create a friendship request:
other_user = User.objects.get(pk=1)
Friend.objects.add_friend(
request.user, # The sender
other_user, # The recipient
message='Hi! I would like to add you') # This message is optional
My question is where should this code be written. I know that it belongs in a view, but what kind of view? Could someone give me an example?
I would probably add it to the view that handles any update to the users friendships. For example, if you have a view that handles submission of a friend requests via some endpoint it might look like this:
class CreateFriendRequestView(APIView):
def post(self, request, *args, **kwargs):
other_user = User.objects.get(pk=request.data['other_user'])
Friend.objects.add_friend(
request.user,
other_user,
message='Hi! I would like to add you')
return Response({'status': 'Request sent'}, status=201)