adds vote posting
also moves some validation code to the model
This commit is contained in:
@@ -10,4 +10,5 @@ def api_root(request, format=None):
|
||||
'artists': reverse('api-artists', request=request, format=format),
|
||||
'users': reverse('api-users', request=request, format=format),
|
||||
'albums': reverse('api-albums', request=request, format=format),
|
||||
'votes': reverse('api-votes', request=request, format=format),
|
||||
})
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from django.db import IntegrityError
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.authentication import SessionAuthentication
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from playlist.models import Vote
|
||||
from playlist.serializers import VoteSerializer
|
||||
from playlist.models import Vote, Profile
|
||||
from playlist.serializers import VoteSerializer, VoteSaveSerializer
|
||||
|
||||
class VoteListView(APIView):
|
||||
authentication_classes = [SessionAuthentication]
|
||||
@@ -17,6 +18,26 @@ class VoteListView(APIView):
|
||||
serializer = VoteSerializer(votes, many=True, context={'request': request})
|
||||
return Response(serializer.data)
|
||||
|
||||
def post(self, request):
|
||||
(profile,_) = Profile.objects.get_or_create(user=request.user)
|
||||
if not profile.can_vote:
|
||||
return Response({'error': 'User cannot vote'}, status=403)
|
||||
serializer = VoteSaveSerializer(data=request.data, context={'request': request})
|
||||
if serializer.is_valid():
|
||||
try:
|
||||
serializer.save(user=request.user)
|
||||
return Response(serializer.data, status=201)
|
||||
except IntegrityError:
|
||||
return Response({'error': 'Duplicate vote'}, status=400)
|
||||
return Response(serializer.errors, status=400)
|
||||
|
||||
def delete(self, request):
|
||||
if request.user.is_superuser:
|
||||
Vote.objects.all().delete()
|
||||
return Response(status=204)
|
||||
else:
|
||||
return Response(status=403)
|
||||
|
||||
class VoteDetailView(APIView):
|
||||
authentication_classes = [SessionAuthentication]
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
Reference in New Issue
Block a user