Skip to content

Instantly share code, notes, and snippets.

@synotna
Created July 15, 2015 13:01
Show Gist options
  • Save synotna/79f1e0128fb98394ceb6 to your computer and use it in GitHub Desktop.
Save synotna/79f1e0128fb98394ceb6 to your computer and use it in GitHub Desktop.
Field permissions mixin for Django Rest Framework
class FieldPermissionsMixin(object):
"""
A Serializer mixin for controlling which fields are included based on user permissions
Usage:
class MySerializer(FieldPermissionsMixin, serializers.ModelSerializer):
class Meta:
model = MyModel
field_permissions = {
'field': ['app.permission'],
}
"""
class Meta:
# field name: [list of permissions]
field_permissions = {}
def get_fields(self):
fields = super().get_fields()
user_permissions = self.context['request'].user.get_all_permissions()
for field, permissions in self.Meta.field_permissions.items():
# if user does not have one of the permissions to view the field, remove it
if not any(permission in user_permissions for permission in permissions):
fields.pop(field)
return fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment