Skip to content

Commit

Permalink
12
Browse files Browse the repository at this point in the history
  • Loading branch information
fabilya committed Oct 1, 2023
1 parent 9a2380a commit 50d6a1c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
13 changes: 7 additions & 6 deletions backend/api/permissions.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from rest_framework.permissions import SAFE_METHODS, BasePermission


class IsAuthorOrReadOnly(BasePermission):

def has_permission(self, request, view):
return (request.method in SAFE_METHODS
or request.user.is_authenticated)
class IsAuthorOrAdminOrReadOnly(BasePermission):

def has_object_permission(self, request, view, obj):
return obj.author == request.user
return (
request.method in SAFE_METHODS
or request.user.is_authenticated
and request.user.is_staff
or request.user == obj.author
)
2 changes: 2 additions & 0 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ class Meta:
'name',
'text',
'cooking_time',
'author',
)
read_only_fields = ('author',)

def validate(self, data):
ingredients_data = data.get('ingredients')
Expand Down
8 changes: 4 additions & 4 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .filters import IngredientFilter, RecipeFilter
from recipes.models import (Favorite, Ingredient, IngredientAmount,
Recipe, ShoppingCart, Tag)
from .permissions import IsAuthorOrReadOnly
from .permissions import IsAuthorOrAdminOrReadOnly

from .serializers import (
FavoriteSerializer,
Expand Down Expand Up @@ -56,7 +56,7 @@ def get_permissions(self):

permissions_dict = {
'create': [permissions.IsAuthenticated()],
'partial_update': [IsAuthorOrReadOnly()],
'partial_update': [IsAuthorOrAdminOrReadOnly()],
'favorite': [permissions.IsAuthenticated()],
'shopping_cart': [permissions.IsAuthenticated()],
'download_shopping_cart': [permissions.IsAuthenticated()],
Expand Down Expand Up @@ -134,7 +134,7 @@ def download_shopping_cart(self, request):
).values(
'ingredient__name',
'ingredient__measurement_unit'
).annotate(amount=Sum('amount'))
).annotate(cart_amount=Sum('amount'))

today = datetime.today()
shopping_list = (
Expand All @@ -143,7 +143,7 @@ def download_shopping_cart(self, request):
shopping_list += '\n'.join([
f'- {ingredient["ingredient__name"]} '
f'({ingredient["ingredient__measurement_unit"]})'
f' - {ingredient["amount"]}'
f' - {ingredient["cart_amount"]}'
for ingredient in ingredients
])
shopping_list += f'\n\nFoodgram ({today:%Y})'
Expand Down

0 comments on commit 50d6a1c

Please sign in to comment.