python - 字段名称 `username` 对模型无效

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

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

(*带标题 (内容类型: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 序列化程序。

最佳答案

在 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 

关于python - 字段名称 `username` 对模型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34038355/

相关文章:

python - 如何在单个 catplot 图中绘制多个数据帧

python - PyFacebook 无限 session

javascript - 在 Cesium 查看器/ map 上覆盖一个工具栏

javascript - Django 中非常非常基本的 JavaScript 按钮

django - 使用序列化程序 Django (DRF) 创建对象

python - 我将 python 社交身份验证与 django 结合使用。我无法断开与 Steam 的连接

python - Django:即使不在 settings.py 中,APPEND_SLASH 是否设置为 True?

python - Django Rest Framework——如何获取urls.py中的Http头信息

Django Rest Framework覆盖modelserialzer中的模型字段

python - ScrapyRT 与 Scrapyd