'is_superuser' is an invalid keyword argument for this function - django

I used Django restframework.
To implement customize user model, I use AbstractBaseUser.
models.py code is below.
[models.py]
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, username, email, password, is_staff, is_admin, is_active, is_superuser, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('Username must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=is_staff, is_admin=is_admin,
is_active=is_active, is_superuser=is_superuser,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(self._db)
return user
def create_user(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, False, False, True, False, **extra_fields)
def create_superuser(self, username, email, password, **extra_fields):
return self._create_user(username, email, password, True, True, True, True, **extra_fields)
class User(AbstractBaseUser):
USER_TYPE_CHOICES = (
('django', 'Django'),
('facebook', 'Facebook'),
('google', 'Google')
)
user_type = models.CharField(
max_length=20,
choices=USER_TYPE_CHOICES,
default='Django'
)
email = models.CharField(max_length=100, null=False)
username = models.CharField(max_length=20, unique=True)
phone = models.CharField(max_length=12)
# Default Permission
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'username'
objects = UserManager()
REQUIRED_FIELDS = ['email']
def get_full_name(self):
pass
def get_short_name(self):
pass
#property
def is_superuser(self):
return self.is_admin
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
#is_staff.setter
def is_staff(self, value):
self._is_staff = value
When I create super user,
It throws TypeError: 'is_superuser' is an invalid keyword argument for this function
Maybe I think there is no function related is_superuser in my code, but I don't know exactly what I have to do.
Is there any solution about this?
Thanks.

Looks like is_superuser field overrided by property with same name. You should rename is_superuser property to fix error:
#property
def is_superuser_property(self):
return self.is_admin

Related

How can i make a custom user model in django without using username field?

I am working on building a project and for this, i need to create a custom user model, since the one that Django comes with isn't suitable for my situation, so whenever i use the AbstractBaseUser, I am forced to use the username field, which i really don't need in my case. how can I create a custom user model without using the username field and thank you
After many attempts, i finally could fix it by overiding it in the accountmanager
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
import uuid
class MyAccountManager(BaseUserManager):
def _create_user(self, email, first_name, last_name, password=None):
if not email:
raise ValueError("Users must have an email address")
if not first_name:
raise ValueError("Users must have an userusername")
if not last_name:
raise ValueError("Users must have an userusername")
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email,first_name, last_name, password):
user = self._create_user(
email=self.normalize_email(email),
password=password,
first_name= first_name,
last_name=last_name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.is_active = True
user.save(using=self._db)
return user
def verifyAccount(self, user, user_input, code):
if user_input == code:
user.is_active = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True

'User' object has no attribute 'get_all_permissions'

What is the cause of this error? I got this error after changing the
admin style 'User' object has no attribute 'get_all_permissions' plz help me. (What is the cause of this error? I got this error after changing the
admin style 'User' object has no attribute 'get_all_permissions' plz help me. )
class UserManager(BaseUserManager):
def create_user(self, email, username, full_name, phone, password):
if not email:
raise ValueError('plz input email')
if not username:
raise ValueError('plz input username')
if not full_name:
raise ValueError('plz input full_name')
if not phone:
raise ValueError('plz input phone')
user = self.model(email=self.normalize_email(email), username=username, full_name=full_name, phone=phone)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, full_name, phone, password):
user = self.create_user(email, username, full_name, phone, password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=50, unique=True)
username = models.CharField(max_length=100, null=True, blank=True, unique=True)
full_name = models.CharField(max_length=300)
phone = models.CharField(max_length=15)
address = models.CharField(max_length=500)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
permission = models.ManyToManyField(Permission, related_name='users')
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'full_name', 'phone']
objects = UserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_superuser
def has_module_perms(self, app_label):
return self.is_superuser
#property
def is_staff(self):
return self.is_admin
Add these codes to your model.py
Import PermissionsMixin from Django contrib Auth
from django.contrib.auth.models import PermissionsMixin
Then change
class Account(AbstractBaseUser):
to
class Account(AbstractBaseUser, PermissionsMixin):
Then it will work fine
Instead of returning self.is_superuser,
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
will work I hope. :-) It's been one and half a year.

parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object

I have the error with this models.py ?
This replace built-in User model.
Errors are detected in line user_obj.save(using=self._db) in def UserManager
and in line def create_superuser user = self.create_user(
email,
last_name=last_name,
first_name=first_name,
password=password,
)
It seems like it does not like my timestamp attribute with date value ?
thanks
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserManager(BaseUserManager):
def create_user(self, email, last_name, first_name, password=None, is_active=True, is_staff=False, is_admin=False):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
if not password:
raise ValueError('Users must have a password')
user_obj = self.model(
email=self.normalize_email(email),
)
user_obj.set_password(password) # change user password
user_obj.first_name = first_name
user_obj.last_name = last_name
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, email, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email,last_name, first_name, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
last_name=last_name,
first_name=first_name,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=255, blank=False, null=False)
last_name = models.CharField(max_length=255, blank=False, null=False)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
timestamp = models.DateTimeField(default=timezone.now)
confirmedEmail = models.BooleanField(default=False) # Check if user is valid
confirmedDate = models.DateTimeField(default=False) # Check if user is valid
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name'] # Email & Password are required by default.
def get_full_name(self):
# The user is identified by their email address
return "%s %s" % (self.first_name, self.last_name)
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
#property
def is_admin(self):
"Is the user a admin member?"
return self.admin
#property
def is_active(self):
"Is the user active?"
return self.active
objects = UserManager()
I find the issue.
confirmedDate = models.DateTimeField(default=False)
It cannot be default= false as it is a datefield. Good answer is:
confirmedDate = models.DateTimeField(null=True, blank=True)

Attribute error: 'User' object has no attribute 'is_admin'

I have customized user model by extending AbstractBaseUser, the user name only accepted as email id. Here is the model:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True)
first_name = models.CharField('first name', max_length=30, blank=True)
last_name = models.CharField('last name', max_length=30, blank=True)
date_joined = models.DateTimeField('date joined', auto_now_add=True)
is_active = models.BooleanField('active', default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
The model manager for the above model is:
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
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)
I am able to create the custom user but when I am trying to log in I got the attribute error:
Attribute error: 'User' object has no attribute 'is_admin'
Below is the admin.py file
class ProfileInline(admin.StackedInline):
model = Course
can_delete = False
verbose_name_plural = 'Course'
fk_name = 'user'
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)
admin.site.register(User, CustomUserAdmin)
Django user models don't have the attribute is_admin.
The error is shown because somewhere in your code (probably login view?) you are calling user.is_admin. Find it and remove it, or use user.is_staff / user.is_superuser instead.

'Manager' object has no attribute 'get_by_natural_key'

I know there are similar questions like this, and I tried every solution that is adressed in those questions. Here is my problem described;
When I execute createsuperuser, I got an error as follows;
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'
Here is how I define UserAccountManager and UserAccount in my implementation;
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class UserAccountManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
if not email:
raise ValueError('Email must be set!')
user = self.model(email=email, first_name=first_name, last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password):
user = self.create_user(email, first_name, last_name, password)
user.is_admin = True
user.save(using=self._db)
return user
def get_by_natural_key(self, email_):
return self.get(code_number=email_)
class UserAccount(AbstractBaseUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
is_active = models.BooleanField(default=True) # default=False when you are going to implement Activation Mail
is_admin = models.BooleanField(default=False)
objects = UserAccountManager
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_short_name(self):
return self.email
def get_full_name(self):
return self.email
def has_perms(self, perm, ob=None):
return True
def has_module_perms(self, app_label):
return True
def natural_key(self):
return self.email
#property
def is_staff(self):
self.is_admin
I set object as follows in UserAccount class : objects = UserAccountManager
What do I do wrong?
Edit (to address Iain Shelvington's solution):
in settings.py, I have this line;
AUTH_USER_MODEL = 'accounts.UserAccount'
It should be objects = UserAccountManager()
https://docs.djangoproject.com/en/1.10/topics/db/managers/#custom-managers-and-model-inheritance
You need to change the setting AUTH_USER_MODEL to 'your_app.UserAccount'