Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework serialize permission

I would like to serialize object level permission - and send a simple True or False to the browser - so accordingly I trigger the "allow editing" code.

I am doing this so the user does not have functionality presented to them that they cannot use.

Is there a built in way to do this? The docs do not allude to this.

I have attempted the following on the serializer:

has_permission = serializers.SerializerMethodField('check_permission')

def check_permission(self, obj):
    return self.check_object_permissions(self.request, obj)

but the serializer does not have the method check_object_permissions - that belongs to the permission object.

like image 317
Django Doctor Avatar asked Nov 01 '22 07:11

Django Doctor


1 Answers

Add method to your model to check the permissions:

 class MyModel(models.Model):
     myfield = models.TextField(max_length=100)

     def check_permissions(self):
        # Perform your permissions functions
        if (.....):
           return True
        else: 
           return False

Add custom field into your Serializer as follows:

  class MyModelSerializer(serializers.ModelSerializer):        
      has_permissions = serializers.BooleanField(source='check_permissions', read_only=True)
      class Meta:
         model = models.MyModel
         fields = ("myfield","has_permissions")
like image 172
HungryArthur Avatar answered Nov 15 '22 09:11

HungryArthur