'Manager' object has no attribute 'get_by_natural_key' - django

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'

Related

'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)

Creating superuser in django

I modified the user model as shown below, to make users log in via phone.
from django.db import models
import datetime
from django.core.mail import send_mail
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.validators import RegexValidator
class UserManager(BaseUserManager):
def get_by_natural_key(self, username):
case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
return self.get(**{case_insensitive_username_field: username})
def create_user(self,phone_number,password=None,is_staff=False,is_active = True, is_admin = False, is_vendor = False):
if not phone_number:
raise ValueError("Users Must Have a phone number")
if not password:
raise ValueError("Users must have a password")
user = self.model(
phone_number )
user.set_password(password)
user.is_staff = is_staff
user.is_active = is_active
user.is_admin = is_admin
user.is_vendor = is_vendor
user.save(using=self._db)
return user
def create_staffuser(self,phone_number, password=None):
user = self.create_user(
phone_number,
password=password,
is_staff=True
)
return user
def create_superuser(self,phone_number, password=None):
user = self.create_user(
phone_number,
password=password,
is_admin=True,
is_staff=True
)
return user
def create_vendoruser(self,phone_number, password=None):
user = self.create_user(
phone_number,
password=password,
is_vendor=True
)
return user
class User(AbstractBaseUser):
phone_number = models.CharField(max_length=20, unique=True)
date_joined = models.DateField(auto_now_add = True)
is_active = models.BooleanField(default = True)
is_staff = models.BooleanField(default = False)
is_admin = models.BooleanField(default = False)
is_vendor = models.BooleanField(default = False)
is_basic = models.BooleanField(default = False)
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.phone_number
# def save(self, *args, **kwargs):
# self.email = self.email.lower()
# return super(User, self).save(*args, **kwargs)
def get_full_name(self):
return self.phone_number
def get_short_name(self):
return self.phone_number
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
def get_type(self):
if self.vendor:
return self.vendor_user
else:
return self.basic_user
#property
def staff(self):
return self.is_staff
#property
def admin(self):
return self.is_admin
#property
def active(self):
return self.is_active
#property
def vendor(self):
return self.is_vendor
#property
def basic(self):
return self.is_basic
USERNAME_FIELD = 'phone_number'
Then I created a superuser and tried to log in, but couldn't.
Upon checking the database from the python shell, I realized that the database had an empty phone number field for the superuser I created.
So the problem is: phone number is not properly saving when I create superuser
In your code you write:
user = self.model(phone_number)
(reformatted)
But if you create a model instance, all parameters must be named parameters (since fields are unordered, it would make it very hard to know where the values would "land"). So you have to specify the field name you want to update:
user = self.model(phone_number=phone_number)

'is_superuser' is an invalid keyword argument for this function

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

Why is Django giving me: 'first_name' is an invalid keyword argument for this function?

I'm trying to create a custom user profile and have modified the example only slightly
from django.conf import settings
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, first_name=None, last_name=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=MyUserManager.normalize_email(email),
first_name=first_name,
last_name=last_name,
#date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name=None, last_name=None):
user = self.create_user(email,
password=password,
first_name=first_name,
last_name=last_name,
#date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
first_name=models.CharField(max_length = 30),
last_name=models.CharField(max_length = 30),
#date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __unicode__(self):
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?"
# Simplest possible answer: All admins are staff
return self.is_admin
When I try to run syncdb I get the following error:
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Email address: uou#pce.com
Password:
Password (again):
TypeError: 'first_name' is an invalid keyword argument for this function
I have struggled to debug this because of the limited nature of the error message. I feel I'm making a simple mistake what am I doing wrong?
You are trying to set None (Null) value into first_name and it seems that this property don't allow it.
Try this changes:
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, first_name='', last_name=''):
In model:
first_name=models.CharField(max_length = 30, blank = True)