Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Permission Check On Create

Why doesn't django rest framework check object permissions when creating an object? It makes no sense (to me, anyway) that a user should be able to create an object they couldn't see, update, or delete. Currently I subclass a viewset like

class CheckCreatePermissionsViewSet(ModelViewSet):
    def perform_create(self, serializer):
    '''
    Called by create before calling serializer.save()
    '''
    obj = serializer.save()
    try:
        self.check_object_permissions(obj)
    except:
        obj.delete()
        raise

Why isn't this implemented by default? It's caused quite the headache for me, and I can't think of a single reason it would be implemented like this.

like image 925
cderwin Avatar asked Dec 04 '15 01:12

cderwin


1 Answers

I find it way more natural and explicit that you call the business logic validation before creating the object rather than create the object and figuring whether or not the user can see it to delete it.

class CheckCreatePermissionsViewSet(ModelViewSet):
    def perform_create(self, serializer):
        try:
            business_rules_are_ok(serializer.data, user):
        except BusinessException:
            raise ValidationError(<content from BusinessException)
        serializer.save()
like image 71
Linovia Avatar answered Oct 12 '22 11:10

Linovia