DocManagerBackend/docmanager_backend/accounts/serializers.py

88 lines
2.6 KiB
Python
Raw Permalink Normal View History

2024-11-23 21:55:32 +08:00
from .models import CustomUser
from rest_framework import serializers
from django.contrib.auth.password_validation import validate_password
from django.core import exceptions as django_exceptions
from rest_framework.settings import api_settings
class CustomUserUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = [
"role"
]
2024-11-23 21:55:32 +08:00
class CustomUserSerializer(serializers.ModelSerializer):
2024-12-16 14:58:50 +08:00
birthday = serializers.DateField(format="%Y-%m-%d")
2024-11-23 21:55:32 +08:00
class Meta:
model = CustomUser
fields = [
"id",
"username",
"email",
"first_name",
"last_name",
"full_name",
"role",
"birthday",
"age",
"sex",
"date_joined",
]
read_only_fields = [
"id",
"username",
"email",
"full_name",
"role",
"birthday",
"age",
"sex",
"date_joined",
2024-11-23 21:55:32 +08:00
]
class CustomUserRegistrationSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
password = serializers.CharField(
write_only=True, style={"input_type": "password", "placeholder": "Password"}
)
2024-11-24 10:34:41 +08:00
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
birthday = serializers.DateField(format="%Y-%m-%d", required=True)
2024-11-23 21:55:32 +08:00
class Meta:
model = CustomUser
fields = ["email", "password", "first_name",
"last_name", "sex", "birthday"]
2024-11-23 21:55:32 +08:00
def validate(self, attrs):
user_attrs = attrs.copy()
user = self.Meta.model(**user_attrs)
password = attrs.get("password")
try:
validate_password(password, user)
except django_exceptions.ValidationError as e:
serializer_error = serializers.as_serializer_error(e)
errors = serializer_error[api_settings.NON_FIELD_ERRORS_KEY]
if len(errors) > 1:
raise serializers.ValidationError({"password": errors[0]})
else:
raise serializers.ValidationError({"password": errors})
2024-11-27 23:28:22 +08:00
if self.Meta.model.objects.filter(username=attrs.get("email")).exists():
2024-11-23 21:55:32 +08:00
raise serializers.ValidationError(
"A user with that email already exists.")
2024-11-23 21:55:32 +08:00
return super().validate(attrs)
def create(self, validated_data):
user = self.Meta.model(**validated_data)
user.is_active = False
user.set_password(validated_data["password"])
user.save()
return user