扩展djoser登录方法以获取用户角色

时间:2019-07-20 15:43:46

标签: python django djoser

Djoser登录api返回用户令牌,我也想返回用户角色。如何执行这种情况?这是登录方法:

def login_user(request, user):
    token, _ = settings.TOKEN_MODEL.objects.get_or_create(user=user)
    if settings.CREATE_SESSION_ON_LOGIN:
        login(request, user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
    return token

我的目标是实现以下目标:

def login_user(request, user):
    token, new_user = settings.TOKEN_MODEL.objects.get_or_create(user=user)
    if not new_user:
        token_and_roles = {
            token: token,
            roles: [for group.lower() in User.objects.get(user).groups]
        }
        return token_and_roles
    if settings.CREATE_SESSION_ON_LOGIN:
        login(request, user)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
    return token

如何覆盖djoser api登录方法?

1 个答案:

答案 0 :(得分:0)

请参考djoser serializer settings doc-您需要编写自己的TokenSerializer版本,然后在设置中进行设置:

DJOSER = {
    "SERIALIZERS": {"token": "myapp.serializers.MyTokenSerializer"},
}