Using ModelViewSet and DjangoObjectPermissions.
Django REST framework seems to not call check_object_permission for a "create" request (POST). I need to check the user is allowed to create THIS object before it's saved into database (because permission check depend of object values)
I suppose I need to override "create" method of the ModelViewSet but I didn't know how to get the instance from serializer without saving it to database.
Thanks
EDIT:
After deeping into DRF code, I'm able to get the instance without save :
def create(self, request, *args, **kwargs):
serializer = WorkedHourSerializer(data=request.data)
if serializer.is_valid():
instance = MyModel(**serializer.validated_data)
But Django refuse to check perm for an object without primary key so I have to force one :
instance.id = 0
self.check_object_permissions(request, instance)
There's no way to get the instance before saving it (see more)
The best approach would seem to be to implement a custom permission (probably subclassing rest_framework.permissions.BasePermission
or rest_framework.permissions.IsAuthenticated
) and adding the logic of permission checking in has_permission(self, request, view)
(see more). This way, you would access request.user
and then you would be able to determine whether that user has permission to create that object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With