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.
Related
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)
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
I am trying to implement Django's built-in password reset functionality using my custom User model but I am running into this error when I try to submit an email address at /accounts/password_reset/:
FieldError at /accounts/password_reset/
Cannot resolve keyword 'is_active' into field. Choices are: ...
Exception location:
Exception Location: C:\Users\...\.virtualenvs\my_project-IsNTW6sC\lib\site-packages\django\db\models\sql\query.py in names_to_path, line 1378
I can provide the full traceback if someone wants to see it but it's reallllly long and it all points to back-end Django files.
Here is models.py:
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=True):
if not email:
raise ValueError('Users must have an email address.')
if not password:
raise ValueError('Users must have a password.')
user = self.model(
email = self.normalize_email(email)
)
user.staff = is_staff
user.admin = is_admin
user.active = is_active
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True
)
return user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=254, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # USERNAME_field (email) and pw required by default
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
username = models.CharField(max_length=200, unique=True, blank=False, validators=[
RegexValidator(
regex='^[a-z0-9_-]*$',
message='Usernames can only contain letters, numbers, underscores, and dashes.'
)
])
first_name = models.CharField(max_length=200, blank=False)
last_name = models.CharField(max_length=200, blank=False)
city = models.CharField(max_length=30, blank=True)
state_or_province = models.CharField(max_length=2, choices=all_choices, default='')
bio = models.TextField(max_length=500, blank=True)
date_joined = models.DateField(auto_now_add=True)
cc_reference = models.CharField(max_length=200, default=False)
event_list = ArrayField(models.IntegerField(), default=list)
def _get_username(self):
username = self.user.email
return username
def _get_firstname(self):
firstname = self.user.email
return firstname
def _get_lastname(self):
lastname = self.user.email
return lastname
def save(self, *args, **kwargs):
if not self.username:
self.username = self._get_username()
self.first_name = self._get_firstname()
self.last_name = self._get_lastname()
super().save()
#receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
instance.userprofile.save()
Any help is appreciated. Thanks!
EDIT:
Thanks to the answer below, I fixed the password reset issue. However, I am now unable to log my superuser in to the admin page. New User model is as follows. I did not change the UserManager:
class User(AbstractBaseUser):
email = models.EmailField(max_length=254, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # USERNAME_field (email) and pw required by default
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
In my case, I have just renamed the field active to is_active and removed is_active #property function.
And then, when I makemigrations it asked me that would I want to rename active field to is_active, and I hit Y to make the migration.
Finally, I migrate the changes to the database.
It's worked without any error.
Your model defines fields active, admin, and staff, instead of is_admin, is_staff, is_active.
In the class MyUser, there might be three functions:
def is_staff(self):
return self.is_staff
def is_admin(self):
return self.is_admin
def is_active(self):
return self.is_active
I believe that the repetition of these names creates a clash.
If possible, delete staff from your custom User.
delete sudsequent function: Not required (Note: Only function, not the object)
def is_active(self):
return self.is_active
Rename u/m function (u can call is_admin using is_staff(self):
def is_staff(self):
return self.is_admin
This will clear the clash and you both problems will be solved.
Note: You also have to remove the createstaffuser() function from the MyUserManager class, and you have to change admin and active (wherever you used them) to is_active and is_active respectively. Finally, you have to remove staff from admin, forms and models.
I hope, this will help.
Try adding is_superuser field into user model then migrate changes.
After, create superuser using terminal/cmd and then try logging as superuser agian
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'
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)