Django Rest Framework-为默认的用户模型验证提供序列化程序,以模仿默认验证 [英] Django Rest Framework - Give Serializer of default User model validations that mimic the default validations
问题描述
我目前正在制作一个REST API,人们可以通过其注册自己.而且我将要编写验证密码的有效期等/长短等信息.当我想到时,也许有一种方法可以模仿模型已经设置的默认约束?有吗?
I am currently making a REST API that people can register themselves via. And I am just about to write the validations for how long/complex passwords should be etc. when it occurred to me there maybe is a way to mimic the default constraints that the model have set already? Is there?
我的serializer.py代码如下:
My code for serializer.py looks like the following:
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework.reverse import reverse
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
links = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password', 'groups', 'user_permissions', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'links')
def get_links(self, obj):
request = self.context['request']
username = obj.get_username()
return{
'self': reverse('user-detail', kwargs={User.USERNAME_FIELD: username}, request=request)
}
def validate(self, attrs):
#...
谢谢
推荐答案
You can enable Django password validation with AUTH_PASSWORD_VALIDATORS
setting.
But
验证者不在模型级别应用,例如在User.objects.create_user()和create_superuser()中.
Validators aren’t applied at the model level, for example in User.objects.create_user() and create_superuser().
因此您需要向序列化器添加验证:
So you need to add validation to the serializer:
from django.contrib.auth.password_validation import validate_password
def validate_password(self, value):
user = self.context['request'].user
validate_password(password=value, user=user)
这篇关于Django Rest Framework-为默认的用户模型验证提供序列化程序,以模仿默认验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!