Skip to content

Commit

Permalink
Merge e3f5653 into b511faa
Browse files Browse the repository at this point in the history
  • Loading branch information
ongebo committed Dec 18, 2018
2 parents b511faa + e3f5653 commit a64f8fd
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 8 deletions.
8 changes: 7 additions & 1 deletion authors/apps/profiles/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ class UserProfile(models.Model):

def __str__(self):
return self.user.username



class Follow(models.Model):
follower = models.ForeignKey(User, on_delete=models.CASCADE)
followed = models.ForeignKey(UserProfile, on_delete=models.CASCADE)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Expand Down
8 changes: 7 additions & 1 deletion authors/apps/profiles/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import serializers
from .models import UserProfile
from .models import UserProfile, Follow


class GetUserProfileSerializer(serializers.ModelSerializer):
Expand All @@ -13,3 +13,9 @@ class UpdateProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['photo','bio','fun_fact']


class FollowSerializer(serializers.ModelSerializer):
class Meta:
model = Follow
fields = ('follower', 'followed')
7 changes: 4 additions & 3 deletions authors/apps/profiles/urls.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from django.urls import path

from .views import UserProfiles,Updateprofile
from .views import UserProfiles, Updateprofile, FollowView, FollowersView

urlpatterns = [
path('users/profiles', UserProfiles.as_view()),
path('users/profiles/', Updateprofile.as_view(),name="profile")

path('users/profiles/', Updateprofile.as_view(),name="profile"),
path('profiles/<username>/follows/', FollowView.as_view()),
path('profiles/<username>/followers/', FollowersView.as_view()),
]
100 changes: 97 additions & 3 deletions authors/apps/profiles/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
from django.shortcuts import render
from .serializers import GetUserProfileSerializer, UpdateProfileSerializer
from .serializers import (
GetUserProfileSerializer, UpdateProfileSerializer, FollowSerializer
)
from rest_framework import generics, viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework import status
from .models import UserProfile
from .models import UserProfile, Follow
from authors.apps.authentication.models import User
from rest_framework.exceptions import NotFound


class UserProfiles(generics.ListAPIView):
Expand All @@ -23,4 +27,94 @@ def update(self,request):
serializer =self.serializer_class(request.user.userprofile, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.update(request.user.userprofile, request.data)
return Response(serializer.data)
return Response(serializer.data)


class FollowView(APIView):
permission_classes = (IsAuthenticated,)

def post(self, request, username):
follower_id = User.objects.get(username=request.user.username).id
try:
followed_id = User.objects.get(username=username).id
self.profile_id = UserProfile.objects.get(user_id=followed_id).id
self.verify_following_criteria_met(follower_id, followed_id, username)
except Exception as e:
if isinstance(e, User.DoesNotExist):
raise NotFound('No user with name {} exists.'.format(username))
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
follow_data = {'follower': follower_id, 'followed': self.profile_id}
serializer = FollowSerializer(data=follow_data)
serializer.is_valid(raise_exception=True)
serializer.save()
profile = self.get_followed_profile(self.profile_id)
return Response(profile, status=status.HTTP_201_CREATED)

def verify_following_criteria_met(self, follower_id, followed_id, name):
if follower_id == followed_id:
raise Exception('You cannot follow your own profile.')
query_result = Follow.objects.filter(follower_id=follower_id, followed_id=self.profile_id)
if len(query_result) != 0:
raise Exception('Already following {}.'.format(name))

def get_followed_profile(self, followed):
profile = UserProfile.objects.get(id=followed)
serializer = GetUserProfileSerializer(profile)
profile = serializer.data
profile['following'] = True
return profile

def delete(self, request, username):
user_id = User.objects.get(username=request.user.username).id
try:
followed_id = User.objects.get(username=username).id
profile_id = UserProfile.objects.get(user_id=followed_id).id
follow = Follow.objects.filter(follower_id=user_id, followed_id=profile_id)
if len(follow) == 0:
raise Exception('Cannot unfollow a user you are not following.')
follow.delete()
return Response(
{'message': 'Successfully unfollowed {}.'.format(username)},
status=status.HTTP_204_NO_CONTENT
)
except Exception as e:
if isinstance(e, User.DoesNotExist):
return Response(
{'error': 'No user with name {} exists.'.format(username)},
status=status.HTTP_400_BAD_REQUEST
)
return Response(
{'error': str(e)}, status=status.HTTP_400_BAD_REQUEST
)

def get(self, request, username):
try:
user_id = User.objects.get(username=username).id
except:
raise NotFound('No user with name {} exists.'.format(username))
follows = Follow.objects.filter(follower_id=user_id)
serializer = FollowSerializer(follows, many=True)
following = list()
for follow in serializer.data:
user_id = UserProfile.objects.get(id=follow['followed']).user_id
username = User.objects.get(id=user_id).username
following.append(username)
return Response({'following': following}, status=status.HTTP_200_OK)


class FollowersView(APIView):
permission_classes = (IsAuthenticated,)

def get(self, request, username):
try:
user_id = User.objects.get(username=username).id
except:
raise NotFound('No user with name {} exists.'.format(username))
profile_id = UserProfile.objects.get(user_id=user_id).id
followers = Follow.objects.filter(followed_id=profile_id)
serializer = FollowSerializer(followers, many=True)
followers = list()
for follow in serializer.data:
username = User.objects.get(id=follow['follower']).username
followers.append(username)
return Response({'followers': followers}, status=status.HTTP_200_OK)

0 comments on commit a64f8fd

Please sign in to comment.