Django:只允许用户发一次帖子

时间:2019-05-19 17:09:55

标签: python jquery django python-3.x django-models

仅在Django上编写了一个函数,该函数只允许用户为每个帖子(错误)投票一次。 如您所见,通过单击链接即可完成操作。只是想知道在用户投票一次之后是否可以隐藏“投票”按钮? 这是代码,希望对您有所帮助:

views.py:

def vote(request, bug_id):
bug = get_object_or_404(BugTable, pk=bug_id)
if request.user.is_authenticated:
    bug.vote += 1
    try:
        Vote.objects.create(bug=bug, user=request.user)
        bug.save()
    except IntegrityError:
        messages.success(request, 'You already voted for this bug')
        return redirect(bugfix)
return render(request, 'detail.html', {'bug': bug})

models.py

class BugTable(models.Model):


author = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
bug_name = models.CharField(max_length=50, blank=False)
vote = models.IntegerField(default=0)

def __str__(self):
    return self.bug_name


class Vote(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   bug = models.ForeignKey(BugTable, on_delete=models.CASCADE, 
   related_name='voter')

class Meta:
    unique_together = ('user', 'bug')

detail.html

{% block features %}
  <h5 style="margin-top: 10px;"><strong>{{ bug.bug_name }}</strong></h5>
  <a href="{% url 'vote' bug.id %}">Vote</a>
  {{ bug.vote}}
{% endblock %}

使用.hide方法尝试使用jQuery简单功能,但无效。也许我可以通过输入{%if%}函数来使用某些东西?感谢您的任何建议

1 个答案:

答案 0 :(得分:0)

有多种方法,最简单的方法是计算当前用户是否在视图中投票,并在模板中提供该投票:

views.py:

def vote(request, bug_id):
    bug = get_object_or_404(BugTable, pk=bug_id)
    current_user_voted = bug.voter.filter(user=request.user).exists()
    if request.user.is_authenticated:
        bug.vote += 1
        try:
            Vote.objects.create(bug=bug, user=request.user)
            bug.save()
        except IntegrityError:
            messages.success(request, 'You already voted for this bug')
            return redirect(bugfix)
    return render(request, 'detail.html', {'bug': bug, 'current_user_voted': current_user_voted})

details.html:

{% block features %}
    <h5 style="margin-top: 10px;"><strong>{{ bug.bug_name }}</strong></h5>
    {% if not current_user_voted %}
        <a href="{% url 'vote' bug.id %}">Vote</a>
    {% endif %}
    {{ bug.vote }}
{% endblock %}