Package: django-voting
A generic voting application for Django projects, which allows
registering of votes for anyModelinstance.InstallationInstall thedjango-votingdistributionAddvotingto yourINSTALLED_APPS:INSTALLED_APPS = [
    …
    'voting',
    …
]Rundjango-adminmigrateUsageVotesVotes are represented by theVotemodel, which lives in thevoting.modelsmodule.Votes are recorded using therecord_votehelper function:>>> from django.contrib.auth.models import User
>>> from shop.apps.products.models import Widget
>>> from voting.models import Vote
>>> user = User.objects.get(pk=1)
>>> widget = Widget.objects.get(pk=1)
>>> Vote.objects.record_vote(widget, user, +1)The score for an object can be retrieved using theget_scorehelper function:>>> Vote.objects.get_score(widget)
{'score': 1, 'num_votes': 1}If the same user makes another vote on the same object, their vote
is either modified or deleted, as appropriate:>>> Vote.objects.record_vote(widget, user, -1)
>>> Vote.objects.get_score(widget)
{'score': -1, 'num_votes': 1}
>>> Vote.objects.record_vote(widget, user, 0)
>>> Vote.objects.get_score(widget)
{'score': 0, 'num_votes': 0}FieldsVoteobjects have the following fields:user– The user who made the vote. Users are represented by
thedjango.contrib.auth.models.Usermodel.content_type– The ContentType of the object voted on.object_id– The id of the object voted on.object– The object voted on.vote– The vote which was made:+1or-1.MethodsVoteobjects have the following custom methods:is_upvote– ReturnsTrueifvoteis+1.is_downvote– ReturnsTrueifvoteis-1.Manager functionsTheVotemodel has a custom manager that has the following helper
functions:record_vote(obj, user, vote)– Record a user’s vote on a
given object. Only allows a given user to vote once on any given
object, but the vote may be changed.votemust be one of1(up vote),-1(down vote) or0(remove vote).get_score(obj)– Gets the total score forobjand the
total number of votes it’s received.Returns a dictionary withscoreandnum_voteskeys.get_scores_in_bulk(objects)– Gets score and vote count
details for all the given objects. Score details consist of a
dictionary which hasscoreandnum_votekeys.Returns a dictionary mapping object ids to score details.get_top(Model, limit=10, reversed=False)– Gets the toplimitscored objects for a given model.IfreversedisTrue, the bottomlimitscored objects
are retrieved instead.Yields(object, score)tuples.get_bottom(Model, limit=10)– A convenience method which
callsget_topwithreversed=True.Gets the bottom (i.e. most negative)limitscored objects
for a given model.Yields(object, score)tuples.get_for_user(obj, user)– Gets the vote made on the given
object by the given user, orNoneif no matching vote
exists.get_for_user_in_bulk(objects, user)– Gets the votes
made on all the given objects by the given user.Returns a dictionary mapping object ids to votes.get_voted_users(object)– Gets all users
voted on the given object.Returns a list of objects contains user ids.Generic ViewsThevoting.viewsmodule contains views to handle a couple of
common cases: displaying a page to confirm a vote when it is requested
viaGETand making the vote itself viaPOST, or voting via
XMLHttpRequestPOST.The following sample URLconf demonstrates using a generic view for
voting on a model, allowing for regular voting and XMLHttpRequest
voting at the same URL:from django.urls import re_path
from voting.views import vote_on_object
from shop.apps.products.models import Widget

widget_kwargs = {
    'model': Widget,
    'template_object_name': 'widget',
    'allow_xmlhttprequest': True,
}

