检查用户是否在模板中对帖子进行了投票

时间:2017-05-31 08:16:43

标签: python django django-models

这是我的Post型号:

模型

class Post(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    title = models.TextField(max_length=76)
    content = models.TextField(null=True, blank=True)
    ...


class PostScore(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    post = models.ForeignKey(Post, related_name='score')
    upvotes = models.IntegerField(default=0)
    downvotes = models.IntegerField(default=0)

这是我的模板。我想做这样的事情......如果用户对帖子进行了投票或投票,则隐藏upvote / downvote按钮:

{% if request.user in Post.has_answered %}
{% else %}
    <img src="upvote.png" class="upvote" />
    <img src="downvote.png" class="downvote" />
{% endif %}

我计划通过在我的ManyToManyField模型中添加一个名为has_answered的{​​{1}}来完成此操作,但由于我收到此错误,我无法执行此操作:

Post

知道如何解决这个问题吗?我对错误信息不太确定,因为我认为我无法改变当前的post.Post.has_answered: (fields.E304) Reverse accessor for 'Post.has_answered' clashes with reverse accessor for 'Post.user'. HINT: Add or change a related_name argument to the definition for 'Post.has_answered' or 'Post.user'. post.Post.user: (fields.E304) Reverse accessor for 'Post.user' clashes with reverse accessor for 'Post.has_answered'. HINT: Add or change a related_name argument to the definition for 'Post.user' or 'Post.has_answered'. 字段。

2 个答案:

答案 0 :(得分:3)

您可以将模型更改为这样。您可能不需要PostScore模型。

class Post(models.Model):
    # Other Fields i.e title, content, author ...
    upvotes = models.ManyToMany(User)
    downvotes = models.ManyToMany(User)

你可以使用此功能在帖子上获得赞成。

upvotes = post_object.upvotes.count()
downvotes = post_object.downvotes.count()

要查看用户是否已投票,

if request.user in post_object.upvotes.all():
    # This user has upvoted this post

同样的downvotes。

您也可以在模板中执行类似的操作,并根据条件隐藏/显示按钮。

{% if request.user in post_object.upvotes.all %}
    <!-- show upvote button highlighted -->
{% elif request.user in post_object.downvotes.all %}
    <!-- show downvote button highlighted -->
{% else %}
    <!-- Show both buttons (not highlighted) -->
{% endif %}

希望这有帮助。

答案 1 :(得分:0)

您是否尝试过将django视图中的flag发送到以下模板:

def myView(request):

    parameters['is_user_voted'] = PostScore.objects.filter(user=self.request.user).exists()
    .....
    .....
    send ```parameters``` to your template using render()

将模板更改为:

{% if is_user_voted == 'True' %}
{% else %}
    <img src="upvote.png" class="upvote" />
    <img src="downvote.png" class="downvote" />
{% endif %}