votes.py 1.35 KB
Newer Older
luxcem's avatar
luxcem committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
from django.views.generic import ListView
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse


def upvote(request, content_type, object_id):
    ct = ContentType.objects.get_for_id(content_type)
    obj = ct.get_object_for_this_type(pk=object_id)
    obj.upvote(user=request.user)
    return HttpResponse({"success"})


def downvote(request, content_type, object_id):
    ct = ContentType.objects.get_for_id(content_type)
    obj = ct.get_object_for_this_type(pk=object_id)
    obj.downvote(user=request.user)
    return HttpResponse({"success"})


class UDList(ListView):
    """
    Ads id upvoted by user
    """
    def get_context_data(self, **kwargs):
        content_type = ContentType.objects.get_for_model(self.model)
        queryset = self.get_queryset()
        context = super().get_context_data(**kwargs)
        context["und_votes"] = {
            "upvoted": queryset.filter(
                und_votes__user=self.request.user,
                und_votes__content_type=content_type,
                und_votes__score=1
            ).values_list("id", flat=True),
            "downvoted": queryset.filter(
                und_votes__user=self.request.user,
                und_votes__content_type=content_type,
                und_votes__score=-1
            ).values_list("id", flat=True)
        }
        return context