依赖权限在Django REST框架中

huangapple go评论57阅读模式
英文:

Dependant permissions in django rest framework

问题

我有一个查询 -

假设我有笔记本(物理学,化学,数学,...),我想通过实施一些权限来在这些笔记本中添加笔记 -

  1. 如果我有查看笔记本的权限,我必须能够在下拉菜单中看到所有/某些笔记本

  2. 只有在我被允许访问某个笔记本并被允许在该笔记本内添加/删除/查看笔记时,我才能够添加/删除/查看该笔记本内的笔记

如何最好地实现这种情况的方法是什么

我在stackoverflow上搜索过,但没有找到任何相关答案。

英文:

I have a query -

Suppose I have a notebooks (Physics,Chemistry,Math,...) and I want to put note in these notebooks by implementing some permissions -

  1. If I have permissions to view notebooks and I must be able to see all/some note books in drop down

  2. I should be able to add/delete/view note inside any notebook if I am allowed to access that notebook and allowed to add/delete/view note inside that notebook

What could be best approach to implement this situation best

I walk around stack overflow but did not find any answer regarding it

答案1

得分: 0

你可以根据正在执行的操作覆盖视图中的 get_permissions 类,还可以添加自定义权限,以下是在与 ModeViewSet 一起使用的示例:

def get_permissions(self):
    if self.action in ['create', 'list', 'retrieve']:
        # 如果已登录,添加或查看记录
        return (permissions.IsAuthenticated(),)
    else:
        # 如果已登录并添加了记录,可以删除或更新记录
        return (permissions.IsAuthenticated(), IsOwner(),)

IsOwner 是来自 permissions.py 中的自定义权限类,如下所示:

from rest_framework import permissions

class IsOwner(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        return obj.user == request.user

这个示例自定义类检查已登录用户是否是创建记录的用户,假设在 notebook 模型中有一个用户 pk。

此外,在用户模型中,您可以设置 is_staff=True 并使用 permissions.IsAdminUser 来允许用户查看记录,或者创建一个基于某种用户类型的自定义权限类。

英文:

You can override the get_permissions class in your view depending on the action being performed, you can also add in your own permission, here is an example working with ModeViewSet.

def get_permissions(self):
    if self.action in ['create', 'list', 'retrieve']:
        # Add or View records if you are logged in
        return (permissions.IsAuthenticated(),)
    else:
        # Delete or update records if you are logged in and added the record
        return (permissions.IsAuthenticated(), IsOwner(),)

IsOwner is coming from a custom permission class in permissions.py as below:

from rest_framework import permissions


class IsOwner(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        return obj.user == request.user

This example custom class checks if the logged in user is the user that created the record assuming there is a user pk in the notebook model.

Also in your user model, you can set is_staff=True and user permissions.IsAdminUser for users allowed to view the records or create a custom permission class to be based on some user type.

huangapple
  • 本文由 发表于 2023年6月13日 13:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定