Skip to content

Commit

Permalink
0.1.dev8 - Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
paltman committed Oct 19, 2011
0 parents commit 75fd9ed
Show file tree
Hide file tree
Showing 28 changed files with 946 additions and 0 deletions.
27 changes: 27 additions & 0 deletions LICENSE
@@ -0,0 +1,27 @@
Copyright (c) 2011, Eldarion, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of Eldarion, Inc. nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2 changes: 2 additions & 0 deletions MANIFEST.in
@@ -0,0 +1,2 @@
include README.rst
recursive-include agon_ratings/templates *.html
11 changes: 11 additions & 0 deletions README.rst
@@ -0,0 +1,11 @@
agon-ratings
============

Provides user ratings of objects.


Documentation
-------------

Documentation can be found online at http://agon-ratings.readthedocs.org/.

1 change: 1 addition & 0 deletions agon_ratings/__init__.py
@@ -0,0 +1 @@
__version__ = "0.1.dev8"
16 changes: 16 additions & 0 deletions agon_ratings/managers.py
@@ -0,0 +1,16 @@
from django.db import models

from django.contrib.contenttypes.models import ContentType


class OverallRatingManager(models.Manager):

def top_rated(self, klass):

return self.filter(
content_type=ContentType.objects.get_for_model(klass)
).extra(
select={
"sortable_rating": "COALESCE(rating, 0)"
}
).order_by("-sortable_rating")
51 changes: 51 additions & 0 deletions agon_ratings/models.py
@@ -0,0 +1,51 @@
import datetime

from decimal import Decimal

from django.db import models

from django.contrib.auth.models import User
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

from agon_ratings.managers import OverallRatingManager


class OverallRating(models.Model):

object_id = models.IntegerField(db_index=True)
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey()
rating = models.DecimalField(decimal_places=1, max_digits=3, null=True)

objects = OverallRatingManager()

class Meta:
unique_together = [
("object_id", "content_type"),
]

def update(self):
self.rating = Rating.objects.filter(
overall_rating = self
).aggregate(r = models.Avg("rating"))["r"]
self.rating = Decimal(str(self.rating or "0"))
self.save()


class Rating(models.Model):
overall_rating = models.ForeignKey(OverallRating, null = True, related_name = "ratings")
object_id = models.IntegerField(db_index=True)
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey()
user = models.ForeignKey(User)
rating = models.IntegerField()
timestamp = models.DateTimeField(default=datetime.datetime.now)

class Meta:
unique_together = [
("object_id", "content_type", "user"),
]

def __unicode__(self):
return unicode(self.rating)
4 changes: 4 additions & 0 deletions agon_ratings/templates/agon_ratings/_rate_form.html
@@ -0,0 +1,4 @@
<form action="{% url agon_ratings_rate content_type_id=ct.id object_id=obj.pk %}" method="POST">
{% csrf_token %}
<input type="hidden" name="rating" id="id_rating" />
</form>
Empty file.
96 changes: 96 additions & 0 deletions agon_ratings/templatetags/agon_ratings_tags.py
@@ -0,0 +1,96 @@
from django import template

from django.contrib.contenttypes.models import ContentType

from agon_ratings.models import Rating, OverallRating


register = template.Library()


class UserRatingNode(template.Node):

@classmethod
def handle_token(cls, parser, token):
bits = token.split_contents()
if len(bits) != 7:
raise template.TemplateSyntaxError()
return cls(
user = parser.compile_filter(bits[2]),
obj = parser.compile_filter(bits[4]),
as_var = bits[6]
)

def __init__(self, user, obj, as_var):
self.user = user
self.obj = obj
self.as_var = as_var

def render(self, context):
user = self.user.resolve(context)
obj = self.obj.resolve(context)
try:
ct = ContentType.objects.get_for_model(obj)
rating = Rating.objects.get(
object_id = obj.pk,
content_type = ct,
user = user
).rating
except Rating.DoesNotExist:
rating = 0
context[self.as_var] = rating
return ""


@register.tag
def user_rating(parser, token):
"""
Usage:
{% user_rating for user and obj as var %}
"""
return UserRatingNode.handle_token(parser, token)


class OverallRatingNode(template.Node):

@classmethod
def handle_token(cls, parser, token):
bits = token.split_contents()
if len(bits) != 5:
raise template.TemplateSyntaxError()
return cls(
obj = parser.compile_filter(bits[2]),
as_var = bits[4]
)

def __init__(self, obj, as_var):
self.obj = obj
self.as_var = as_var

def render(self, context):
obj = self.obj.resolve(context)
try:
ct = ContentType.objects.get_for_model(obj)
rating = OverallRating.objects.get(
object_id=obj.pk,
content_type=ct
).rating or 0
except OverallRating.DoesNotExist:
rating = 0
context[self.as_var] = rating
return ""


