Django自定义用户模型重命名用户名colum

时间:2017-07-30 12:00:55

标签: django

我正在尝试实现自定义Django用户模型。以下是我的用户模型。我的问题是,在我的应用程序中,我使用电子邮件字段作为用户名。但它不能像我使用模型时那样工作,我得到以下错误。 "Unknown column 'users.username' in 'field list'"

class usersManager(BaseUserManager):
    pass


def myoverridenmeta(name, bases, adict):
    newClass = type(name, bases, adict)
    for field in newClass._meta.fields:
        if field.attname == 'last_login':
            field.column = 'lastlogin'
            field.db_column = 'lastlogin'
    return newClass


class users(AbstractUser):
    REQUIRED_FIELDS = ('ID', 'emal', 'password', 'salt', 'subscriptionID')
    USERNAME_FIELD = 'email'
    is_anonymous = False
    is_authenticated = True

    ID = models.AutoField(primary_key=True)
    email = models.CharField(max_length=254, unique=True)
    password = models.CharField(max_length=64)
    salt = models.CharField(max_length=32)
    lang = models.CharField(max_length=2, default='EN')
    regDate = models.DateField(auto_now_add=True)
    orgID = models.PositiveIntegerField(default=0)
    subscriptionID = models.CharField(max_length=18)
    activated = models.BooleanField(default=0)
    orgConfirmed = models.BooleanField(default=0)
    deleted = models.BooleanField(default=0)
    lastLogin = models.DateTimeField()

    objects = usersManager()

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'
        db_table = 'users'

    def __str__(self):
        return self.email

    def get_short_name(self):
        return self.email

def get_full_name(self):
    return self.email

__metaclass__ = myoverridenmeta

该模型用于Django中的自定义身份验证。以下是我的自定义身份验证类。

class AuthenticationBackend:

    # Create an authentication method
    # This is called by the standard Django login procedure
    def authenticate(self, username=None, password=None):
        try:
            # Try to find a user matching your username
            user = users.objects.get(email=username)

            #  Check the password
            if user.password == hashlib.sha256(password + user.salt).hexdigest():
                return user
            else:
                return None
        except users.DoesNotExist:
            # No user was found, return None - triggers default login failed
            return None

    # Required for your backend to work properly - unchanged in most scenarios
    def get_user(self, user_id):
        try:
            return users.objects.get(pk=user_id)
        except users.DoesNotExist:
            return None

0 个答案:

没有答案