Django 令牌和会话身份验证

Django Token and Session auth

我正在为自定义用户模型创建一个登录模型,它与 django 一起工作正常,现在我尝试转换为 Rest。

它正在创建令牌,但它没有 return 令牌并且会话也为空

(生成令牌但 serializer.data 为空) enter image description here

(会话数据库为空) enter image description here

django Serializer.py

class UserLoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
    required=False,
    allow_blank=True,
    write_only=True,
    label="Email "
)

password = serializers.CharField(
    required=True,
    write_only=True,
    style={'input_type': 'password'}
)

class Meta(object):
    model = User
    fields = ['email', 'password']

def validate(self, data):
    email = data.get('email', None)
    password = data.get('password', None)

    if not email:
        raise serializers.ValidationError("Please enter email to login.")

    user = User.objects.filter(Q(email=email)).exclude(email__iexact="").exclude(email__isnull=True).distinct()
    if user.exists():
        user1 = authenticate(email=email, password=password)
        if user1 is not None:
            if user1.is_active:
                token, created = Token.objects.get_or_create(user=user1)
                data['token'] = token
            else:
                raise serializers.ValidationError("Account not active.")
        else:
            raise serializers.ValidationError("Invalid credentials.")
    else:
        raise serializers.ValidationError("This email is not valid.")


    return data

Django view.py

class UserLogin(views.APIView):
permission_classes = (permissions.AllowAny, )
serializer_class = UserLoginSerializer

def post(self, request):
    serializers = self.serializer_class(data=request.data)
    print(serializers)
    if serializers.is_valid(raise_exception=True):
        print("data", serializers.data)
        return Response(serializers.data, status=status.HTTP_200_OK)
    return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)

您可以在序列化程序中添加令牌字段。

class UserLoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
    required=False,
    allow_blank=True,
    write_only=True,
    label="Email "
)

password = serializers.CharField(
    required=True,
    write_only=True,
    style={'input_type': 'password'}
)
token = serializers.SerializerMethodField()

class Meta(object):
    model = User
    fields = ['email', 'password']

def validate(self, data):
    email = data.get('email', None)
    password = data.get('password', None)

    if not email:
        raise serializers.ValidationError("Please enter email to login.")

    user = User.objects.filter(Q(email=email)).exclude(email__iexact="").exclude(email__isnull=True).distinct()
    if user.exists():
        user1 = authenticate(email=email, password=password)
        if user1 is not None:
            if user1.is_active:
                token, created = Token.objects.get_or_create(user=user1)
                data['token'] = token
            else:
                raise serializers.ValidationError("Account not active.")
        else:
            raise serializers.ValidationError("Invalid credentials.")
    else:
        raise serializers.ValidationError("This email is not valid.")


    return data
    def get_token(self, obj):
        try:
            return Token.objects.get(user=obj).key
        except:
            return ''