Created
September 24, 2019 09:29
-
-
Save grillazz/89b0bca72e9770d445148937f26ea89d to your computer and use it in GitHub Desktop.
DRF overwriting __init__ for Serializer to conditionally add fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework.serializers import HyperlinkedModelSerializer | |
from dry_rest_permissions.generics import DRYPermissionsField | |
from .models import CustomUser | |
class CustomUserSerializer(HyperlinkedModelSerializer): | |
permissions = DRYPermissionsField(additional_actions=["activate", "deactivate"]) | |
class Meta: | |
model = CustomUser | |
fields = ("url", "id", "name", "email", "permissions", "role", "is_active") | |
# non admin should't be able to update role and is_active | |
read_only_fields = ["role", "is_active"] | |
class ForAdminCustomUserSerializer(CustomUserSerializer): | |
class Meta: | |
model = CustomUser | |
fields = ("url", "id", "name", "email", "permissions", "role", "is_active") | |
def __init__(self, *args, **kwargs): | |
super(CustomUserSerializer, self).__init__(*args, **kwargs) | |
# get the request from parent serializer's context | |
request_obj = self.context.get('request') | |
# add extra fields if user is admin | |
if request_obj.user.role == 'ADMIN': | |
self.Meta.fields = list(self.Meta.fields) | |
self.Meta.fields.extend(["role", "is_active"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment