-2

I know I can do this easily in models.py but I don't have like model in my app. I have post app and there's like field. so I want to restrict it in my views.py Here's my try but I don't understand why it won't restrict it

@login_required
def like_post(request, pk):
    if User.objects.filter(pk = pk, id = request.user.id).exists():
        return HttpResponse('You already voted for this, cheater')
    else:
        liked_post = Post.objects.get(id=pk)
        count = liked_post.likes
        count += 1
        liked_post.likes = count
        liked_post.save()


    return redirect('/community/post/%s' %liked_post.id)
rosababy
  • 167
  • 10
  • Because this code makes no sense. `pk` and `id` mean the same thing. All you're doing is checking that the current User exists, which it obviously does. – Daniel Roseman Jun 09 '19 at 17:58

1 Answers1

0

First of all about mistakes: In "if" statement you are trying to find a user by a post primary key. Moreover, you are performing a search both by id and pk, while they are technically the same in your case. See: Django queries - id vs pk

As for implementation: I am afraid it's impossible to track "cheaters" in your implementation. You cannot understand that "This user already liked this post" without storing likes. There is no data that tells you this fact. "Else" part is ok, but if you want to track "likers", some customisation is needed.

The easiest option is to add ManyToMany field referencing User to your Post model and call it "likers". The table with columns "user_id", "post_id" will be created under the hood and will tell that "This user liked this post".

from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    ...
    likers = models.ManyToManyField(User)
    ...

And in your view liked_post.likers.add(request.user), to add current user to likers and liked_post.likers.filter(user=request.user).exists() to find "cheaters"

cepbuch
  • 486
  • 1
  • 4
  • 10