Reputation:
Im trying to simply accomplish that a vote on a post gets count +1 if a user hits the like button on my site but for some reasone it counts not +1, instead it counts +2 if i hit the URL of that post:
views.py
def post_up_vote (request, pk):
post = get_object_or_404(Post, pk=pk)
try:
if request.method == 'GET':
if post.author == request.user:
messages.error(request, 'You are trying to vote on a Post you created by your own. Thats not possible.')
return redirect('post_detail', pk=post.pk)
if Post_Vote.objects.filter(voter=request.user, voted=post).exists():
messages.error(request, 'You already Voted this Post. Double votes are not allowed.')
return redirect('post_detail', pk=post.pk)
else:
post.up_vote = F('up_vote') + 1
post.save()
Post_Vote.objects.create(voter=request.user, voted=post)
messages.success(request, 'You have successfully Provided an Up-Vote for this Post.')
return redirect('post_detail', pk=post.pk)
else:
messages.error(request, 'Something went wrong, please try again.')
return redirect('post_detail', pk=post.pk)
except:
messages.error(request, 'Something went wrong, please try again.')
return redirect('post_detail', pk=post.pk)
models.py
class Post(models.Model):
...
up_vote = models.IntegerField(default=0)
down_vote = models.IntegerField(default=0)
...
class Post_Vote(models.Model):
voter = models.ForeignKey(User, on_delete=models.CASCADE)
voted = models.ForeignKey(Post, on_delete=models.CASCADE)
published_date = models.DateField(auto_now_add=True, null=True)
class Meta:
unique_together = ('voter', 'voted')
def publish(self):
self.published_date = timezone.now()
self.save()
urls.py
url(r'^post/(?P<pk>\d+)/up-vote/$', app.post_up_vote, name='post_up_vote'),
template.html
<a href="{% url 'post_up_vote' pk=post.pk %}"> <i class="btn success fa fa-thumbs-up"></i></a>
if i create a new post on my site and vote on this post with a diffrent user then the original post author, then the voting counts +2 and not +1 and im not able to see any reason for that.
Upvotes: 0
Views: 161
Reputation: 1623
F() objects assigned to model fields persist after saving the model instance and will be applied on each save().
post.up_vote = F('up_vote') + 1
post.save()
post.refresh_from_db()
Upvotes: 1