Search code examples
pythondjangomodels

Like functionality in Django


I'm developing a social platform and currently coding the like functionality for user posts. However, I can't seem to make it work. These are my Models.py:

class Post(models.Model):
    user = models.ForeignKey(User)
    posted = models.DateTimeField(auto_now_add=True)
    content = models.CharField(max_length=150)
    picturefile = models.ImageField(upload_to="post_content", blank=True)

class Like(models.Model):
    user = models.ForeignKey(User, null=True)
    post = models.ForeignKey(Post, null=True)

I pass the post ID through my url as 'post_id', and then in my views:

def liking(request, post_id):
    newlike = Like.objects.create()
    newlike.post = post_id
    newlike.user = request.user
    newlike.save()
    return redirect(reverse('dashboard'))

However, it returns the following error:

Cannot assign "'47'": "Like.post" must be a "Post" instance.

Does anyone knows what I'm missing or doing wrong?


Solution

  • You are passing newlike.post a number (integer field) while it is expecting a Post instance.

    This sould work:

    from django.http.shortcuts import get_object_or_404
    
    def liking(request, post_id):
        post = get_object_or_404(Post, id=post_id)
        newlike = Like.objects.create(user=request.user, post=post)
        return redirect(reverse('dashboard'))
    

    Note 1: Better use the handy shortcut get_object_or_404 in order to raise a 404 error when the specific Post does not exist. Note 2: By calling objects.create will automatically save into the db and return an instance!