【发布时间】:2020-08-20 09:22:17
【问题描述】:
我想将password 字段和confirm_password 字段添加到我的UserSerializer。我编写了一个名为create 的函数来为我的password 字段创建哈希密码,但在它创建哈希密码之前,我希望它确保confirm_password 和password 匹配。如果我删除 confirm_password 字段,代码可以正常工作。有什么问题?
[更新]
我的序列化器.py
# serializer define the API representation
class UserSerializer(serializers.HyperlinkedModelSerializer):
# password field
password = serializers.CharField(
write_only = True,
required = True,
help_text = 'Enter password',
style = {'input_type': 'password'}
)
# confirm password field
confirm_password = serializers.CharField(
write_only = True,
required = True,
help_text = 'Enter confirm password',
style = {'input_type': 'password'}
)
class Meta:
model = User
fields = [
'url', 'first_name', 'last_name', 'email',
'password', 'confirm_password', 'is_staff'
]
def create(self, validated_data):
if validated_data.get('password') != validated_data.get('confirm_password'):
raise serializers.ValidationError("Those password don't match")
elif validated_data.get('password') == validated_data.get('confirm_password'):
validated_data['password'] = make_password(
validated_data.get('password')
)
return super(UserSerializer, self).create(validated_data)
我遇到的错误
TypeError: User() got an unexpected keyword argument 'confirm_password'
[20/Aug/2020 16:15:44] "POST /users/ HTTP/1.1" 500 168152
浏览器出错
TypeError at /users/
Got a `TypeError` when calling `User.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `User.objects.create()`. You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly.
如果您需要更多详细信息,我可以编辑问题。太棒了!
【问题讨论】:
标签: python django django-rest-framework