urlpatterns = [
    re_path(
        r"^widgets/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$",
        vote_on_object,
        kwargs=widget_kwargs,
    ),
]voting.views.vote_on_objectDescription:A view that displays a confirmation page and votes on an object. The
given object will only be voted on if the request method isPOST.
If this view is fetched viaGET, it will display a confirmation
page that should contain a form thatPOSTs to the same URL.Required arguments:model: The Django model class of the object that will be
voted on.Eitherobject_idor (slugandslug_field) is
required.If you provideobject_id, it should be the value of the
primary-key field for the object being voted on.Otherwise,slugshould be the slug of the given object, andslug_fieldshould be the name of the slug field in theQuerySet’s model.direction: The kind of vote to be made, must be one of'up','down'or'clear'.Either apost_vote_redirectargument defining a URL must
be supplied, or anextparameter must supply a URL in the
request when the vote isPOSTed, or the object being voted
on must define aget_absolute_urlmethod or property.The view checks for these in the order given above.Optional arguments:allow_xmlhttprequest: A boolean that designates whether this
view should also allow votes to be made via XMLHttpRequest.If this isTrue, the request headers will be check for anHTTP_X_REQUESTED_WITHheader which has a value ofXMLHttpRequest. If this header is found, processing of the
current request is delegated tovoting.views.xmlhttprequest_vote_on_object.template_name: The full name of a template to use in
rendering the page. This lets you override the default template
name (see below).template_loader: The template loader to use when loading the
template. By default, it’sdjango.template.loader.extra_context: A dictionary of values to add to the template
context. By default, this is an empty dictionary. If a value in
the dictionary is callable, the generic view will call it just
before rendering the template.context_processors: A list of template-context processors to
apply to the view’s template.template_object_name:  Designates the name of the template
variable to use in the template context. By default, this is'object'.Template name:Iftemplate_nameisn’t specified, this view will use the template<app_label>/<model_name>_confirm_vote.htmlby default.Template context:In addition toextra_context, the template’s context will be:object: The original object that’s about to be voted on.
This variable’s name depends on thetemplate_object_nameparameter, which is'object'by default. Iftemplate_object_nameis'foo', this variable’s name will
befoo.direction: The argument which was given for the vote’sdirection(see above).voting.views.xmlhttprequest_vote_on_objectDescription:A view for use in voting on objects via XMLHttpRequest. The given
object will only be voted on if the request method isPOST. This
view will respond with JSON text instead of rendering a template or
redirecting.Required arguments:model: The Django model class of the object that will be
voted on.Eitherobject_idor (slugandslug_field) is
required.If you provideobject_id, it should be the value of the
primary-key field for the object being voted on.Otherwise,slugshould be the slug of the given object, andslug_fieldshould be the name of the slug field in theQuerySet’s model.direction: The kind of vote to be made, must be one of'up','down'or'clear'.JSON text context:The context provided by the JSON text returned will be:success:trueif the vote was successfully processed,falseotherwise.score: an object containing ascoreproperty, which
holds the object’s updated score, and anum_votesproperty,
which holds the total number of votes cast for the object.error_message: if the vote was not successfully processed,
this property will contain an error message.Template tagsThevoting.templatetags.voting_tagsmodule defines a number of
template tags which may be used to retrieve and display voting
details.Tag referencescore_for_objectRetrieves the total score for an object and the number of votes
it’s received, storing them in a context variable which hasscoreandnum_votesproperties.Example usage:{% score_for_object widget as score %}

{{ score.score }} point{{ score.score|pluralize }}
after {{ score.num_votes }} vote{{ score.num_votes|pluralize }}scores_for_objectsRetrieves the total scores and number of votes cast for a list of
objects as a dictionary keyed with the objects’ ids and stores it in a
context variable.Example usage:{% scores_for_objects widget_list as scores %}vote_by_userRetrieves theVotecast by a user on a particular object and
stores it in a context variable. If the user has not voted, the
context variable will beNone.Example usage:{% vote_by_user user on widget as vote %}votes_by_userRetrieves the votes cast by a user on a list of objects as a
dictionary keyed with object ids and stores it in a context
variable.Example usage:{% votes_by_user user on widget_list as vote_dict %}dict_entry_for_itemGiven an object and a dictionary keyed with object ids - as returned
by thevotes_by_userandscores_for_objectstemplate tags -
retrieves the value for the given object and stores it in a context
variable, storingNoneif no value exists for the given object.Example usage:{% dict_entry_for_item widget from vote_dict as vote %}confirm_vote_messageIntended for use in vote confirmatio templates, creates an appropriate
message asking the user to confirm the given vote for the given object
description.Example usage:{% confirm_vote_message widget.title direction %}Filter referencevote_displayGiven a string mapping values for up and down votes, returns one
of the strings according to the givenVote:Vote typeArgumentOutputs+1'Bodacious,Bogus'Bodacious-1'Bodacious,Bogus'BogusIf no string mapping is given,'Up'and'Down'will be used.Example usage:{{ vote|vote_display:"Bodacious,Bogus" }}