Django Like Button

django

Solution

I assume that many users can like many pictures.

You'll need another model:

class Like(models.Model):
    user = models.ForeignKey(User)
    picture = models.ForeignKey(Picture)
    created = models.DateTimeField(auto_now_add=True)

And call the number of likes like this:

p = Picture.objects.get(...)
number_of_likes = p.like_set.all().count()

To increase the number of likes you might want to do something like that in a view:

def like(request, picture_id):
    new_like, created = Like.objects.get_or_create(user=request.user, picture_id=picture_id)
    if not created:
        # the user already liked this picture before
    else:
        # oll korrekt

so whenever someone clicks on the same like button twice, he only counts as one.

To find out if the current user already likes the displayed image or not:

def picture_detail(request, id):
    pic = get_object_or_404(Picture, pk=id)
    user_likes_this = pic.like_set.filter(user=request.user) and True or False

Hope this helps.

Problem

I'm been trying to create a like button for my pet pictures in each board for my app but I can't figure out how to create one because it contains an integer. Usually, I have an idea and understanding of the functions I create. When the user clicks on the like button. The like button will increase by 1 and it will display near the picture. This is my picture module. ``` class Picture(models.Model): user = models.ForeignKey(User) board = models.ForeignKey(Board ,related_name='lo') image = models.FileField(upload_to="images/",blank=True,null=True) description = models.TextField() is_primary = models.BooleanField(default=False) def __unicode__(self): return self.description ``` Can someone please help me create the basics of a like button? So I can understand the logic of the function.

Original source