简体   繁体   English

如何限制用户在DRF ModelViewSet中看不到其他用户数据?

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

I've created a todo list API, which have user profiles. 我创建了一个具有用户配置文件的待办事项列表API。 Each User profile can have Todo List. 每个用户配置文件可以具有待办事项列表。 Now everything is working fine, but the issue here is one user can able to see other users data, but I want to restrict one user no to see other users todo list while am requesting a URL. 现在一切正常,但是这里的问题是一个用户可以查看其他用户的数据,但是我想限制一个用户不要在请求URL时看到其他用户的待办事项列表。

models.py 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 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 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 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

Unexpected Result: 意外结果:

[
    {
        "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"
    }
]

Expected result: 预期结果:

[
    {
        "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"
    },
]

I have to see only todo_item of user_profile 1 because user_profile: 1 is the user logged in. 我只需要查看user_profile 1的todo_item,因为user_profile:1是登录的用户。

You can try this. 你可以试试看 Return the record of specfic user 返回特定用户的记录

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)

hope it helps 希望能帮助到你

refer this 参考这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不调用 API 的情况下从 DRF 中的 ModelViewSet 获取数据 - How to get data from ModelViewSet in DRF without calling an API call 如何限制用户访问权限以查看/修改其他用户使用Django创建的对象 - How to restrict user acces to see/modify objects created by other users with Django 仅在 DRF 中检索当前用户的数据 - retrieve data for current user only in DRF 如何防止用户更改 URL<pk> 查看其他提交数据 Django</pk> - How to prevent user changing URL <pk> to see other submission data Django 无法发布到DRF模型视图集-request.data立即清空 - Cannot post to DRF modelviewset - request.data immediately emptied Django rest 框架:防止一个用户在 ModelViewSet 中删除/编辑/查看其他用户 - Django rest framework : Prevent one user from deleting/Editing/Viewing other users in ModelViewSet 如何在 DRF ModelViewSet 中为单独的请求方法设置权限? - How can I set permission for seperate request methods in DRF ModelViewSet? 如何将自定义值从 DRF ModelViewSet 传递到权限 class? - How can custom values be passed from a DRF ModelViewSet to a permissions class? 如何将用户与 Django drf 中的发布请求相关联 - How to associate user to a post request in Django drf 如何在 DRF 中返回用户名而不是用户 object? - How to return username instead of user object in DRF?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM