def recompute_ratings(obj_type='all'): if obj_type == 'all': recompute_objs = ((rating_config['model'], rating_config['compute_func']) for rating_config in settings.RATINGS_CONFIG.itervalues()) elif obj_type in settings.RATINGS_CONFIG: rating_config = settings.RATINGS_CONFIG[obj_type] recompute_objs = (rating_config['model'], rating_config['compute_func']) else: recompute_objs = () for model, compute_func in recompute_objs: recompute_obj_ratings(str_to_class(model), str_to_class(compute_func))
def set_rating(request, obj_type, obj_id, vote_type): error = "" if obj_type in RATINGS_CONFIG: model_name = RATINGS_CONFIG[obj_type]['model'] model = str_to_class(model_name) try: obj = model.objects.get(pk=obj_id) if obj.rating == None: rating = Rating.objects.create() rating.save() obj.rating = rating obj.save() vote, is_new = RatingVote.objects.get_or_create(user=request.user, rating=obj.rating) if is_new: vote.vote_type = vote_type vote.save() if vote_type == VOTE_LIKE: obj.rating.likes += 1 else: obj.rating.dislikes += 1 obj.rating.save() tasks.task_compute_object_rating(obj_type, obj) else: error = _("You already voted") except model.DoesNotExist: error = _("You can't vote for this object") else: error = _("You can't vote for this object") if request.is_ajax(): if error: return json_response({'status': "error", 'text': error}) else: return json_response({'status': "ok", 'text': _("Your vote successfully counted")}) return redirect(request.META.get('HTTP_REFERER', '/'))
def task_compute_object_rating(obj_type, obj): return str_to_class(settings.RATINGS_CONFIG[obj_type]['compute_func']).delay(obj.id)