Home > Mobile >  social blog Like button
social blog Like button

Time:07-29

Like button is not working. here is my code please check it gives error Cannot resolve keyword 'username' into field. Choices are: id, post_id, post_id_id, user_id, user_id_id

view.py

def like_post(request):
    user_id = request.user.username
    post_id = request.GET.get('post_id')
    post = Post.objects.get(id=post_id)

    like_filter = LikePost.objects.filter(post_id=post_id,username=user_id).first()

    if like_filter == None:
        new_like = LikePost.objects.create(post_id=post_id, username=user_id)
        new_like.save()
        post.no_of_likes = post.no_of_likes 1
        post.save()
        return redirect('showpost.html')
    else:
        like_filter.delete()
        post.no_of_likes = post.no_of_likes-1
        post.save()
        return redirect('showpost.html')

model.py

class LikePost(models.Model):
    post_id = models.ForeignKey(Post,on_delete=models.CASCADE, null=True)
    user_id = models.ForeignKey(User,on_delete=models.CASCADE, null=True)

html.file

<div >
{% if post.no_of_likes == 0 %} No likes

{% elif post.no_of_likes == 1 %}

Liked by {{post.no_of_likes}} person

{% else %}

Liked by {{post.no_of_likes}} people

{% endif %}

CodePudding user response:

user_id = User.objects.get(id=request.user.pk)

Get the object and pass it in to create a query it will work,Because ForeignKey accept object intend of id or any value

CodePudding user response:

You'd need to change your likefilter as currently you're trying to retrieve a LikePost with post_id and user_id attributes. You should have something like:

like_filter = LikePost.objects.filter(post_id=post_id,user_id=user_id).first()

And I may be wrong but it seems like your user_id contains the username value of your user instead of its id, so you could also change that to:

user_id = request.user.id

CodePudding user response:

user_id = request.user.pk
like_filter = LikePost.objects.filter(post_id=post_id, pk=user_id).first()

try this way

  • Related