我对 django 很陌生,我正在使用 djoser 创建用户。我有自定义用户模型和自定义用户序列化器。我的自定义用户正在关注。
class User(AbstractBaseUser, PermissionsMixin):
"""
A fully featured User model with admin-compliant permissions that uses
a full-length email field as the username.
Email and password are required. Other fields are optional.
"""
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
middle_name = models.CharField(_('middle name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
extra_field = models.BooleanField(_('changethis'), default=False,
help_text=_('Describes whether the user is changethis '
'site.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
username = models.CharField(_('username'), max_length=30, blank=True)
roles = models.ManyToManyField(Role, related_name='role_user')
objects = CustomUserManager()
以下是我的 CustomUserManager()
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
**extra_fields)
以下是我的序列化程序代码。
class RegisterSerializer(serializers.Serializer):
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
first_name = serializers.CharField(required=True)
middle_name = serializers.CharField(required=False)
last_name = serializers.CharField(required=True)
password = serializers.CharField(required=True, write_only=True)
roles = serializers.ListSerializer(child=serializers.IntegerField())
# def create(self, validated_data):
def create(self, validated_data):
roles_ids = validated_data.pop('roles')
roles = Role.objects.filter(id__in=roles_ids)
user = User.objects.create_user(**validated_data)
user.roles.set(roles)
return user
由于角色对象已经创建,所以我只需从请求中获取角色 id 列表并过滤这些角色对象并为各自的用户设置它们。现在用户创建得很好,但是当 djoser 尝试使用相同的序列化程序返回响应时,它会引发以下异常。
TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“角色”
因为角色应该是整数列表而不是角色对象列表。我该如何解决?