Browse files

Cosmetic changes.

  • Loading branch information...
1 parent 35d91ea commit 8205625ba99a331554ce431c7694c2dfc7d36417 @jezdez jezdez committed Jul 26, 2012
Showing with 53 additions and 36 deletions.
  1. +1 −1 docs/overview.txt
  2. +15 −17 voting/managers.py
  3. +12 −7 voting/models.py
  4. +14 −2 voting/templatetags/voting_tags.py
  5. +3 −4 voting/urls.py
  6. +8 −5 voting/views.py
View
2 docs/overview.txt
@@ -395,4 +395,4 @@ If no string mapping is given, ``'Up'`` and ``'Down'`` will be used.
Example usage::
- {{ vote|vote_display:"Bodacious,Bogus" }}
+ {{ vote|vote_display:"Bodacious,Bogus" }}
View
32 voting/managers.py
@@ -13,24 +13,22 @@
if supports_aggregates:
class CoalesceWrapper(Aggregate):
sql_template = 'COALESCE(%(function)s(%(field)s), %(default)s)'
-
- def __init__(self, lookup, **extra):
+
+ def __init__(self, lookup, **extra):
self.lookup = lookup
self.extra = extra
-
+
def _default_alias(self):
return '%s__%s' % (self.lookup, self.__class__.__name__.lower())
default_alias = property(_default_alias)
-
+
def add_to_query(self, query, alias, col, source, is_summary):
super(CoalesceWrapper, self).__init__(col, source, is_summary, **self.extra)
query.aggregate_select[alias] = self
-
class CoalesceSum(CoalesceWrapper):
sql_function = 'SUM'
-
class CoalesceCount(CoalesceWrapper):
sql_function = 'COUNT'
@@ -62,38 +60,38 @@ def get_scores_in_bulk(self, objects):
object_ids = [o._get_pk_val() for o in objects]
if not object_ids:
return {}
-
+
ctype = ContentType.objects.get_for_model(objects[0])
-
+
if supports_aggregates:
queryset = self.filter(
- object_id__in = object_ids,
- content_type = ctype,
+ object_id__in=object_ids,
+ content_type=ctype,
).values(
'object_id',
).annotate(
- score = CoalesceSum('vote', default='0'),
- num_votes = CoalesceCount('vote', default='0'),
+ score=CoalesceSum('vote', default='0'),
+ num_votes=CoalesceCount('vote', default='0'),
)
else:
queryset = self.filter(
- object_id__in = object_ids,
- content_type = ctype,
+ object_id__in=object_ids,
+ content_type=ctype,
).extra(
- select = {
+ select={
'score': 'COALESCE(SUM(vote), 0)',
'num_votes': 'COALESCE(COUNT(vote), 0)',
}
).values('object_id', 'score', 'num_votes')
queryset.query.group_by.append('object_id')
-
+
vote_dict = {}
for row in queryset:
vote_dict[row['object_id']] = {
'score': int(row['score']),
'num_votes': int(row['num_votes']),
}
-
+
return vote_dict
def record_vote(self, obj, user, vote):
View
19 voting/models.py
@@ -1,28 +1,33 @@
+from datetime import datetime
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.db import models
-from django.utils.timezone import now, utc
+
+try:
+ from django.utils.timezone import now
+except ImportError:
+ now = datetime.now
from voting.managers import VoteManager
-from datetime import datetime
SCORES = (
(+1, u'+1'),
(-1, u'-1'),
)
+
class Vote(models.Model):
"""
A vote on an object by a User.
"""
- user = models.ForeignKey(User)
+ user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
- object = generic.GenericForeignKey('content_type', 'object_id')
- vote = models.SmallIntegerField(choices=SCORES)
- time_stamp = models.DateTimeField(editable = False , default=now )
+ object_id = models.PositiveIntegerField()
+ object = generic.GenericForeignKey('content_type', 'object_id')
+ vote = models.SmallIntegerField(choices=SCORES)
+ time_stamp = models.DateTimeField(editable=False, default=now)
objects = VoteManager()
View
16 voting/templatetags/voting_tags.py
@@ -7,6 +7,7 @@
# Tags
+
class ScoreForObjectNode(template.Node):
def __init__(self, object, context_var):
self.object = object
@@ -20,6 +21,7 @@ def render(self, context):
context[self.context_var] = Vote.objects.get_score(object)
return ''
+
class ScoresForObjectsNode(template.Node):
def __init__(self, objects, context_var):
self.objects = objects
@@ -33,6 +35,7 @@ def render(self, context):
context[self.context_var] = Vote.objects.get_scores_in_bulk(objects)
return ''
+
class VoteByUserNode(template.Node):
def __init__(self, user, object, context_var):
self.user = user
@@ -48,6 +51,7 @@ def render(self, context):
context[self.context_var] = Vote.objects.get_for_user(object, user)
return ''
+
class VotesByUserNode(template.Node):
def __init__(self, user, objects, context_var):
self.user = user
@@ -63,6 +67,7 @@ def render(self, context):
context[self.context_var] = Vote.objects.get_for_user_in_bulk(objects, user)
return ''
+
class DictEntryForItemNode(template.Node):
def __init__(self, item, dictionary, context_var):
self.item = item
@@ -78,6 +83,7 @@ def render(self, context):
context[self.context_var] = dictionary.get(item.id, None)
return ''
+
def do_score_for_object(parser, token):
"""
Retrieves the total score for an object and the number of votes
@@ -98,6 +104,7 @@ def do_score_for_object(parser, token):
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return ScoreForObjectNode(bits[1], bits[3])
+
def do_scores_for_objects(parser, token):
"""
Retrieves the total scores for a list of objects and the number of
@@ -114,6 +121,7 @@ def do_scores_for_objects(parser, token):
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return ScoresForObjectsNode(bits[1], bits[3])
+
def do_vote_by_user(parser, token):
"""
Retrieves the ``Vote`` cast by a user on a particular object and
@@ -133,6 +141,7 @@ def do_vote_by_user(parser, token):
raise template.TemplateSyntaxError("fourth argument to '%s' tag must be 'as'" % bits[0])
return VoteByUserNode(bits[1], bits[3], bits[5])
+
def do_votes_by_user(parser, token):
"""
Retrieves the votes cast by a user on a list of objects as a
@@ -152,6 +161,7 @@ def do_votes_by_user(parser, token):
raise template.TemplateSyntaxError("fourth argument to '%s' tag must be 'as'" % bits[0])
return VotesByUserNode(bits[1], bits[3], bits[5])
+
def do_dict_entry_for_item(parser, token):
"""
Given an object and a dictionary keyed with object ids - as
@@ -179,6 +189,7 @@ def do_dict_entry_for_item(parser, token):
register.tag('votes_by_user', do_votes_by_user)
register.tag('dict_entry_for_item', do_dict_entry_for_item)
+
# Simple Tags
def confirm_vote_message(object_description, vote_direction):
@@ -200,6 +211,7 @@ def confirm_vote_message(object_description, vote_direction):
# Filters
+
def vote_display(vote, arg=None):
"""
Given a string mapping values for up and down votes, returns one
@@ -222,10 +234,10 @@ def vote_display(vote, arg=None):
arg = 'Up,Down'
bits = arg.split(',')
if len(bits) != 2:
- return vote.vote # Invalid arg
+ return vote.vote # Invalid arg
up, down = bits
if vote.vote == 1:
return up
return down
-register.filter(vote_display)
+register.filter(vote_display)
View
7 voting/urls.py
@@ -3,11 +3,10 @@
urlpatterns = patterns('',
url(r"^vote/(?P<app_label>[\w\.-]+)/(?P<model_name>\w+)/"\
- "(?P<object_id>\d+)/(?P<direction>up|down|clear)/$",
- "voting.views.vote_on_object_with_lazy_model", {
- "allow_xmlhttprequest": True,
+ "(?P<object_id>\d+)/(?P<direction>up|down|clear)/$",
+ "voting.views.vote_on_object_with_lazy_model", {
+ "allow_xmlhttprequest": True,
},
name="voting_vote"
),
)
-
View
13 voting/views.py
@@ -10,6 +10,7 @@
VOTE_DIRECTIONS = (('up', 1), ('down', -1), ('clear', 0))
+
def vote_on_object(request, model, direction, post_vote_redirect=None,
object_id=None, slug=None, slug_field=None, template_name=None,
template_loader=loader, extra_context=None, context_processors=None,
@@ -40,14 +41,15 @@ def vote_on_object(request, model, direction, post_vote_redirect=None,
object_id=object_id, slug=slug,
slug_field=slug_field)
- if extra_context is None: extra_context = {}
+ if extra_context is None:
+ extra_context = {}
if not request.user.is_authenticated():
return redirect_to_login(request.path)
try:
vote = dict(VOTE_DIRECTIONS)[direction]
except KeyError:
- raise AttributeError("'%s' is not a valid vote type." % vote_type)
+ raise AttributeError("'%s' is not a valid vote type." % direction)
# Look up the object to be voted on
lookup_kwargs = {}
@@ -61,12 +63,13 @@ def vote_on_object(request, model, direction, post_vote_redirect=None,
try:
obj = model._default_manager.get(**lookup_kwargs)
except ObjectDoesNotExist:
- raise Http404, 'No %s found for %s.' % (model._meta.app_label, lookup_kwargs)
+ raise Http404('No %s found for %s.' %
+ (model._meta.app_label, lookup_kwargs))
if request.method == 'POST':
if post_vote_redirect is not None:
next = post_vote_redirect
- elif request.REQUEST.has_key('next'):
+ elif 'next' in request.REQUEST:
next = request.REQUEST['next']
elif hasattr(obj, 'get_absolute_url'):
if callable(getattr(obj, 'get_absolute_url')):
@@ -120,7 +123,7 @@ def json_error_response(error_message):
def xmlhttprequest_vote_on_object(request, model, direction,
- object_id=None, slug=None, slug_field=None):
+ object_id=None, slug=None, slug_field=None):
"""
Generic object vote function for use via XMLHttpRequest.

0 comments on commit 8205625

Please sign in to comment.