我正在使用 django-tastypie 编写 API .我希望有两个自定义权限问题 django-guardian可以修复。
我有两个用户组 Clinicians 和 Patients。临床医生应该能够访问只属于他们的患者的对象,而患者应该只能访问他们自己创建的对象。
我的代码如下:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
class BlogPostResource(ModelResource):
author = fields.ToOneField(UserResource, 'author', full=True)
class Meta:
queryset = BlogPost.objects.all()
resource_name = 'posts'
allowed_methods = ["get", "post"]
# Add it here.
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
filtering = {
'author': ALL_WITH_RELATIONS,
}
如何使用权限来限制对此 BlogPostResource
的访问?
最佳答案
您可以通过自定义 Authorization 来实现这一点类,例如:
class CustomAuthorization(Authorization):
def apply_limits(self, request, object_list):
...
clin_group = Group.objects.get(name='YOUR GROUP')
if request and hasattr(request, 'user'):
if clin_group in request.user.groups.all():
object_list = object_list.filter(user__in=request.user.patients.all()) # or however you stop clinician>patient relation
else:
object_list = object_list.filter(user=request.user)
return object_list
关于python - 限制对仅拥有的内容 django 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15477521/