Commits

Ryan Witt committed ee71db4

Added a number_awarded helper method and made badge choices changable from settings.py

  • Participants
  • Parent commits 13f4a17

Comments (0)

Files changed (3)

 from django.contrib.auth.models import User
 from django.core.urlresolvers import reverse
 from django.db import models
+from django.conf import settings
 
 from badges.signals import badge_awarded
 from badges.managers import BadgeManager
 
-LEVEL_CHOICES = (
+if hasattr(settings, 'BADGE_LEVEL_CHOICES'):
+    LEVEL_CHOICES = settings.BADGE_LEVEL_CHOICES
+else:
+    LEVEL_CHOICES = (
         ("1", "Bronze"),
         ("2", "Silver"),
         ("3", "Gold"),
         ("4", "Diamond"),
-        )
+    )
 
 class Badge(models.Model):
     id = models.CharField(max_length=255, primary_key=True)
         
         return BadgeToUser.objects.filter(badge=self, user=user).count()
 
+    def number_awarded(self, user_or_qs=None):
+        """
+        Gives the number awarded total. Pass in an argument to
+        get the number per user, or per queryset.
+        """
+        kwargs = {'badge':self}
+        if user_or_qs is None:
+            pass
+        elif isinstance(user_or_qs, User):
+            kwargs.update(dict(user=user_or_qs))
+        else:
+            kwargs.update(dict(user__in=user_or_qs))
+        return BadgeToUser.objects.filter(**kwargs).count()
+
+
 class BadgeToUser(models.Model):
     badge = models.ForeignKey(Badge)
     user = models.ForeignKey(User)

badges/templatetags/badges_tags.py

 
 @register.filter
 def is_in(value,arg):
-   return value in arg
+    return value in arg
 
 @register.filter
 def level_count(badges, level):
-   return badges.filter(level=level).count()
+    return badges.filter(level=level).count()
 
 @register.filter
 def level_title(level):
-   return level_choices[level]
+    return level_choices[level]
 
 @register.filter('badge_count')
 def _badge_count(user_or_qs):
-   return badge_count(user_or_qs)
+    return badge_count(user_or_qs)
 
+@register.filter
+def number_awarded(badge, user_or_qs=None):
+    return badge.number_awarded(user_or_qs)
         registered_badges[badge.id] = badge()
     return badge
 
-def badge_count(user_or_qs):
+def badge_count(user_or_qs=None):
     """
     Given a user or queryset of users, this returns the badge
     count at each badge level that the user(s) have earned.
 
     Uses a single database query.
     """
-    if isinstance(user_or_qs, User):
-        kwargs = dict(user=user_or_qs)
+    kwargs = {}
+    if user_or_qs is None:
+        pass
+    elif isinstance(user_or_qs, User):
+        kwargs.update(dict(user=user_or_qs))
     else:
-        kwargs = dict(user__in=user_or_qs)
+        kwargs.update(dict(user__in=user_or_qs))
 
     return BadgeToUser.objects.filter(
         **kwargs