from rest_framework.viewsets import ViewSet from rest_framework.response import Response from django.shortcuts import get_object_or_404 from rest_framework import status from django.core.exceptions import ObjectDoesNotExist from image.models import Image from image.serializers import ImageSerializer, ImageUpdateSerializer class ImageViewSet(ViewSet): def list(self, request): image_list = [] images = Image.objects.all() for image in images: image_list.append(image.get()) serializer = ImageSerializer(image_list, many=True) return Response(serializer.data) def create(self, request): serializer = ImageSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data new_image = Image.create_from_user( description=data['description'], file_format=data['file_format'], image_file=data['image_file'], name=data['name'], user=request.user ) serializer = ImageSerializer(instance=new_image) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Image.objects.all() image = get_object_or_404(queryset, pk=pk) image = image.get() serializer = ImageSerializer(instance=image) return Response(serializer.data) def update(self, request, pk=None): serializer = ImageUpdateSerializer(data=request.data) serializer.is_valid(raise_exception=True) queryset = Image.objects.all() image = get_object_or_404(queryset, pk=pk) image = image.update(serializer.validated_data) serializer = ImageSerializer(instance=image) return Response(serializer.data) def partial_update(self, request, pk=None): return self.update(request, pk) def destroy(self, request, pk=None): try: image = Image.objects.get(id=pk) image.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ObjectDoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT)