簡體   English   中英

如何限制用戶在DRF ModelViewSet中看不到其他用戶數據?

[英]How to restrict user not to see other user data in DRF ModelViewSet?

我創建了一個具有用戶配置文件的待辦事項列表API。 每個用戶配置文件可以具有待辦事項列表。 現在一切正常,但是這里的問題是一個用戶可以查看其他用戶的數據,但是我想限制一個用戶不要在請求URL時看到其他用戶的待辦事項列表。

models.py

class TodoListItem(models.Model):
    """Todo List"""

    user_profile = models.ForeignKey('UserProfile', on_delete=models.CASCADE)
    todo_item = models.CharField(max_length=150)
    description = models.CharField(max_length=255)
    created_on = models.DateTimeField(auto_now_add=True)
    reminder_date = models.DateTimeField()

    def __str__(self):
        """Return the model as the string"""

        return self.todo_item

views.py

class TodoItemViewSet(viewsets.ModelViewSet):
    """Handles creating, reading, and updating profile Todo Items."""

    authentication_classes = (TokenAuthentication,)
    serializer_class = serializers.TodoItemSerializer
    queryset = models.TodoListItem.objects.all()
    permission_classes = (permissions.UpdateTodoItem, IsAuthenticated)

    def perform_create(self, serializer):
        """Sets the user profile to the logged in User."""

        serializer.save(user_profile=self.request.user)

serializers.py

class TodoItemSerializer(serializers.ModelSerializer):
    """Serializer for Todo Items."""

    class Meta:
        model = models.TodoListItem
        fields = ('id', 'user_profile', 'todo_item', 'description', 'created_on', 'reminder_date')
        extra_kwargs = {'user_profile': {'read_only': True}}

Permissions.py

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

    def has_object_permission(self, request, view, obj):
        """Check 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

意外結果:

[
    {
        "id": 1,
        "user_profile": 1,
        "todo_item": "Todo Item 1",
        "description": "Sample todo item 1",
        "created_on": "2019-06-06T04:48:59.401451Z",
        "reminder_date": "2019-06-02T04:48:57Z"
    },
    {
        "id": 2,
        "user_profile": 2,
        "todo_item": "Todo Item 2",
        "description": "Sample todo item 3",
        "created_on": "2019-06-06T04:50:08.734365Z",
        "reminder_date": "2019-06-03T04:50:07Z"
    },
    {
        "id": 3,
        "user_profile": 1,
        "todo_item": "Todo Item 2",
        "description": "",
        "created_on": "2019-06-06T04:54:47.919602Z",
        "reminder_date": "2019-06-07T02:00:00Z"
    },
    {
        "id": 4,
        "user_profile": 1,
        "todo_item": "Todo Item 4",
        "description": "Sample todo item 4",
        "created_on": "2019-06-06T05:00:08.004224Z",
        "reminder_date": "2019-06-07T10:01:00Z"
    }
]

預期結果:

[
    {
        "id": 1,
        "user_profile": 1,
        "todo_item": "Todo Item 1",
        "description": "Sample todo item 1",
        "created_on": "2019-06-06T04:48:59.401451Z",
        "reminder_date": "2019-06-02T04:48:57Z"
    },
    {
        "id": 3,
        "user_profile": 1,
        "todo_item": "Todo Item 2",
        "description": "",
        "created_on": "2019-06-06T04:54:47.919602Z",
        "reminder_date": "2019-06-07T02:00:00Z"
    },
    {
        "id": 4,
        "user_profile": 1,
        "todo_item": "Todo Item 4",
        "description": "Sample todo item 4",
        "created_on": "2019-06-06T05:00:08.004224Z",
        "reminder_date": "2019-06-07T10:01:00Z"
    },
]

我只需要查看user_profile 1的todo_item,因為user_profile:1是登錄的用戶。

你可以試試看 返回特定用戶的記錄

class TodoItemViewSet(viewsets.ModelViewSet):
    """Handles creating, reading, and updating profile Todo Items."""

    authentication_classes = (TokenAuthentication,)
    serializer_class = serializers.TodoItemSerializer
    queryset = models.TodoListItem.objects.all()
    permission_classes = (permissions.UpdateTodoItem, IsAuthenticated)

    def perform_create(self, serializer):
        """Sets the user profile to the logged in User."""
        serializer.save(user_profile=self.request.user)

    def get_queryset(self):
        return self.queryset.filter(user_profile=self.request.user)

希望能幫助到你

參考這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM