无法使用djoser自定义用户注册



我一直使用djoser与django处理注册和登录。我没有问题配置默认注册字段(用户名,电子邮件,密码和re_password)。但是现在我想自定义寄存器字段并添加genderhobby。但是,当我尝试使用这些附加字段注册另一个用户时,我一直得到以下错误默认不提供。

user = User.objects.create_user(**validated_data)
TypeError: UserManager.create_user() missing 2 required positional arguments: 'gender', 'hobby'

错误来自models.py文件中用于创建新用户的函数,如下所示:

class UserManager(BaseUserManager):
def create_user(self, username, email, gender, hobby, password=None, **extra_fields):
if username is None:
raise ValueError(_('Username is required'))
if email is None:
raise ValueError(_('Enter a functional email address'))
if gender is None:
raise ValueError(_('Provide your gender'))
if hobby is None:
raise ValueError(_('Enter hobby'))

user = self.model(email=self.normalize_email(email) **extra_fields)
user.username=username  
user.gender=gender, 
user.hobby=hobby
user.set_password(password)
user.save()
return user
def create_superuser(self,username, email, gender, hobby, password=None):
if password is None:
raise ValueError(_('Please enter your password'))
user = self.create_user(email=self.normalize_email(email))
user.username=username 
user.gender=gender, 
user.hobby=hobby
user.is_superuser = True
user.is_staff = True
user.save()
return user

class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=25, unique=True, default='')
email = models.EmailField(max_length=255, unique=True)
gender = models.CharField(max_length=50, null=True, blank=True)
hooby = models.CharField(max_length=50, null=True, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

def __str__(self):
return self.username

serializers.py


class UserCreateSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
model = User
fields = (
'id', 
'username', 'email',
'gender', 'hobby',
'password'
)

settings.py

djoser = {
'SERIALIZERS': {
'user_create': 'accounts.serializers.UserCreateSerializer',
'user': 'accounts.serializers.UserCreateSerializer',
'current_user': 'accounts.serializers.UserCreateSerializer',
'user_delete': 'djoser.serializers.UserDeleteSerializer',
}
}

我已经通过了代码几次,我仍然找不到为什么我得到错误

我也遇到了同样的问题。将字段添加到User模型中的REQUIRED_FIELDS中,问题就解决了。只需将性别和爱好添加到REQUIRED_FIELDS

一个问题是你肯定有" hooby"作为字段

相关内容

  • 没有找到相关文章

最新更新