这对我有用,请尝试
假设您正确安装了djangorestframework_simplejwt
只需将其粘贴到settings.py的末尾即可
REST_AUTH_SERIALIZERS = {
'USER_DETAILS_SERIALIZER': 'users.serializers.UserSerializer',
}
这里 UserSerializer 使用 CustomUserModel 即
serializers.py
class UserSerializer(serializer.ModelSerializer):
class Meta:
model = get_user_model()
fields = []
read_only_fields = ( ,)
并添加覆盖 TokenObtainPairView 的默认序列化程序验证方法的序列化程序
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
# The default result (access/refresh tokens)
data = super().validate(attrs)
refresh = self.get_token(self.user)
# assign token
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
# extra fields
data['age'] = self.user.age
return data
在此帮助下,我在调用登录端点时获得了我制作的 CustomUser 的“年龄”模型字段。
在您的视图类中使用此序列化程序,然后调用此视图的 url 在调用此 url 之后
返回数据如下:
{
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..............",
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...............",
"username": "Shubham",
"id": 4,
"age": 100,
"description": "Slow shubham gadwal mehra try to understand."
}