Skip to content

Commit

Permalink
review-fix. Shopping cart validation is now completely in serializers…
Browse files Browse the repository at this point in the history
…. Finished moving validation from views to serializers.
  • Loading branch information
Resistor-git committed Sep 25, 2023
1 parent 1099718 commit c56f80f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 44 deletions.
40 changes: 25 additions & 15 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,13 +286,6 @@ class Meta:
class SubscriptionCreateDestroySerializer(serializers.ModelSerializer):
"""Serialization and validation of subscriptions."""

class Meta:
model = Subscription
fields = (
'user',
'author',
)

def validate(self, data):
if self.context['request'].method == 'POST':
if data['user'] == data['author']:
Expand All @@ -310,6 +303,13 @@ def to_representation(self, instance):
'request': self.context.get('request')
}).data

class Meta:
model = Subscription
fields = (
'user',
'author',
)


class SubscriptionRetrieveSerializer(CustomUserRetrieveSerializer):
"""Provides information about the author and their recipes"""
Expand Down Expand Up @@ -359,14 +359,6 @@ def to_representation(self, instance):
instance['recipe'], context=context
).data

class Meta:
model = Favorite
fields = (
'id',
'user',
'recipe'
)

def validate(self, data):
if self.context['request'].method == 'POST':
if Favorite.objects.filter(user=data['user'], recipe=data['recipe']).exists():
Expand All @@ -377,6 +369,14 @@ def validate(self, data):
raise serializers.ValidationError('The recipe is not in favorites')
return data

class Meta:
model = Favorite
fields = (
'id',
'user',
'recipe'
)


class ShoppingCartSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
Expand All @@ -394,6 +394,16 @@ def validate_recipe(self, value):
f'Ingredient with id {value.id} does not exist'
)

def validate(self, data):
if self.context['request'].method == 'POST':
if ShoppingCart.objects.filter(user=data['user'], recipe=data['recipe']).exists():
raise serializers.ValidationError('The recipe is already in shopping cart')
return data
if self.context['request'].method == 'DELETE':
if ShoppingCart.objects.filter(user=data['user'], recipe=data['recipe']).exists():
return data
raise serializers.ValidationError('The recipe is not in shopping cart')

class Meta:
model = ShoppingCart
fields = (
Expand Down
44 changes: 16 additions & 28 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,46 +167,34 @@ def favorite(self, request, pk):
def shopping_cart(self, request, pk):
user = self.request.user
recipe = get_object_or_404(Recipe, pk=pk)
serializer = ShoppingCartSerializer(
data={'recipe': recipe.pk},
context={'request': request}
)

if request.method == 'POST':
if recipe:
serializer = ShoppingCartSerializer(
data={'recipe': recipe.pk},
context={'request': request}
)
serializer.is_valid(raise_exception=True)
if not ShoppingCart.objects.filter(
user=user,
recipe=recipe
).exists():
ShoppingCart.objects.create(user=user, recipe=recipe)
return Response(
serializer.data,
status=status.HTTP_201_CREATED
)
return Response(
{'errors': 'The recipe is already in shopping cart'},
status=status.HTTP_400_BAD_REQUEST
)
else:
if serializer.is_valid(raise_exception=True):
ShoppingCart.objects.create(user=user, recipe=recipe)
return Response(
{'errors': 'The recipe does not exist'},
status=status.HTTP_400_BAD_REQUEST
serializer.data,
status=status.HTTP_201_CREATED
)
return Response(
status=status.HTTP_400_BAD_REQUEST
)

if request.method == 'DELETE':
if ShoppingCart.objects.filter(user=user, recipe=recipe).exists():
if serializer.is_valid(raise_exception=True):
ShoppingCart.objects.get(user=user, recipe=recipe).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
else:
return Response(
{'errors': 'The recipe is not in shopping cart'},
status=status.HTTP_400_BAD_REQUEST
)
return Response(
status=status.HTTP_400_BAD_REQUEST
)

@action(
methods=['GET'],
detail=False,
permission_classes=[permissions.IsAuthenticated]
)
def download_shopping_cart(self, request):
shopping_cart_ingredients = RecipeIngredient.objects.filter(
Expand Down
2 changes: 1 addition & 1 deletion backend/foodgram/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

SECRET_KEY = os.getenv('SECRET_KEY', 'default_stub_key')

DEBUG = False
DEBUG = True

ALLOWED_HOSTS = [
'127.0.0.1',
Expand Down

0 comments on commit c56f80f

Please sign in to comment.