0

我有一个论坛模型。我有一个问题、正文、pub_date、图像、创建者、喜欢的字段。从管理员,我可以为特定论坛的给定用户添加喜欢。但是我现在很困惑,如何在视图中为 request.user 添加喜欢?

模型.py:

class Forum(models.Model):
    question = models.CharField(max_length=150)
    body = models.TextField()
    pub_date = models.DateTimeField(default=datetime.now)
    image = models.ImageField(upload_to=get_upload_file_name)
    creator = models.ForeignKey(User, related_name="creator_set")
    likes = models.ManyToManyField(User, through="Like")

    def __unicode__(self):
        return self.question

class Like(models.Model):
    forum = models.ForeignKey(Forum)
    liked = models.ForeignKey(User)
    liked_date = models.DateTimeField(default=datetime.now)

    def __unicode__(self):
        return "%s likes %s" % (self.liked, self.forum)

我想过这样做:

>>>forum = Forum.objects.get(id=1)
>>>user = request.user
>>>user.like_set.add(forum)

但是,它没有帮助。请,任何帮助将不胜感激。谢谢你。

4

1 回答 1

1

首先,您需要创建一个以视图为目标的 URL。URL 将 aforum_id作为 URL 参数传递。

from datetime import datetime
from django.shortcuts import get_object_or_404

@login_required
def update_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like, _ = Like.objects.get_or_create(user=request.user, forum=forum, 
                   defaults={'liked_date': datetime.now()})
    #rest of the code here. 

这是一种方式。您也可以按照您的想法进行操作,但您必须手动控制可能生成的重复项。(您可以在unique_together上指定一个('forum', 'liked')

并删除

@login_required
def delete_likes(request, forum_id):
    forum = get_object_or_404(Forum, id=forum_id)
    like = get_object_or_404(Like, user=request.user, forum=forum)
    like.delete()
    #rest of the code here. 
于 2013-08-17T18:20:04.837 回答