【问题标题】:Field name `username` is not valid for model字段名称“用户名”对模型无效
【发布时间】:2016-03-06 10:26:58
【问题描述】:

我正在尝试使用 rest-auth 提供的序列化程序从定义的 endpoint /rest-auth/user/ 获取(*带有标头)用户详细信息

(*带标题 (内容类型:应用程序/json 授权:令牌 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 序列化程序。

【问题讨论】:

    标签: python django django-rest-framework django-allauth django-rest-auth


    【解决方案1】:

    在 django-rest-auth 中,有一个用于用户模型的默认序列化程序:

        USER_DETAILS_SERIALIZER = 'rest_auth.views.UserDetailsView' 
    

    他们正在序列化django.contrib.auth.User

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

    示例:

        class CustomUserDetailsSerializer(serializers.ModelSerializer):
    
            class Meta:
                model = MyUser
                fields = ('email',)
                read_only_fields = ('email',)
    

    在settings.py中

        USER_DETAILS_SERIALIZER = CustomUserDetailsSerializer 
    

    【讨论】:

    • 这个解决方案对我来说很好,只是一个细节来改进答案以供将来参考:在 settings.py 中使用如下代码:REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER':'users.serializers.CustomUserDetailsSerializer' }
    猜你喜欢
    • 2020-01-12
    • 2018-03-11
    • 2015-02-01
    • 2020-08-16
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2011-10-07
    相关资源
    最近更新 更多