50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import permissions, status
|
|
from rest_framework.authentication import SessionAuthentication
|
|
|
|
from django.utils.translation import gettext as _
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
from ..models import ProfileModel, FriendModel
|
|
from ..serializers.ProfileSerializer import ProfileSerializer
|
|
|
|
|
|
class GetFriendsView(APIView):
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
authentication_classes = (SessionAuthentication,)
|
|
|
|
def get(self, request):
|
|
return Response(ProfileSerializer(request.user.profilemodel.get_friends(), many=True).data)
|
|
|
|
|
|
class EditFriendView(APIView):
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
authentication_classes = (SessionAuthentication,)
|
|
|
|
def get_object(self):
|
|
return self.request.user.profilemodel
|
|
|
|
def post(self, request, pk=None):
|
|
user_profile = self.get_object()
|
|
friend_profile = get_object_or_404(ProfileModel, pk=pk)
|
|
|
|
if user_profile.pk == pk:
|
|
return Response(_('You can\'t be friend with yourself.'), status.HTTP_400_BAD_REQUEST)
|
|
|
|
if user_profile.is_friend(friend_profile):
|
|
return Response(_('You are already friend with this user.'), status.HTTP_400_BAD_REQUEST)
|
|
|
|
FriendModel(friend1=user_profile, friend2=friend_profile).save()
|
|
return Response(_('Friendship succssfully created.'), status.HTTP_201_CREATED)
|
|
|
|
def delete(self, request, pk=None):
|
|
user_profile = self.get_object()
|
|
friend_profile = get_object_or_404(ProfileModel, pk=pk)
|
|
|
|
if not user_profile.is_friend(friend_profile):
|
|
return Response(_('You are not friend with this user.'), status.HTTP_400_BAD_REQUEST)
|
|
|
|
user_profile.delete_friend(friend_profile)
|
|
return Response(_('Friendship succssfully deleted.'))
|