简体   繁体   中英

Django: allowing user to like post only once

Just wrote a function on Django that allows users to vote only once per post(bug). As you will see that it's been done by pressing the link. Just would like to know if it's possible to hide the Vote button after user voted once? Here is the code, hope it helps:

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 %}

Tried with jQuery simple function using .hide method, did not work. May be there is something i could use just by entering {% if %} function? Thanks for any advice

There are multiple ways of doing it, simplest would be to calculate if current user is voted in view and provide that in template:

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM