django-vote
is a simple Django app to conduct vote for django model.
This project was inspired by django-taggit
pip install django-vote
INSTALLED_APPS = (
...
'vote',
)
from vote.models import VoteModel
class ArticleReview(VoteModel, models.Model):
...
manage.py makemigrations
manage.py migrate
review = ArticleReview.objects.get(pk=1)
# Up vote to the object
review.votes.up(user_id)
# Down vote to the object
review.votes.down(user_id)
# Removes a vote from the object
review.votes.delete(user_id)
# Check if the user already voted (up) the object
review.votes.exists(user_id)
# Check if the user already voted (down) the object
# import UP, DOWN from vote.models
review.votes.exists(user_id, action=DOWN)
# Returns the number of votes for the object
review.votes.count()
# Returns the number of down votes for the object
review.votes.count(action=DOWN)
# Returns a list of users who voted and their voting date
review.votes.user_ids()
# Returns all instances voted by user
Review.votes.all(user_id)
There are two template tags you can use in template:
vote_count
to get vote count for a model instancevote_exists
to check whether current user vote for the instance
{% load vote %}
<ol>
{% for comment in comments %}
<li>
{{comment.content}} - up:{% vote_count comment "up" %} - down: {% vote_count comment "down" %} - exists_up:
{% vote_exists comment user "up" %} - exists_down: {% vote_exists comment user "down"%}
</li>
{% endfor %}
</ol>
Install django-rest-framework
from rest_framework.viewsets import ModelViewSet
from vote.views import VoteMixin
class CommentViewSet(ModelViewSet, VoteMixin):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
POST /api/comments/{id}/vote/
POST /api/comments/{id}/vote/ {"action":"down"}
DELETE /api/comments/{id}/vote/