Django应用程序我使用的是Django-restframework。我试着创建一个用户,这个用户必须输入两次密码。但是如果我做了一个帖子,在我填写了数据之后:
{
"email": "user@example.com",
"username": "string",
"password": "string",
"password2": "string"
}
然后我得到这个错误:
TypeError at /api/user/create/
MyAccountManager.create_user() got an unexpected keyword argument 'password2'
这就是我的create方法:
from django.contrib.auth import (get_user_model, authenticate)
from rest_framework import serializers
from django.utils.translation import gettext as _
class AccountSerializer(serializers.ModelSerializer):
"""Serializer for the account object"""
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = get_user_model()
fields=['email', 'username', 'password','password2' ]
extra_kwargs = {'password': {'write_only': True, 'min_length':5}}
def create(self, validated_data):
"""Create user"""
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError( {'error': 'P1 and P2 are not the same'})
return get_user_model().objects.create_user(**validated_data)
这是它的样子
class CreateUserView(generics.CreateAPIView):
"""_summary_:Create a new user in the system
Args:
generics (_type_): _description_
"""
serializer_class = AccountSerializer
问:如何解决这个问题?
我现在就像:
class AccountSerializer(serializers.ModelSerializer):
"""Serializer for the account object"""
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = get_user_model()
fields=['email', 'username', 'password','password2' ]
extra_kwargs = {'password': {'write_only': True, 'min_length':5}}
def create(self, validated_data):
"""Create user"""
password = self.validated_data['password']
if password != self.validated_data.pop('password2'):
raise serializers.ValidationError( {'error': 'P1 and P2 are not the same'})
return get_user_model().objects.create_user(**validated_data)
但我仍然得到这个错误:
TypeError at /api/user/create/
MyAccountManager.create_user() got an unexpected keyword argument 'password2'
1条答案
按热度按时间js81xvg61#
您的
MyAccountManager.create_user
没有password2
参数,您应该在AccountSerializer.create
中检查它是否等于pwd1后,将其添加到validated_data
中。或者更整洁: