diff --git a/cinema/views.py b/cinema/views.py index 242852f2..fc0b8e72 100644 --- a/cinema/views.py +++ b/cinema/views.py @@ -9,6 +9,7 @@ DestroyModelMixin, ) from django.http import Http404 +from django.shortcuts import get_object_or_404 from cinema.models import Genre, Actor, CinemaHall, Movie from cinema.serializers import ( @@ -27,18 +28,14 @@ def get(self, request) -> Response: def post(self, request) -> Response: serializer = GenreSerializer(data=request.data) - 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) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) class GenreDetail(APIView): def get_object(self, pk: int) -> Genre: - try: - return Genre.objects.get(pk=pk) - except Genre.DoesNotExist: - raise Http404 + return get_object_or_404(Genre, pk=pk) def get(self, request, pk: int) -> Response: genre = self.get_object(pk) @@ -48,18 +45,16 @@ def get(self, request, pk: int) -> Response: def put(self, request, pk: int) -> Response: genre = self.get_object(pk) serializer = GenreSerializer(genre, data=request.data) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data) def patch(self, request, pk: int) -> Response: genre = self.get_object(pk) serializer = GenreSerializer(genre, data=request.data, partial=True) - if serializer.is_valid(): - serializer.save() - return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(serializer.data) def delete(self, request, pk: int) -> Response: genre = self.get_object(pk)