[英]Create permissions based on model field names in django
我正在尝试创建权限,以便每个用户都可以查看特定作者的文章。 权限示例包括: Can view author1
, Can view author2
等,以及Can view all
。 在文章类中,我尝试如下创建权限:
class Article(models.Model)
#some not important stuff
class Meta:
permissions = (
('view_%s' % Author.name, 'Can view %s' % Author.name),
('view_all', 'Can view all'),
)
这是行不通的,据我所知,权限存储在数据库中,因此甚至可以通过这种方式创建权限吗?
我认为更好的设计解决方案是:
class Author(models.Model):
...
my_allowed_viewers = models.ManyToManyField('self', related_name='views_allowed', reverse=False)
然后像
class IsAuthorizedReader(permissions.BasePermission):
def has_permission(self, request, view):
author_id = request.user.id
author_to_view_id = request.data.get('author_to_view_id')
if author_to_view_id is not None:
return Authors.objects.get(pk=author_to_view_id).my_allowed_viewers.filter(author_id).exists()
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.