I want to save the votes of an user of each post in order to prevent duplicate vote. The idea is to save the upvotes in 'liked_eintraege'. The user should only be able to vote on the result page, not index page. Hence I added it to the result view.
Currently if you upvote a post, the points go up but the problem ist that it keeps redirecting to this (upvoted) post, no matter on what post I click (however duplicate vote is not possible because it goes to the else clause and doesn't show the vote triangle).
views.py
def result(request, id):
eintrag = get_object_or_404(Eintrag, pk=id)
...
eintraege = Eintrag.objects.all().order_by('-id')
if request.user.is_authenticated():
#here in the next line is the problem:
liked_eintraege = request.user.liked_eintraege.filter(id__in=[eintrag.id for eintrag in eintraege])
else:
liked_eintraege=[]
context = {
'eintrag': eintrag,
'comments': comments,
'comment_form':form,
'liked_eintraege': liked_eintraege
}
return render(request, 'gaestebuch/result.html', context)
@login_required
def vote(request):
eintrag = get_object_or_404(Eintrag, pk=request.POST.get('eintrag'))
eintrag.points += 1
eintrag.save()
user = request.user
user.liked_eintraege.add(eintrag)
user.save()
return HttpResponse()
models.py:
class Eintrag(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=200)
points = models.IntegerField(default=1)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
voters = models.ManyToManyField(User, related_name='liked_eintraege')
and in result.html:
{% if user.is_authenticated and eintrag not in liked_eintraege %}
<a href="/vote/" id="eintrag-vote-{{ eintrag.id }}" class="vote">▲</a>
<p id="eintrag-title-{{ eintrag.id }}">{{ eintrag.title }}</p>
{% else %}
<p>{{ eintrag.title }}</p>
{% endif %}
the vote function works, thanks to a previous post I already did.
Aucun commentaire:
Enregistrer un commentaire