예제 #1
0
def addlike(request, article_id):
    # пока обязательно проверяем
    if request.method == "GET":
            # article_id приходит через GET запрос
            # article_id = request.GET['article_id']
            article = Article.objects.get(id=article_id)  # подхватываем статью из базы
            user = request.user
            try:
                user_liked = Like.objects.get(like_user=user,
                                              like_article=article_id)  # подхватываем лайки к этой статье
            except ObjectDoesNotExist:
                user_liked = None

            if user_liked:
                user_liked.delete()

                article.article_likes -= 1  # Likes.objects.filter(likes_article_id=article_id).count()
                article.save()
            else:
                user_liked = Like(like_article=article)
                article.article_likes += 1
                user_liked.likes_user = user
                article.save()
                user_liked.save()
                return HttpResponse(article.article_likes, content_type='text/html')
                #return redirect(return_path)
                # except ObjectDoesNotExist:
                # raise Http404
    #Лайков к этой статье вообще нет, сразу выходим
    return HttpResponse(0, content_type='text/html')
예제 #2
0
    def post(self, request, *args, **kwargs):
        """Like/dislike posts and comments"""

        user = self.request.user
        is_dislike = request.GET.get('type', None) == 'dislike'
        post_or_comment_id = self.kwargs['pk']
        is_comment = request.GET.get('comment', False)
        if is_comment:
            # Comment to like
            post_or_comment = Comment.objects.get(pk=post_or_comment_id)
            post_id = post_or_comment.post.pk
        else:
            # Post to like
            post_or_comment = Blog.objects.get(pk=post_or_comment_id)
            post_id = post_or_comment.pk

        like_qs = post_or_comment.likes.filter(author=user)
        if like_qs.exists():
            like_obj = like_qs.first()
            if like_obj.dislike == is_dislike:
                like_obj.delete()
            else:
                like_obj.dislike = is_dislike
                like_obj.save()
        else:
            like_obj = Like(dislike=is_dislike, author=user)
            if is_comment:
                like_obj.comment = post_or_comment
            else:
                like_obj.post = post_or_comment
            like_obj.save()

        return HttpResponseRedirect(
            reverse('blog-detail', kwargs={'pk': post_id}))
예제 #3
0
def like_post(request, post_id):
    method = request.POST.get('method')
    if request.method == 'POST':
        post = get_object_or_404(Post, id=post_id)
        if method == 'like':
            if Like.objects.filter(post=post, author=request.user.userprofile):
                raise ValidationError(
                    _('Invalid like: %(value)s'),
                    code='invalid',
                    params={'value': 'already exists'},
                )
            like = Like(author=request.user.userprofile, post=post)
            like.save()
        elif method == 'dislike':
            like = Like.objects.get(author=request.user.userprofile, post=post)
            like.delete()

        post.save()
        post.author.save()
        request.user.userprofile.save()

        response_data = {}
        response_data['post_id'] = post.id
        response_data['likes'] = post.like_set.count()
        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )
    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )
예제 #4
0
def likepost(request, pk=None):
    post = get_object_or_404(Post, id=pk)
    if request.user.is_authenticated:
        like = Like.objects.filter(post=post, author=request.user).first()
        if not like:
            like = Like(post=post, author=request.user)
            like.save()
        else:
            like.delete()
    return HttpResponse(Like.objects.filter(post=post).count())
예제 #5
0
파일: views.py 프로젝트: NeRo8/neroblog
def PostLike(request, pk):
    myarticle = Post.objects.get(pk=pk)  # Берем статью з id = pid
    myuser = request.user  # та користувача з id 1

    if not Like.objects.filter(post_id=pk).filter(user=myuser):
        newLike = Like(post_id=myarticle, user=myuser)
        newLike.save()
        myarticle.likeit += 1
        myarticle.save()

    return HttpResponseRedirect(reverse('post-detail', args=[pk]))
예제 #6
0
파일: views.py 프로젝트: victor0198ebs/blog
def PostDislikeView(request, pk):
    # post = Post.objects.get(pk=)
    # user = User.objects.get(pk=)
    post_id = request.POST.get('post_id', None)
    user_id = request.POST.get('user_id', None)
    print(post_id)
    print(user_id)
    post_instance = Post.objects.get(id=post_id)
    user_instance = User.objects.get(id=user_id)

    if post_id and user_id:
        like = Like(like_status=False, post=post_instance, user=user_instance)
        like.save()

    return redirect('/post/' + str(post_id))
예제 #7
0
 def generate_answers(self, answers_cnt):
     print(f"GENERATE ANSWERS {answers_cnt}")
     uids = list(
         Profile.objects.values_list(
             'id', flat=True))
     qids = list(
         Question.objects.values_list(
             'id', flat=True))
     for i in range(answers_cnt):
         a=Answer.objects.create(
             author_id=choice(uids),
             question_id=choice(qids),
             text=fake.sentence(),
             rating=fake.random_int(1, 100))
         l = Like(content_object=a, positive=fake.random_int(1, 100), negative=-fake.random_int(1, 100))
         l.save()
         a.rating = l.rating
         a.save()
예제 #8
0
def articleLike(request):
    token = request.POST['token']

    user_token = Token.objects.filter(key=token)
    if len(user_token) == 0:
        return Response('nologin')

    article_id = request.POST['article_id']
    article = Article.objects.get(id=article_id)

    liked = Like.objects.filter(belong=article, belong_user=user_token[0].user)
    if liked:
        liked[0].delete()
        return Response('ok')
    else:
        new_like = Like(belong=article, belong_user=user_token[0].user)
        new_like.save()
        return Response('ok')
예제 #9
0
 def generate_questions(self, questions_cnt):
     print(f"GENERATE QUESTIONS {questions_cnt}")
     uids = list(
         Profile.objects.values_list(
             'id', flat=True))
     tags = list(
         Tag.objects.values_list(
             'id', flat=True))
     for i in range(questions_cnt):
         q=Question.objects.create(
             author_id=choice(uids),
             title=fake.sentence(),
             text='\n'.join(fake.sentences(fake.random_int(2, 5))),
             rating = fake.random_int(1,100))
         l = Like(content_object=q, positive=fake.random_int(1,100), negative= -fake.random_int(1,100))
         l.save()
         q.rating = l.rating
         q.save()
         for j in range(1, fake.random_int(1, 7)):
             q.tag.add(choice(tags))
예제 #10
0
    def get(self, request, **kwargs):
        blog = Blog.objects.get(id=kwargs['blog_pk'])
        is_like = Like.objects.filter(user=request.user).filter(post=blog).count()

        # いいねを解除する
        if is_like > 0:
            liking = Like.objects.get(post__id=kwargs['blog_pk'], user=request.user)
            liking.delete()
            blog.like_num -= 1
            blog.save()

            return JsonResponse({"like": blog.like_num})

        # いいねする
        blog.like_num += 1
        blog.save()
        like = Like()
        like.user = request.user
        like.post = blog
        like.save()

        return JsonResponse({"like": blog.like_num})
예제 #11
0
파일: views.py 프로젝트: gizaju10/django
def like(request, *args, **kwargs):
    post = Post.objects.get(id=kwargs['pk'])
    is_like = Like.objects.filter(user=request.user).filter(post=post).count()
    # unlike
    if is_like > 0:
        liking = Like.objects.get(post__id=kwargs['pk'], user=request.user)
        liking.delete()
        post.like_num -= 1
        post.save()
        messages.warning(request, 'いいねを取り消しました')
        return redirect(
            reverse_lazy('blog:post_detail', kwargs={'pk': kwargs['pk']}))
    # like
    post.like_num += 1
    post.save()
    like = Like()
    like.user = request.user
    like.post = post
    like.save()
    messages.success(request, 'いいね!しました')
    return HttpResponseRedirect(
        reverse_lazy('blog:post_detail', kwargs={'pk': kwargs['pk']}))
예제 #12
0
파일: views.py 프로젝트: Shaxv/PeopleBook
def like_post(post, user):
    l = Like(post=post, user=user)
    l.save()