gpt4 book ai didi

django-rest-auth 错误 - save() 采用 1 个位置参数,但给出了 2 个

转载 作者:行者123 更新时间:2023-12-04 14:23:11 26 4
gpt4 key购买 nike

我将 django-rest-auth 与自定义用户模型、注册 View 和序列化程序一起使用。我想要实现的是电子邮件登录而不是用户名。 api View 显示正确,但是当我发布时,出现错误:

TypeError at /rest-auth/registration/
save() takes 1 positional argument but 2 were given

这是追溯:http://dpaste.com/2FR3DZY

序列化器.py

class CustomUserSerializer(serializers.ModelSerializer):
"""Serializer for User objects."""

class Meta:
model = models.User
fields = ('id', 'email', 'name', 'password')
extra_kwargs ={'password': {'write_only': True}}

def create(self, validated_data):
"""Create and return a new User."""

user = models.User(
email=validated_data['email'],
name=validated_data['name']
)

user.set_password(validated_data['password'])
user.save()

return user

View .py

class CustomRegistrationsView(RegisterView):
serializer_class = CustomUserSerializer

网址.py

path('rest-auth/registration/', CustomRegistrationsView.as_view(), name='rest_register'),   
path('rest-auth/', include('rest_auth.urls')),

模型.py

class UserManager(BaseUserManager):
"""Helps Django work with our custom user model."""

def create_user(self, email, name, password=None):
"""Creates a new user object."""

if not email:
raise ValueError('Users must have an email address.')

email = self.normalize_email(email)
user = self.model(email=email, name=name)

user.set_password(password)
user.save(using=self._db)

return user

def create_superuser(self, email, name, password):
"""Creates and saves a new superuser with given details."""

user = self.create_user(email, name, password)

user.is_superuser = True
user.is_staff = True

user.save(using=self._db)

return user

class User(AbstractBaseUser, PermissionsMixin):
"""Represents a "user" inside our system."""

email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']

def get_full_name(self):
"""Used to get a users full name."""

return self.name

def get_short_name(self):
"""Used to get a users short name."""

return self.name

def __str__(self):
"""Django uses this when it needs to convert the object to a string"""

return self.email

谁能给个建议?

最佳答案

因为您的自定义注册 View 继承自 RegisterViewRegisterView 中定义的perform_create 方法将使用基于请求对象的请求对象调用序列化程序的保存方法implementation由于您的序列化程序继承自 ModelSerializer,因此保存方法不采用任何位置参数,因此会出现错误。

CustomUserSerializer 需要定义一个将请求对象作为参数的保存方法。在下面勾选此免除 django-rest-auth configuration

The custom REGISTER_SERIALIZER must define a def save(self, request) method that returns a user model instance.

我建议您查看 implementation默认的 REGISTER_SERIALIZER 将指导您的自定义序列化程序的外观。

关于django-rest-auth 错误 - save() 采用 1 个位置参数,但给出了 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com