CommentCreate是CreateAPIView
,用于在另一个“报告”模型上发表评论。我需要阻止任何不是报告作者的人,或者不允许发布评论的指定人群中的任何人使用此端点创建评论。
class CommentCreate(generics.CreateAPIView):
serializer_class = CommentSerializer
queryset = Comment.objects.none()
def check_object_permissions(self, request, obj):
if obj.report.creator != request.user:
# also check if request.user is in the group of people that can comment
raise exceptions.PermissionDenied(
detail='You do not have permission')
我面临的问题是check_object_permissions
被调用,但异常没有被捕获到任何地方,所以评论无论如何都会正常发布。我在这里缺少什么?
答案 0 :(得分:4)
创建check_object_permissions
时,不会调用方法Comment
。
以下是create
的完整CreateAPIView
代码:
class CreateModelMixin(object):
"""
Create a model instance.
"""
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
serializer.save()
def get_success_headers(self, data):
try:
return {'Location': data[api_settings.URL_FIELD_NAME]}
except (TypeError, KeyError):
return {}
check_object_permissions
仅在get_object
中调用,只有当您尝试通过API检索对象时,才会调用CommentCreate
。
要在perform_create
中进行权限检查,您应该覆盖其中的class CommentCreate(generics.CreateAPIView):
serializer_class = CommentSerializer
queryset = Comment.objects.none()
def perform_create(self, serializer):
# untested if...
if serializer.validated_data['report'].creator != self.request.user:
raise exceptions.PermissionDenied(
detail='You do not have permission')
serializer.save()
方法并进行检查:
{{1}}