Click here to Skip to main content
15,508,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am making a blog website through Django. right now i having a problem in making of Like button.please help.

What I have tried:

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 class="flex space-x-4 lg:font-bold col-lg-6 d-flex flex-wrap mt-2">

   <a href="/like-post?post_id={{post.id}}" class="flex items-center space-x-2">

      <div class="p-2 rounded-full text-black  d-flex">

       <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="25" height="25" class="">

         <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />

       </svg>

    {% if post.no_of_likes == 0 %}
     <p class="mb-0">No likes</p>
    {% elif post.no_of_likes == 1 %}
    <p>Liked by {{post.no_of_likes}} person</p>
    {% else %}
    <p>Liked by {{post.no_of_likes}} people</p>
    {% endif %}
     </div>
  </a>
</div>
Posted
Comments
Richard MacCutchan 29-Jul-22 9:36am    
You have not explained which line gives the error. But at a guess you are trying to assign an invalid type to an object attribute. Check your class definitions to see if they are correct.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900