diff --git a/program/views.py b/program/views.py index 8e88c6efe90caf5a095a538de925d3a9685acdea..1bee42fb3165b7031775b38a8d4fcf343327b664 100644 --- a/program/views.py +++ b/program/views.py @@ -40,6 +40,7 @@ from program.models import ( Category, FundingCategory, Host, + Image, Language, LicenseType, LinkType, @@ -58,6 +59,7 @@ from program.serializers import ( ErrorSerializer, FundingCategorySerializer, HostSerializer, + ImageSerializer, LanguageSerializer, LicenseTypeSerializer, LinkTypeSerializer, @@ -295,6 +297,63 @@ class APIUserViewSet( return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) +class APIImageViewSet(viewsets.ModelViewSet): + queryset = Image.objects.all() + serializer_class = ImageSerializer + permission_classes = [permissions.DjangoModelPermissionsOrAnonReadOnly] + pagination_class = LimitOffsetPagination + + def get_queryset(self): + """The queryset contains only images where the owner is the request's user.""" + + return Image.objects.filter(owner=self.request.user.username) + + def create(self, request, *args, **kwargs): + """Create an Image instance. Any user can create an image.""" + + serializer = ImageSerializer( + data=request.data, + context={"owner": request.user.username}, + ) + + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def update(self, request, *args, **kwargs): + """Update an Image instance. Only the creator can update an image.""" + + image = self.get_object() + + if image.owner != request.user.username: + return Response(status=status.HTTP_403_FORBIDDEN) + + serializer = ImageSerializer( + image, + data=request.data, + ) + + if serializer.is_valid(): + serializer.save() + return Response(serializer.data) + + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def destroy(self, request, *args, **kwargs): + """Destroy an Image instance. Only the owner can delete an image.""" + + image = self.get_object() + + if image.owner != request.user.username: + return Response(status=status.HTTP_401_UNAUTHORIZED) + + image.delete() + + return Response(status=status.HTTP_204_NO_CONTENT) + + @extend_schema_view( create=extend_schema(summary="Create a new show."), retrieve=extend_schema(summary="Retrieve a single show."),