Example #1
0
def cast_vote(request, comment_id, positive):
    comment_ct = ContentType.objects.get_for_model(Comment)       

    # Check if the comment already exists
    try:
        existing_vote = Vote.objects.get(
            parent_id=comment_id, parent_type=comment_ct,
            positive=positive, user=request.user
        )

        existing_vote.delete()

        response = {'status': 'unvote success'}
        return HttpResponse(
            json.dumps(response), 200, content_type="application/json")        
    except Vote.DoesNotExist:
        try:
            comment = Comment.objects.get(pk=comment_id)

            # Create the vote and save it
            new_vote = Vote()
            new_vote.user = request.user
            new_vote.positive = positive
            new_vote.parent = comment
            new_vote.save()

            if positive:
                # Send out a notification to the person who originally wrote
                # the comment, if a positive vote is casted.
                Vote.vote_casted.send(sender="Comments", vote=new_vote)

            return APIUtilities._api_success()
        except:
            return APIUtilities._api_failure()
Example #2
0
def cast_resource_revision_vote(request, resource_id, revision_id, positive):
    try:
        from oer.models import Resource, ResourceRevision
        Resource.objects.get(pk=resource_id)
        revision = ResourceRevision.objects.get(pk=revision_id)
    except:
        return APIUtilities._api_not_found()

    # Check if the vote already exists.
    try:
        from django.contrib.contenttypes.models import ContentType
        resource_revision_ct = ContentType.objects.get_for_model(ResourceRevision)

        existing_vote = Vote.objects.get(
            user=request.user, parent_type=resource_revision_ct, parent_id=revision.id,
            positive=positive)

        existing_vote.delete()

        context = {'action': 'unvote'}
        return APIUtilities._api_success(context)

    except Vote.DoesNotExist:
        try:
            # Create the vote and save it
            new_vote = Vote()
            new_vote.user = request.user
            new_vote.positive = positive
            new_vote.parent = revision
            new_vote.save()

            if positive and revision.user != request.user:
                Vote.resource_revision_vote_casted.send(sender="ResourceRevision", vote=new_vote)

            return APIUtilities._api_success()
        except:
            context = {
                'title': 'Unable to cast revision vote',
                'message': 'We apologize as we failed to cast your vote on this resource revision. '
                + 'Please contact us if the problem persists.'
            }
            return APIUtilities._api_failure(context)