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

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.

Related

Serializer user "Invalid data. Expected a dictionary, but got User"

I am trying to display the fields of my user model but I always get that my serializer is not valid
{
"non_field_errors": [
"Invalid data. Expected a dictionary, but got User."
]
}
this is my model
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
class UserManager(BaseUserManager):
def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
user = self.model(
username=username,
is_staff=is_staff,
is_superuser=is_superuser,
**extra_fields
)
user.set_password(password)
user.save(using=self.db)
return user
def create_user(self, username, password=None, **extra_fields):
return self._create_user(username, password, False, False, **extra_fields)
def create_superuser(self, username, password=None, **extra_fields):
return self._create_user(username, password, True, True, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=255, unique=True)
email = models.EmailField( max_length=255, blank=True, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
age = models.PositiveIntegerField()
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
def __str__(self):
return f"{self.id} {self.name} {self.username} {self.age}"
this is my serializer
class UserUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email', 'username', 'name', 'age']
this is my view
class UserUpdateApiView(APIView):
def get(self, request, pk):
try:
queryset = User.objects.get(pk=pk)
serializer = UserUpdateSerializer(data=queryset)
if serializer.is_valid(raise_exception=True):
return Response(data=serializer.data)
except User.DoesNotExist:
return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND)
You have used the data keyword argument, i think the problem is here. Pass the queryset without keyword argument:
class UserUpdateApiView(APIView):
def get(self, request, pk):
try:
queryset = User.objects.get(pk=pk)
serializer = UserUpdateSerializer(queryset)
return Response(serializer.data)
except User.DoesNotExist:
return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND)
data is the serialized output in fact. the keyword argument for passing your input model data is named instance I believe

How to remove username field and password2 field from RegisterSerializer in django rest framework?

When I call the api/seller/register api, the fields appear are username, password1 and password2. I want these removed and only want simple password, email and phone_num.
How to remove this?
I am trying to make a seller registration using RegisterSerializer. I tried with ModelSerailzers and provided fields as I want but this will lead to me the error saying save() only takes 1 argument.So, I just want these unnecessary fields removed using RegisterSerializer.
My model:
class CustomUserManager(BaseUserManager):
"""
Custom user model manager with email as the unique identifier
"""
def create_user(self, first_name, last_name, email, password, **extra_fields):
"""
Create user with the given email and password.
"""
if not email:
raise ValueError("The email must be set")
first_name = first_name.capitalize()
last_name = last_name.capitalize()
email = self.normalize_email(email)
user = self.model(
first_name=first_name, last_name=last_name, email=email, **extra_fields
)
user.set_password(password)
user.save()
return user
def create_superuser(self, first_name, last_name, email, password, **extra_fields):
"""
Create superuser with the given email and password.
"""
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
extra_fields.setdefault("is_active", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self.create_user(first_name, last_name, email, password, **extra_fields)
class CustomUser(AbstractUser):
username = models.CharField(max_length=255,blank=False)
first_name = models.CharField(max_length=255, verbose_name="First name")
last_name = models.CharField(max_length=255, verbose_name="Last name")
email = models.EmailField(unique=True)
is_seller = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
objects = CustomUserManager()
def __str__(self):
return self.email
My serializer:
class SellerRegisterSerializer(RegisterSerializer):
seller = serializers.PrimaryKeyRelatedField(read_only=True,)
# username = serializers.CharField(required=True)
phone_num = serializers.CharField(required=False)
# class Meta:
# model = User
# fields = ['seller','email', 'phone_num', 'first_name', 'last_name', 'password']
def get_cleaned_data(self):
data = super(SellerRegisterSerializer, self).get_cleaned_data()
extra_data = {
'phone_num': self.validated_data.get('phone_num', ''),
}
data.update(extra_data)
return data
def save(self, request, **kwargs):
user = super(SellerRegisterSerializer, self).save(request)
# user = super().save(is_seller=True)
user.is_seller = True
user.save()
seller = Seller(seller=user,
phone_num=self.cleaned_data.get('phone_num'))
seller.save()
return user
My view:
class SellerRegisterView(RegisterView):
serializer_class = SellerRegisterSerializer

You are trying to add a non-nullable field 'password' to user without a default; we can't do that

I am building a custom User class in django to use in creating a signup application and I keep on getting the error above every time I try to makemigrations.As far as I can see, my code is per django documentation here.I also have AUTH_USER_MODEL correctly placed in my settings configurations. Here's my models.py
# from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""Create and save 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)
if password:
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and password."""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=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 User(AbstractUser):
email = models.EmailField(_('email address'), unique=True, default='email')
username = None
first_name = models.CharField(max_length=20, blank=False, null=False, default='first_name')
last_name = models.CharField(max_length=20, blank=False, null=False, default='last_name')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+91 ...'")
phone_no = models.CharField(validators=[phone_regex], max_length=17,blank=False, default='phone_number')
# email_validator = EmailValidator(message='Invalid email
# address',code=None,whitelist=None)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
# Email & Password are required by default
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
objects = UserManager()
def get_full_name(self):
return self.email
def get_short_name():
return self.email
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
# does user have a specific permission
return True
def has_module_pers(self, app_label):
# does user have permissions to view the app 'app_label'
return True
#property
def is_admin(self):
return self.is_admin
#property
def is_active(self):
return self.is_active
# Create your models here.""
I removed the existing users from Database and deleted the previous migration files from migration folder. After again migrations issue has been resolved

Custom User model error: AttributeError: 'CustomUser' object has no attribute 'is_anonymous'

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!
Your CustomUser class must inherit from AbstractBaseUser too. You didn't include it in your code. models.Model is not necessary then.
First you must do :
from django.contrib.auth.models import AbstractBaseUser
And then
class CustomUser(AbstractBaseUser):
###
You can simply add this property in your CustomUser model:
#property
def is_anonymous(self):
"""
Always return False. This is a way of comparing User objects to
anonymous users.
"""
return False

'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