Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check object permission before create in Django rest framework

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.

  1. How to get the object instance from serializer without saving to database ?
  2. Or how to have DRF check for object permission for a POST/create request ?

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)
like image 259
fabien-michel Avatar asked Nov 14 '16 14:11

fabien-michel


1 Answers

  1. There's no way to get the instance before saving it (see more)

  2. 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.

like image 129
lucasnadalutti Avatar answered Oct 27 '22 13:10

lucasnadalutti