Thanks a lot for sharing... This really helped.
omat
On 16 Mayıs, 18:38, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> OK. My app is called "karma". The model looks like this:
>
> from django.db import models
> from django.http import Http404, HttpResponse
> from django.contrib.contenttypes.models import ContentType
> from django.contrib.auth.models import User
> import datetime
>
> class KarmaScoreManager(models.Manager):
> def vote(self, user_id, content_type, object_id, rating):
> try:
> karma =
> self.get(content_type__pk=content_type,object_id=object_id,user__pk=user_id)
> except self.model.DoesNotExist:
> karma = self.model(None, user_id=user_id,
> content_type_id=content_type, object_id=object_id, score=rating,
> scored_date=datetime.datetime.now())
> karma.save()
> else:
> karma.score = rating
> karma.scored_date = datetime.datetime.now()
> karma.save()
>
> def get_pretty_score(self, score):
> """
> Given a score between -1 and 1 (inclusive), returns the same
> score on a
> scale between 1 and 10 (inclusive), as an integer.
> """
> if score is None:
> return DEFAULT_KARMA
> return int(round((4.5 * score) + 5.5))
>
> class KarmaScore(models.Model):
> user = models.ForeignKey(User, related_name="karma_user",)
> content_type = models.ForeignKey(ContentType)
> content_object = models.GenericForeignKey()
> object_id = models.IntegerField(_('object ID'))
> score = models.SmallIntegerField(_('score'), db_index=True)
> scored_date = models.DateTimeField(_('score date'), auto_now=True)
> objects = KarmaScoreManager()
> class Meta:
> verbose_name = _('karma score')
> verbose_name_plural = _('karma scores')
>
> class Admin:
> list_display = ('user', 'content_type',
> 'object_id','scored_date')
>
> def __repr__(self):
> return _("%(score)d rating by %(user)s") % {'score':
> self.score, 'user': self.user}
>
> And The view is:
>
> from django.http import Http404, HttpResponse
> from django.shortcuts import render_to_response
> from django.template import RequestContext
> from django.contrib.contenttypes.models import ContentType
> from gretschpages.karma.models import KarmaScore
>
> def vote(request, content_type, obj_id, vote, js=""):
> ctype = ContentType.objects.get(model=content_type)
> thisObject = ctype.get_object_for_this_type(pk=obj_id)
> rating = {'up': 1, 'down': -1}.get(vote, False)
>
> if not rating:
> raise Http404, "Invalid vote"
> if not request.user.is_authenticated():
> return HttpResponse("Anonymous users cannot vote",
> mimetype="text/html")
> try:
> obj = KarmaScore.objects.filter(content_type=ctype.id,
> object_id=obj_id)
>
> except:
> raise Http404, _("Invalid comment ID")
>
> if thisObject.id == request.user.id:
> return HttpResponse("No voting for yourself", mimetype="text/
> html")
>
> KarmaScore.objects.vote(request.user.id, ctype.id, obj_id, rating)
>
> if js == "js":
> return HttpResponse(str(thisObject.get_karma_total()),
> mimetype="text/html")
> else:
> return render_to_response('comments/karma_vote_accepted.html',
> {'obj': obj}, context_instance=RequestContext(request))
>
> Then, in the model of the thing you want karma for, you need these
> helper functions:
>
> def _fill_karma_cache(self):
> "Helper function that populates good/bad karma caches"
> good, bad = 0, 0
> from django.contrib.contenttypes.models import ContentType
> from gretschpages.karma.models import KarmaScore
> ctype = ContentType.objects.get(model='post')
>
> #for k in self.karmascore_set:
> for k in KarmaScore.objects.filter(content_type=ctype.id,
> object_id=self.id):
> if k.score == -1:
> bad +=1
> elif k.score == 1:
> good +=1
> self._karma_total_good, self._karma_total_bad = good, bad
>
> def get_good_karma_total(self):
> if not hasattr(self, "_karma_total_good"):
> self._fill_karma_cache()
> return self._karma_total_good
>
> def get_bad_karma_total(self):
> if not hasattr(self, "_karma_total_bad"):
> self._fill_karma_cache()
> return self._karma_total_bad
>
> def get_karma_total(self):
> if not hasattr(self, "_karma_total_good") or not
> hasattr(self, "_karma_total_bad"):
> self._fill_karma_cache()
> karma = self._karma_total_good - self._karma_total_bad
> if karma < 0:
> if karma < -3:
> elif k.score == 1:
> good +=1
> self._karma_total_good, self._karma_total_bad = good, bad
>
> def get_good_karma_total(self):
> if not hasattr(self, "_karma_total_good"):
> self._fill_karma_cache()
> return self._karma_total_good
>
> def get_bad_karma_total(self):
> if not hasattr(self, "_karma_total_bad"):
> self._fill_karma_cache()
> return self._karma_total_bad
>
> def get_karma_total(self):
> if not hasattr(self, "_karma_total_good") or not
> hasattr(self, "_karma_total_bad"):
> self._fill_karma_cache()
> karma = self._karma_total_good - self._karma_total_bad
> if karma < 0:
> if karma < -3:
> return 'collapsed'
> return 0
> return karma
>
> def __str__(self):
> return str(self.id)
>
> I'm sure you could abstract out those helpers so they didn't have to
> be in the other model, but I never bothered. Also, you'll see some
> extra code in there you may not need that I use for various other
> thing (like ajax voting, and collapsing things if they're voted down
> too much).
>
> On May 16, 9:04 am, omat <[EMAIL PROTECTED]> wrote:
>
> > I am trying to avoid coupling with the model of the content so I am
> > trying it with ContentTypes. Though, yours can be more practical to
> > start with.
>
> > On 16 Mayıs, 16:54, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> > wrote:
>
> > > I did... well, sorta semi-standalone. Much like the comments system,
> > > there's a couple of functions that have to be put in the model of the
> > > thing you're doing karma voting on... at least the way I did it.
>
> > > Wasn't too tough.
>
> > > On May 16, 6:31 am, omat <[EMAIL PROTECTED]> wrote:
>
> > > > Hi,
>
> > > > Neat design of the karma scoring application in the comments framework
> > > > of the contributed application is quite appealing. But it is tided to
> > > > the comments application.
>
> > > > I am trying to isolate it and make a more generic karma application
> > > > for any content (photos, blog entries, etc.) contributed by users.
>
> > > > I wonder if anybody has already did this or built a standalone
> > > > karmascore application...
>
> > > > oMat
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---