Django使用替代的Auth模型抛出操作错误

pdtvr36n  于 2023-11-20  发布在  Go
关注(0)|答案(2)|浏览(149)

如果这是一个重复的问题,请提前道歉。2尽我所能,我无法找到这个问题。
使用Django 2.0,我用自己的Users模型替换了内置的django.contrib.auth,并使用AbstractUser对其进行了扩展。Users模型依赖于MySQL中的一个现有表,该表被配置为与Django一起使用。Django在执行检查时没有检测到任何问题;但是,我收到了以下错误:

OperationalError at / (1054, "Unknown column 'users.last_login' in 'field list'")

字符串
我将该列添加到表中,以为这将是一个有用的字段,但担心因为我认为我会得到另一个错误的另一个丢失的字段。

OperationalError at / (1054, "Unknown column 'users.is_superuser' in 'field list'")


替换用户模型的目的是让我可以丢弃不重要的字段,比如“username”。我只需要将每一列添加到表中,直到我得到表中的所有auth字段,还是我做了一些根本性的错误?
TL;DR:如何使用现有的表为Django创建自定义身份验证方法?

iqih9akk

iqih9akk1#

正如你所说的,你会得到这些错误,因为你的表没有AbstractUser模型中定义的字段的列。最简单的解决方案是将所有缺失的字段添加到你的表中。
或者,如果你想避免这种情况,你可以让你的用户模型子类AbstractBaseUser代替。这个抽象模型只有passwordlast_login的字段。注意,这种方法会有更多的工作。这似乎是一个很好的指南:
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

r8xiu3jd

r8xiu3jd2#

"I have fixed this problem after a lot of tries. Just pass AbstractBaseUser in the class CustomUser(AbstractBaseUser) and don't include PermissionsMixin in the parameters and for the extra column which are not matching include last_login = None and the CustomUser model will run as expected. 
Adding the code for reference. "

from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
import re
from django.utils import timezone
from django.core.mail import send_mail
# from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, loginId, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not loginId:
            raise ValueError('The given email must be set')
        # email = self.normalize_email(email)
        user = self.model(loginId=loginId, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, loginId, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(loginId, password, **extra_fields)

    def create_superuser(self, loginId, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(loginId, password, **extra_fields)

class CustomUser(AbstractBaseUser):
    userId = models.AutoField(primary_key=True)
    loginId = models.IntegerField(unique=True)
    password = models.CharField(max_length=128)
    userType = models.CharField(
        max_length=1,
        choices=[
            ('0', 'walmart'),
            ('1', 'partner'),
            ('2', 'forecaster'),
            ('3', 'supervisor'),
        ],
        default='0'
    )
    firstName = models.CharField(max_length=60, null=False)
    lastName = models.CharField(max_length=60, null=False)
    emailId = models.CharField(max_length=120, blank=True, null=True)
    location = models.CharField(max_length=80)
    lobId = models.IntegerField(blank=True, null=True)
    channelId = models.IntegerField(blank=True, null=True)
    createdDate = models.DateTimeField(auto_now_add=True)
    lastLoginDate = models.DateTimeField(blank=True, null=True)
    lastLoginIp = models.CharField(max_length=15, blank=True, null=True)
    status = models.CharField(
        max_length=1,
        choices=[
            ('0', 'inactive'),
            ('1', 'active'),
            ('2', 'deleted'),
        ]
    )
    last_login = None
    objects = UserManager()

    USERNAME_FIELD = 'loginId'
    REQUIRED_FIELDS = []

    class Meta:
        managed = False
        db_table = 'rpt_admin'

    def __str__(self):
        return str(self.loginId)  

    def __int__(self):
        return int(self.userType)

字符串

相关问题