Skip to content

Commit

Permalink
Merge e35f041 into ac135ef
Browse files Browse the repository at this point in the history
  • Loading branch information
ekumamait committed Dec 20, 2018
2 parents ac135ef + e35f041 commit 4c97f21
Show file tree
Hide file tree
Showing 5 changed files with 173 additions and 6 deletions.
27 changes: 26 additions & 1 deletion authors/apps/comments/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.utils import timezone
from authors.apps.articles.models import Article
from authors.apps.authentication.models import User

from authors.apps.core.models import TimestampedModel

class Comments(models.Model):
"""
Expand All @@ -22,6 +22,10 @@ class Comments(models.Model):

created_at = models.DateTimeField(
auto_created=True, auto_now=False, default=timezone.now)
likes = models.IntegerField(
db_index=True,
default=False
)

def __str__(self):
"""
Expand Down Expand Up @@ -68,3 +72,24 @@ def __str__(self):
class Meta:

ordering = ['created_at']


class Impressions(TimestampedModel):
"""
Create an `Impression` with a slug, user details, likes and dislikes.
"""

comment = models.ForeignKey(
Comments,
on_delete=models.CASCADE,
default=None
)
user = models.ForeignKey(
'profiles.UserProfile',
on_delete=models.CASCADE,
default=None
)
likes = models.BooleanField(
db_index=True,
default=None
)
32 changes: 30 additions & 2 deletions authors/apps/comments/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rest_framework import serializers
from authors.apps.articles.models import Article
from authors.apps.comments.models import Comments, Replies
from authors.apps.comments.models import Comments, Replies, Impressions
from authors.apps.authentication.models import User
from authors.apps.profiles.models import UserProfile
from authors.apps.profiles.serializers import GetUserProfileSerializer
Expand Down Expand Up @@ -48,4 +48,32 @@ class Meta:
'article',
'author',
'created_at',
'replies')
'replies',
'likes'
)

class ImpressionSerializer(serializers.ModelSerializer):
"""
Serializes impressions requests and adds to an Article.
"""

createdAt = serializers.SerializerMethodField(method_name='get_created_at')
updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

class Meta:
model = Impressions
fields = (
'comment',
'user',
'likes',
'updatedAt',
'createdAt',
)

def get_created_at(self, instance):

return instance.created_at.isoformat()

def get_updated_at(self, instance):

return instance.updated_at.isoformat()
60 changes: 60 additions & 0 deletions authors/apps/comments/tests/test_like_comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from rest_framework.test import APIClient, APITestCase, APIRequestFactory
from rest_framework import status
from .test_comment_data import CommentTest


class Test_Impression(CommentTest):

def test_add_like_impression(self, response=[]):
article = self.client.post(
'/api/articles/',
data=self.new_article,
format='json')
slug = self.get_slug(article)

self.client.post(
'/api/{}/comments/'.format(slug),
data=self.post_comment,
format='json')

response = self.client.get(
'/api/{}/comments/'.format(slug),
format='json')

for i in response.data['comments']:
self.id = i['id']
id = self.id
response1 = self.client.post('/api/comment/like/{}'.format(id), format='json')

self.assertEqual(response1.status_code, status.HTTP_201_CREATED)

def test_add_like_impression_twice(self, response=[]):
article = self.client.post(
'/api/articles/',
data=self.new_article,
format='json')
slug = self.get_slug(article)

self.client.post(
'/api/{}/comments/'.format(slug),
data=self.post_comment,
format='json')

response = self.client.get(
'/api/{}/comments/'.format(slug),
format='json')

for i in response.data['comments']:
self.id = i['id']
id = self.id
self.client.post('/api/comment/like/{}'.format(id), format='json')
response1 = self.client.post('/api/comment/like/{}'.format(id), format='json')

self.assertEqual(response1.status_code, status.HTTP_201_CREATED)

def test_add_like_impression_doesnot_exist(self):
id = 908766
response1 = self.client.post('/api/comment/like/{}'.format(id), format='json')

self.assertEqual(response1.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Invalid pk \"908766\" - object does not exist.', str(response1.data))
3 changes: 2 additions & 1 deletion authors/apps/comments/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
"""
from django.urls import path
from rest_framework.routers import DefaultRouter
from authors.apps.comments.views import CommentsView, RepliesView
from authors.apps.comments.views import CommentsView, RepliesView, LikeComment

urlpatterns = [

path('<slug>/comments/', CommentsView.as_view()),
path('comment/<Id>/', CommentsView.as_view()),
path('comment/<commentID>/replies/', RepliesView.as_view()),
path('comment/replies/<Id>/', RepliesView.as_view()),
path('comment/like/<comment_id>', LikeComment.as_view()),

]

Expand Down
57 changes: 55 additions & 2 deletions authors/apps/comments/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from authors.apps.comments.models import Comments, Replies
from authors.apps.comments.models import Comments, Replies, Impressions
from authors.apps.articles.models import Article
from authors.apps.comments.serializers import RepliesSerializer, CommentSerializer
from authors.apps.comments.serializers import RepliesSerializer, CommentSerializer, ImpressionSerializer
from rest_framework.generics import (
RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,
ListCreateAPIView)
from ..authentication.models import User
from django.db.models import Count


def get_object(obj_Class, pk):
Expand Down Expand Up @@ -123,3 +128,51 @@ def put(self, request, Id):
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



class LikeComment(ListCreateAPIView):
"""
ca view class to handle liking a comment
"""

permission_classes = (IsAuthenticated,)

def post(self, request, comment_id):
user = User.objects.get(username=request.user.username)

impression = {
'user': user.id,
'likes': True,
'comment': comment_id
}
self.updateimpression(impression)
try:
impression = Impressions.objects.all().filter(comment=comment_id, likes=True)
total_likes = impression.aggregate(Count('likes'))
comment = Comments.objects.get(id=comment_id)
comment.likes = total_likes['likes__count']
comment.save()
except Comments.DoesNotExist:
raise NotFound('A comment with this id does not exist.')
return Response(
{'message': 'i liked this.'},
status=status.HTTP_201_CREATED)

def updateimpression(self, impression):
try:
item = Impressions.objects.filter(
user = impression['user'],
comment = impression['comment']
)[0]
if item.likes == True:
item.likes = False
else:
item.likes = True
item.save()
except:
serializer = ImpressionSerializer(
data=impression
)
serializer.is_valid(raise_exception=True)
serializer.save()

0 comments on commit 4c97f21

Please sign in to comment.