如何覆盖 renderer_classes 以在 REST API 中发送额外信息

How to override the renderer_classes to send extra information in REST API

我已经创建了其余 api 用于用户身份验证,并且在响应中我得到了令牌。我还想添加用户是否有工作人员权限,我已经得到了序列化程序的信息,但我无法传递给视图。

而且我需要验证用户是否处于活动状态这部分根本不起作用。

我的序列化程序代码:

class AuthTokenSerializer(serializers.Serializer):
    """Serializer for the user authentication object"""
    email = serializers.CharField()
    password = serializers.CharField(
        style={'input_type': 'password'},
        trim_whitespace=False
    )

    def validate(self, attrs):
        """Validate and authenticate the user"""
        email = attrs.get('email')
        password = attrs.get('password')

        user = authenticate(
            request=self.context.get('request'),
            username=email,
            password=password
        )
#This part I am trying to authenticate whether the account is active or not 
        if user is not None:
            if not user.is_active:
                msg = _('The password is valid, but the account has been disabled! ')
                raise serializers.ValidationError(msg, code='not_active')

        if not user:
            msg = _('Unable to authenticate with provided credentials')
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        attrs['is_staff'] = user.is_staff  #Here I am getting the user has permission of staff or not.
        return attrs

而 views.py 是:

class CreateTokenView(ObtainAuthToken):
    """Create a new auth token for the user"""
    serializer_class = AuthTokenSerializer
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

models.py

class User(AbstractBaseUser, PermissionsMixin):
    """Custom user model that supports using email instead of username"""
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    image = models.ImageField(null=True, upload_to=user_image_file_path)
    contact_no = models.CharField(max_length=255, default='')
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

我怎样才能覆盖我的观点,以便我可以获得这两个信息。任何信息都会有很大帮助。谢谢

由于您想要更改 post 响应的默认行为,因此您需要明确更改它。

那么我们如何才能做到这一点。我们需要覆盖ObtainAuthTokenpost方法。希望以下代码能解决您的问题。

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

class CreateTokenView(ObtainAuthToken):
    serializer_class = AuthTokenSerializer
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'is_staff': user.is_staff
        })

参考资料: django-restframework example