django 创建新用户,MyAccountManager.create_user()获得了意外的关键字参数

7vux5j2d  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(104)

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'
js81xvg6

js81xvg61#

您的MyAccountManager.create_user没有password2参数,您应该在AccountSerializer.create中检查它是否等于pwd1后,将其添加到validated_data中。

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'})  
 
        self.validated_data.pop('password2')  # throw away the pwd2

       return get_user_model().objects.create_user(**validated_data)

或者更整洁:

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)

相关问题