模型中的字段名`username`无效

8
我正在尝试使用rest-auth提供的序列化程序通过定义的endpoint /rest-auth/user/ GET(*带标头)获取用户详细信息。
(*带标头 (Content-Type:application / json 授权:Token 1a5472b2af03fc0e9de31fc0fc6dd81583087523 ))
我得到了以下回溯:https://dpaste.de/oYay#L 我已经定义了自定义用户模型(使用电子邮件而不是用户名),如下所示:
class UserManager(BaseUserManager):
def create_user(self, email, password, **kwargs):
    user = self.model(
        # lower-cases the host name of the email address
        # (everything right of the @) to avoid case clashes
        email=self.normalize_email(email),
        is_active=True,
        **kwargs
    )
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuser(self, email, password, **kwargs):
    user = self.model(
        email=email,
        is_staff=True,
        is_superuser=True,
        is_active=True,
        **kwargs
    )
    user.set_password(password)
    user.save(using=self._db)
    return user


class MyUser(AbstractBaseUser, PermissionsMixin):
    USERNAME_FIELD = 'email'

    email = models.EmailField(unique=True)

设置如下:

AUTH_USER_MODEL = 'users.MyUser'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
# Config to make the registration email only
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_VERIFICATION = 'optional'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

我不确定如何纠正这个错误,使它符合rest-auth序列化器的要求。

1个回答

14
在 Django-rest-auth 中,有一个默认的用户模型序列化器:
    USER_DETAILS_SERIALIZER = 'rest_auth.views.UserDetailsView' 

这里它们正在序列化 django.contrib.auth.User

在您的情况下,您正在使用自定义用户模型,并且在您的模型中没有用户名字段,因此在尝试序列化用户名字段时会出现错误。 因此,您需要为您的用户模型编写一个序列化程序,并将其路径添加到您的设置中:

例如:

    class CustomUserDetailsSerializer(serializers.ModelSerializer):

        class Meta:
            model = MyUser
            fields = ('email',)
            read_only_fields = ('email',)

在 settings.py 文件中

    USER_DETAILS_SERIALIZER = CustomUserDetailsSerializer 

12
这个解决方案对我很有效,只需改进一些细节以便日后参考: 在settings.py中使用以下代码:REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.CustomUserDetailsSerializer' } - Anon957

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接