@register.tag
def overall_rating(parser, token):
"""
Usage:
{% overall_rating for obj as var %}
"""
return OverallRatingNode.handle_token(parser, token)


@register.inclusion_tag("agon_ratings/_rate_form.html")
def user_rate_form(obj):
ct = ContentType.objects.get_for_model(obj)
return {"ct": ct, "obj": obj}
6 changes: 6 additions & 0 deletions agon_ratings/urls.py
@@ -0,0 +1,6 @@
from django.conf.urls.defaults import *


urlpatterns = patterns("agon_ratings.views",
url(r"^(?P<content_type_id>\d+)/(?P<object_id>\d+)/rate/$", "rate", name="agon_ratings_rate"),
)
66 changes: 66 additions & 0 deletions agon_ratings/views.py
@@ -0,0 +1,66 @@
from django.conf import settings
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.utils import simplejson as json
from django.views.decorators.http import require_POST

from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType

from agon_ratings.models import Rating, OverallRating


NUM_OF_RATINGS = getattr(settings, "AGON_NUM_OF_RATINGS", 5)


@require_POST
@login_required
def rate(request, content_type_id, object_id):
ct = get_object_or_404(ContentType, pk=content_type_id)
obj = get_object_or_404(ct.model_class(), pk=object_id)
rating_input = int(request.POST.get("rating"))

data = {
"user_rating": rating_input,
"overall_rating": 0
}

# @@@ Seems like this could be much more DRY with a model method or something
if rating_input == 0: # clear the rating
try:
rating = Rating.objects.get(
object_id = object_id,
content_type = ct,
user = request.user
)
overall = rating.overall_rating
rating.delete()
overall.update()
data["overall_rating"] = str(overall.rating)
except Rating.DoesNotExist:
pass
elif 1 <= rating_input <= NUM_OF_RATINGS: # set the rating
print rating_input
rating, created = Rating.objects.get_or_create(
object_id = obj.pk,
content_type = ct,
user = request.user,
defaults = {
"rating": rating_input
}
)
overall, created = OverallRating.objects.get_or_create(
object_id = obj.pk,
content_type = ct
)
rating.overall_rating = overall
rating.rating = rating_input
rating.save()
overall.update()
data["overall_rating"] = str(overall.rating)
else: # whoops
return HttpResponseForbidden(
"Invalid rating. It must be a value between 0 and %s" % NUM_OF_RATINGS
)

return HttpResponse(json.dumps(data), mimetype="application/json")
1 change: 1 addition & 0 deletions build/lib/agon_ratings/__init__.py
@@ -0,0 +1 @@
__version__ = "0.1.dev1"
16 changes: 16 additions & 0 deletions build/lib/agon_ratings/managers.py
@@ -0,0 +1,16 @@
from django.db import models

from django.contrib.contenttypes.models import ContentType


class OverallRatingManager(models.Manager):

def top_rated(self, klass):

return self.filter(
content_type=ContentType.objects.get_for_model(klass)
).extra(
select={
"sortable_rating": "COALESCE(rating, 0)"
}
).order_by("-sortable_rating")
48 changes: 48 additions & 0 deletions build/lib/agon_ratings/models.py
@@ -0,0 +1,48 @@
import datetime

from decimal import Decimal

from django.db import models

from django.contrib.auth.models import User
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

from agon_ratings.managers import OverallRatingManager


class OverallRating(models.Model):

object_id = models.IntegerField(db_index=True)
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey()
rating = models.DecimalField(decimal_places=1, max_digits=3, null=True)

objects = OverallRatingManager()

class Meta:
unique_together = [
("object_id", "content_type"),
]

def update(self):
self.rating = Rating.objects.filter(
overall_rating = self
).aggregate(r = models.Avg("rating"))["r"]
self.rating = Decimal(str(self.rating or "0"))
self.save()


class Rating(models.Model):
overall_rating = models.ForeignKey(OverallRating, null = True, related_name = "ratings")
object_id = models.IntegerField(db_index=True)
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey()
user = models.ForeignKey(User)
rating = models.IntegerField()
timestamp = models.DateTimeField(default=datetime.datetime.now)

class Meta:
unique_together = [
("object_id", "content_type", "user"),
]
4 changes: 4 additions & 0 deletions build/lib/agon_ratings/templates/_rate_form.html
@@ -0,0 +1,4 @@
<form action="{% url agon_ratings_rate content_type_id=ct.id object_id=obj.pk %}" method="POST">
{% csrf_token %
<input type="hidden" name="rating" id="id_rating" />
</form>
Empty file.

0 comments on commit 75fd9ed

Please sign in to comment.