我想编写一个Mixin(或使用第三方)来检查记录的用户是否是某个对象的所有者。
url(r'^api/mymodel/(?P<pk>\d)/?', CreateUpdateMyModel.as_view(), name='create_or_update')
class MyModel(models.Model):
owner = models.OneToOneField('auth.User')
class OwnerRequired(SingleObjectMixin):
# do this self.object = self.get_object() for getting the object
#
# some logic for checking if request.user == self.object.owner
# otherwise return something like Response(status=status.HTTP_403_FORBIDDEN)
继承SingleObjectMixin
对我很重要,因为我希望能够做到这样的事情:
class CreateUpdateMyModel(APIView, OwnerRequired):
model = MyModel
def post(self, request, *args, **kwargs):
# self.object should be available here
# so that write some code taking it into account
OwnerRequired
应该如何实现这一目标?
我可以接受另一种选择,事实上,我已经从django-braces中检查了PermissionRequiredMixin
并且我想使用它,但我不确定该怎么做
permission_required = ?? # I can code a method for, but how can I pass the model instance and the request.user?
还有另一种简单的选择吗?
答案 0 :(得分:1)
看看object level permissions。在示例部分中,该页面上还有相关示例 - 请参阅IsOwnerOrReadOnly example。
另请注意,对象级权限只能运行:
GenericAPIView
或其子类,并调用get_object()
来检索实例。self.check_object_permissions(request, instance
。