Django管理员无法使用自定义用户模型正确登录

时间:2013-03-03 01:15:07

标签: django django-admin django-1.5

我将Django 1.4.5上的应用程序升级到Django 1.5,刚刚完成迁移到自定义用户模型。当我使用我自己的身份验证表单和我的超级用户凭据(在执行manage.py syncdb时创建)登录到我的应用程序时,一切正常。

我可以通过身份验证,如果我转到/admin,我已经按预期登录了。我能够完美地导航和使用管理面板。但是,如果我尝试使用django管理员登录表单从/admin登录管理面板,则会收到错误消息:

  

请输入员工帐户的正确电子邮件和密码。注意   这两个字段可能区分大小写。

我做了一些调查,并认为它可能与ModelAdmin有关,所以我从文档中跟踪this example并创建了自定义ModelAdmin。但问题仍然存在。

任何可能导致此问题的想法?

3 个答案:

答案 0 :(得分:4)

您是否在create_superuser下的BaseUserManager函数中添加了以下行?它可能看起来像这样:

class CustomUserManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        if not username:
            raise ValueError('Dude you need a username.')
        if not email:
            raise ValueError(
                'type an e-mail..')

        new_user = self.model(
            username=username,
            email=CustomUserManager.normalize_email(email))
        new_user.set_password(password)
        new_user.save(using=self._db)
        return new_user

  def create_superuser(self, username, email, password):
        new = self.create_user(
            username,
            email,
            password=password
        )
        new.is_active = True
        new.is_staff = True
        new.is_superuser = True
        new.save(using=self._db)
        return new

专注于:

    new.is_active = True
    new.is_staff = True
    new.is_superuser = True

答案 1 :(得分:0)

我遇到了同样的问题,但是我发现@alix的答案非常有帮助。我忘记添加is_active=True on create_superuser()

def create_staffuser(self, email, first_name=None, last_name=None, user_role=None, password=None):
    user = self.create_user(
        email,
        first_name=first_name,
        last_name=last_name,
        user_role=user_role,
        password=password,
        is_staff=True,
        is_active=True
    )
    return user

因此,基本上,您需要专注于is_active并检查

# changes the in-build User model to ours (Custom)
AUTH_USER_MODEL = 'accounts.User'

AUTHENTICATION_BACKENDS = (
    # Needed to login by custom User model, regardless of `allauth`
    "django.contrib.auth.backends.ModelBackend",

    # `allauth` specific authentication methods, such as login by e-mail
    "allauth.account.auth_backends.AuthenticationBackend",
)

答案 2 :(得分:0)

是的,这部分做到了。感谢您对这些@gregoltsov 的指点

obj.is_active = True
obj.is_staff = True
obj.is_admin = True

我缺少的是 obj.is_active 部分。