Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.9 kB
0
Indexable
Never
from django.urls import include, path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'groups', views.GroupViewSet)
router.register(r'posts', views.PostViewSet)
router.register(r'comments', views.CommentViewSet)

urlpatterns = [
    path('api/v1/', include(router.urls)),
    path('api/v1/api-token-auth/', views.obtain_auth_token),
]


from rest_framework import viewsets
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import IsAuthenticated

from posts.models import Group, Post, Comment
from rest_framework.response import Response

from .serializers import GroupSerializer, PostSerializer, CommentSerializer
from .permissions import IsAuthorOrReadOnly

API_PERMISSIONS = [IsAuthenticated, IsAuthorOrReadOnly]


class GroupViewSet(viewsets.ModelViewSet):
    """Viewset для модели Group."""

    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class PostViewSet(viewsets.ModelViewSet):
    """Viewset для модели Post"""

    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = API_PERMISSIONS

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()

        if instance.author != request.user:
            raise PermissionDenied("Вы не можете изменять чужие данные.")

        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        return Response(serializer.data)


class CommentViewSet(viewsets.ModelViewSet):
    """Viewset для модели Comment"""

    permission_classes = API_PERMISSIONS
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer