본문 바로가기
BE/Python & Django REST API

[Django REST API] 12. Create profile feed API

by 건빵거늬 2021. 12. 25.
1. Plan profile feed
2. Add feed model
3. Create profile feed serializer
4. Create Viewset for profile feed item
5. Add permissions

1. Plan profile feed

(1) Requirements

  • CRUD feed items
  • R other user's feed items

(2) API URLs

2. Add feed model

(1) model 만들기

(2) admin 페이지 등록

3, 4. Create profile serializer, viewset

5. Add permissions

# permissions.py

class UpdateOwnStatus(permissions.BasePermission):
    """Allow users to update their own status"""

    def has_object_permission(self, request, view, obj):
        """Check the user is trying to update their own status"""
        if request.method in permissions.SAFE_METHODS:
            return True

        return obj.user_profile.id == request.user.id
# views.py

from rest_framework.permissions import IsAuthenticatedOrReadOnly
# IsAuthenticatedOrReadOnly의 대안으로 IsAuthenticated 도 있다.
...

class UserProfileFeedViewSet(viewsets.ModelViewSet):
    """Handles creating, reading and updating profile feed items."""
    ...
    permission_classes = (
        permissions.UpdateOwnStatus,
        IsAuthenticatedOrReadOnly
        # 대안으로 IsAuthenticated 를 쓰면 아예 읽기도 막을 수 있다
    )
    ...

댓글