登录Django的管理员

时间:2016-07-06 09:27:05

标签: python django authentication django-admin

我很感激自定义用户模块的帮助。我在django documentation中将其设置为此示例。我有以下问题:

  1. 登录管理界面不起作用。登录页面显示,但在shell中创建具有./manage createsuperuser的用户后,不接受我的凭据。
  2. 创建超级用户时,它会以明文形式保存密码。我查看了数据库,并以明文形式找到了密码。我想这来自create_superuser(),其中不使用user.set_password()但密码=密码(如django docs中的示例,那么为什么他们会这样做?)。我在shell中更改了它然后它被加密了。登录仍然无法正常工作。
  3. 我的代码如下: 认证/ models.py

    class UserManager(BaseUserManager):
    
    def create_user(self, email, password=None, **kwargs):
    
        if not email:
            raise ValueError('Users must have an email address')
    
        user = self.model(
            email=self.normalize_email(email),
            **kwargs
        )
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, email, password, **kwargs):
        user = self.model(
            email,
            password=password,
            **kwargs
        )
        user.is_admin=True
        user.save(using=self._db)
        return user
    

    class MyUser(AbstractBaseUser):
    # use this for auth and sessions
    # REQUIRED_FIELDS = ['password']
    
    session = models.ForeignKey(
        'sessions.Session',
        verbose_name='Session',
        blank=True, null=True,
    )
    email = models.EmailField(unique=True, primary_key=True)
    #password = forms.CharField(max_length=30, widget=forms.PasswordInput()) #render_value=False
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    signed_up_since = models.DateTimeField('Signed up since', default=timezone.now())
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    
    objects = UserManager()
    USERNAME_FIELD = 'email'
    
    def __str__(self):
        return self.email
    
    def get_full_name(self):
        return self.email
    
    def get_short_name(self):
        return self.email
    
    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
    

    我编辑了设置:

    AUTH_USER_MODEL = "authentication.MyUser"
    

    我不使用自定义会话后端或身份验证后端,进行了迁移,sqlmigrations等.Shell给了我这个:

    >>> user.is_staff
    True
    

    有什么想法吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

问题是您是在self.model()方法中使用create_user创建用户的。这导致密码保存为纯文本。

您应该使用create_user方法,如example in the docs中所示。这将正确散列密码。

def create_superuser(self, email, password, **kwargs):
    user = self.create_user(
        email,
        password=password,
        **kwargs
    )
相关问题