问题
Trying to set up a custom user model that extends the base user. Some user will have login information and some will not, but I still want all users logged. That's what I think the error is saying.
In the default Django model they were logged, but now some users will just have just IP address and username. Other users will have more information like email, etc.
Gettin this error:
AttributeError: 'CustomUser' object has no attribute 'is_anonymous'
Here is my custom user class:
class MyUserManager(BaseUserManager):
def create_user(first_name, last_name, address1, state, zipcode, email, username, password):
user=self.model(
first_name = first_name,
last_name = last_name,
address1 = address1,
zipcode = zipcode,
state = state,
email=email,
username = username,
password = password
)
user.is_superuser = False
user.is_admin = False
user.is_staff = False
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, 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(email, password, **extra_fields)
class CustomUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=25
)
last_name = models.CharField(max_length=25
)
address1 = models.CharField(null=True, max_length=100, blank=True)
zipcode = models.CharField(max_length=10, null=True,blank=True)
state = models.CharField(null=True, max_length=2, blank=True)
email = models.EmailField(max_length = 250)
username = models.CharField(max_length = 25)
password = models.CharField(max_length =25,
null=True)
objects=MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name', 'username', 'email', 'password', 'zipcode']
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
def __str__(self):
return f'{self.first_name} ({self.last_name}) ({self.email})'
How might I get this to work? Any help would be great!
回答1:
Your CustomUser class must inherits from AbstractBaseUser too. You didn't include it in your code. First you must do :
from django.contrib.auth.models import AbstractBaseUser
And then
class CustomUser(models.Model,AbstractBaseUser):
###
来源:https://stackoverflow.com/questions/57446355/custom-user-model-error-attributeerror-customuser-object-has-no-attribute-i