75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
![]() |
from rest_framework import serializers
|
||
|
from django.contrib.auth import authenticate
|
||
|
from django.contrib.auth.password_validation import validate_password
|
||
|
from .models import User
|
||
|
|
||
|
|
||
|
class UserRegistrationSerializer(serializers.ModelSerializer):
|
||
|
"""用户注册序列化器"""
|
||
|
password = serializers.CharField(write_only=True, validators=[validate_password])
|
||
|
password_confirm = serializers.CharField(write_only=True)
|
||
|
|
||
|
class Meta:
|
||
|
model = User
|
||
|
fields = ('username', 'email', 'first_name', 'last_name',
|
||
|
'phone', 'department', 'position', 'password', 'password_confirm')
|
||
|
|
||
|
def validate(self, attrs):
|
||
|
if attrs['password'] != attrs['password_confirm']:
|
||
|
raise serializers.ValidationError("密码不一致")
|
||
|
return attrs
|
||
|
|
||
|
def create(self, validated_data):
|
||
|
validated_data.pop('password_confirm', None)
|
||
|
user = User.objects.create_user(**validated_data)
|
||
|
return user
|
||
|
|
||
|
|
||
|
class UserLoginSerializer(serializers.Serializer):
|
||
|
"""用户登录序列化器"""
|
||
|
username = serializers.CharField()
|
||
|
password = serializers.CharField(write_only=True)
|
||
|
|
||
|
def validate(self, attrs):
|
||
|
username = attrs.get('username')
|
||
|
password = attrs.get('password')
|
||
|
|
||
|
if username and password:
|
||
|
user = authenticate(username=username, password=password)
|
||
|
if not user:
|
||
|
raise serializers.ValidationError('用户名或密码错误')
|
||
|
if not user.is_active:
|
||
|
raise serializers.ValidationError('用户账号已被禁用')
|
||
|
attrs['user'] = user
|
||
|
else:
|
||
|
raise serializers.ValidationError('用户名和密码不能为空')
|
||
|
|
||
|
return attrs
|
||
|
|
||
|
|
||
|
class UserProfileSerializer(serializers.ModelSerializer):
|
||
|
"""用户信息序列化器"""
|
||
|
full_name = serializers.SerializerMethodField()
|
||
|
|
||
|
class Meta:
|
||
|
model = User
|
||
|
fields = ('id', 'username', 'email', 'first_name', 'last_name',
|
||
|
'full_name', 'phone', 'department', 'position', 'avatar',
|
||
|
'is_staff', 'is_superuser', 'date_joined')
|
||
|
read_only_fields = ('id', 'username', 'is_staff', 'is_superuser', 'date_joined')
|
||
|
|
||
|
def get_full_name(self, obj):
|
||
|
return f'{obj.first_name} {obj.last_name}'.strip() or obj.username
|
||
|
|
||
|
|
||
|
class UserListSerializer(serializers.ModelSerializer):
|
||
|
"""用户列表序列化器"""
|
||
|
full_name = serializers.SerializerMethodField()
|
||
|
|
||
|
class Meta:
|
||
|
model = User
|
||
|
fields = ('id', 'username', 'full_name', 'email', 'department', 'position', 'is_active')
|
||
|
|
||
|
def get_full_name(self, obj):
|
||
|
return f'{obj.first_name} {obj.last_name}'.strip() or obj.username
|