Добрый день!
Подскажите почему могу создать пользователя без пароля или с простым паролем 123
мне казалось в модели AbstractUser в Django присутствует валидация длины и присутствия пароля
Моя модель
class User(AbstractUser):
"""The user's model."""
username = models.CharField(
max_length=MAX_LENGTH,
verbose_name="Имя пользователя",
unique=True,
db_index=True,
)
first_name = models.CharField(max_length=MAX_LENGTH,
verbose_name="Имя")
last_name = models.CharField(
max_length=MAX_LENGTH,
verbose_name="Фамилия"
)
email = models.EmailField(
verbose_name="Электронная почта",
unique=True
)
is_subscribed = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "first_name", "last_name"]
class Meta:
verbose_name = "Пользователь"
verbose_name_plural = "Пользователи"
ordering = ("id",)
def __str__(self):
return self.username
Мой serializer
class CustomCreateUserSerializer(serializers.ModelSerializer):
"""Serializer for create User"""
username = serializers.CharField(
max_length=150,
validators=[
RegexValidator(
regex=r"^[\w.@+-]+$",
message=(' "имя пользователя" должно содержать только'
'буквы(латиницу), цифры, точки, символы'
'подчеркивания, дефисы, а также символы @ и +.'),
)
],
)
password = serializers.CharField(
max_length=128,
write_only=True,
validators=[MinLengthValidator(8)],
error_messages={
'blank': 'Password cannot be blank.',
'min_length': 'Password must be at least 8 characters long.',
}
)
def validate_username(self, value):
if User.objects.filter(username=value).exists():
raise serializers.ValidationError("Username already exists.")
return value
class Meta:
model = User
fields = (
"email",
"id",
"username",
"first_name",
"last_name",
"password",
)
extra_kwargs = {"password": {"write_only": True},
"email": {"required": True}}
def create(self, validated_data):
password = validated_data.pop('password')
if not password:
raise serializers.ValidationError("Password is required.")
user = User.objects.create(**validated_data)
user.set_password(password)
user.save()
return user
И ViewSet
class CustomUserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = CustomUserSerializer
@action(methods=['get'], detail=True)
def get_user(self, request, pk=None):
try:
if pk:
user = self.get_object()
serializer = CustomUserSerializer(user)
return Response(serializer.data, status=status.HTTP_200_OK)
except:
raise Http404('Страница не найдена')
users = self.get_queryset()
pagination = CustomPagination()
result_page = pagination.paginate_queryset(users, request)
serializer = CustomUserSerializer(result_page, many=True)
return Response(pagination.get_paginated_response(serializer.data),
status=status.HTTP_200_OK)
@action(methods=['post'], detail=True,
permission_classes=[permissions.AllowAny])
def create_user(self, request):
serializer = CustomCreateUserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(
serializer.data,
status=status.HTTP_201_CREATED)
else:
errors = serializer.errors
return Response(
errors,
status=status.HTTP_400_BAD_REQUEST)