Can't login to Django Admin with custom User Model - django

I create a custom model for User, By this I can create superuser from command line, and its create successfully. But when I trying to login to Django admin with created Super user its show me This error
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
#property
def is_active(self):
return self.active
These property also set True
models.py
from django.db import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
creates a user with given email and password
"""
if not email:
raise ValueError('user must have a email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(self._db)
return user
def create_staffuser(self, email, password):
"""
creates a user with staff permissions
"""
user = self.create_user(
email=email,
password=password
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
creates a superuser with email and password
"""
user = self.create_user(
email=email,
password=password
)
user.staff = True
user.superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True
)
active = models.BooleanField(default=False)
staff = models.BooleanField(default=False) # <- admin user, not super user
superuser = models.BooleanField(default=False) # <- super user
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # <- email and password are required by default
class Meta:
app_label = "account_app"
db_table = "users"
def __str__(self):
return self.email
def get_full_name(self):
return str(self.email)
def has_perm(self, perm, obj=None):
"""Does the user has a specific permission"""
return True
def has_module_perms(self, app_lable):
"""Does the user has permission to view a specific app"""
return True
#property
def is_staff(self):
"""Is the user a staff member"""
return self.staff
#property
def is_superuser(self):
"""Is the user a admin member"""
return self.superuser
#property
def is_active(self):
"""Is the user active"""
return self.active
# hook the user manager to objects
objects = UserManager()
settings.py where I change for Custom User Model
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dashboard_app',
'account_app',
]
AUTH_USER_MODEL = "account_app.User" # changes the built-in user model to ours
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
WSGI_APPLICATION = 'SMSystem.wsgi.application'

its set default value for active = 0 need to set 1 or True

Had the same issue. Instead of password=None, change it to password. And pass 'password=password' together with 'username=username' into the create_user function as you see below:
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password):
if not email:
raise ValueError('Please add an email address')
if not username:
raise ValueError('Please add an username')
**user = self.model(email=self.normalize_email(
email), username=username, password=password)**
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(email=self.normalize_email(
email), username=username, password=password)
user.is_active = True
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
Hope it works for you

Only users with is_active attribute True can log into the system.
Inside createuser method pass active=True or change default value of active to True
def create_user(self, email, password=None):
"""
creates a user with given email and password
"""
if not email:
raise ValueError('user must have a email address')
user = self.model(
email=self.normalize_email(email),
active=True, #Add this line
)
user.set_password(password)
user.save(self._db)
return user
--OR, change default value of active to true --
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='Email address',
max_length=255,
unique=True
)
# change default value to True
active = models.BooleanField(default=True)

Related

I'm unable to login in admin and login is not working in Django project after Custom User

Tysm in advance, for helping
Already a superuser is made but admin login or login view is not working, Some problem in authenticate it every time returns none if correct password and email are passed
Custom User Model
class UserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError("Email Requierd!")
if not username:
raise ValueError("Username required!")
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
userid = models.UUIDField(
default=uuid.uuid4, editable=False, primary_key=True)
username = models.CharField(max_length=255, unique=True)
email = models.EmailField(max_length=255, unique=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now_add=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 = ['username']
objects = UserManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perm(self, app_label):
return True
Already a superuser is made but admin login or login view is not working, Some problem in authenticate it every time returns none if password and email are passed!
psql view
login view
def login_view(request):
user = request.user
if user.is_authenticated:
return redirect('home')
if request.POST:
form = LoginForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model, authenticate
User = get_user_model()
class UserCreateForm(UserCreationForm):
email = forms.EmailField()
#is_seller = forms.BooleanField
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class LoginForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'password']
def clean(self):
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(request, email=email, password=password):
raise forms.ValidationError("Invlaid Login")
After login, it doesn't give me any errors and neither redirects to homepage!
After login, it doesn't give me any errors and neither redirects to homepage!
Tysm in advance, for helping
Try to set is_active field as default=True

how can i add phone number field from class profile to class user?

I need to add phone number into my required model's field, so I'm doing this but is not working correctly
so if everyone knows how can I add a Phone number, please help me:
#models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
class UserManager(BaseUserManager):
def create_user(self, phone_number, email, password=None, is_active=True, is_staff=False, is_admin=False):
if not email:
raise ValueError("User Must have an Email Address")
if not password:
raise ValueError("User Must have a Password")
if not phone_number:
raise ValueError("User Must have a Phone Number")
user_obj = self.model(email=self.normalize_email(email))
user_obj.set_password(password) # change user password
user_obj.phone_number(phonenumber_field)
user_obj.staff = is_staff
user_obj.active = is_active
user_obj.admin = is_admin
user_obj.save(using=self._db)
return user_obj
# staff user
def create_staffuser(self, email, password=None):
user = self.create_user(
email,
password=password,
phone_number=PhoneNumberField,
is_staff=True
)
return user
# admin user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
phone_number=PhoneNumberField,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
# full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True) # can log in
staff = models.BooleanField(default=False) # staff user non super user
admin = models.BooleanField(default=False) # super user
timestamp = models.DateTimeField(auto_now_add=True)
phone_number = PhoneNumberField()
USERNAME_FIELD = 'email' # username
REQUIRED_FIELDS = [] # FULL_NAME
object = 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 Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
I wanna add phone number in class profile and include this to the required field on user class, but I cant
every time i have error : raise TypeError("Can't convert %s to PhoneNumber." % type(value).name)
TypeError: Can't convert int to PhoneNumber.
You can't add a ModelField class to an attribute. Instead try to pass the value through method arguments. As per documentation, you should be able to pass the value if the field is required.
So, update your manager method like this:
class UserManager(BaseUserManager):
def create_user(self, email, phone_number, password=None, is_active=True, is_staff=False, is_admin=False):
if not email:
raise ValueError("User Must have an Email Address")
if not password:
raise ValueError("User Must have a Password")
if not phone_number:
raise ValueError("User Must have a Phone Number")
user_obj = self.model(email=self.normalize_email(email))
user_obj.set_password(password) # change user password
user_obj.phone_number = phone_number
user_obj.staff = is_staff
user_obj.active = is_active
user_obj.admin = is_admin
user_obj.save(using=self._db)
return user_obj
# staff user
def create_staffuser(self, email, phone_number, password=None):
user = self.create_user(
email,
password=password,
phone_number=phone_number,
is_staff=True
)
return user
# admin user
def create_superuser(self, email, phone_number, password=None):
user = self.create_user(
email,
password=password,
phone_number=phone_number,
is_staff=True,
is_admin=True
)
return user
And add phone_number to required fields in model:
REQUIRED_FIELDS = ['phone_number']

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)

Django: no attribute 'get_by_natural_key'

i currently try the implement my very own user model. Therefor i created a new app "accounts". But each time when i try to create anew user i get the following error:
AttributeError: 'AnonymousUser' object has no attribute '_meta'
accounts - models.py:
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
#User Model Manager
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not username:
raise ValueError('Error: The User you want to create must have an username, try again')
user = self.model(
user=self.normalize_username(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, username, password):
"""
Creates and saves a staff user with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
#User fields
user = models.CharField(verbose_name='username',max_length=30,unique=True)
bio = models.TextField(max_length=5000, blank=True, null=True)
pubpgp = models.TextField(blank=True, null=True)
#Account typs
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'user'
REQUIRED_FIELDS = [] # Username & Password are required by default.
def get_full_name(self):
# The user is identified by their Username ;)
return self.user
def get_short_name(self):
# The user is identified by their Username address
return self.user
def __str__(self):
return self.user
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()
After that i jumpt back to settings.py and added the custom user model to my acctual blog application:
AUTH_USER_MODEL = 'accounts.User'
and i also added
INSTALLED_APPS = [
...
'accounts',
...
]
All this user model/django stuff is a bit new to me and i have no idea what the error "AttributeError: 'Manager' object has no attribute 'get_by_natural_key'" means.
Thanks :D
Edit: AttributeError: 'UserManager' object has no attribute 'normalize_username'
normalize_username belongs to AbstractBaseUser, you can try the code below.
In signup view, when you save the form you already get the user (form.save()). Because the reason from authentication is to verify a set of credentials and getting the user (but we already have the user)
In this line: user = authenticate(username=username, password=raw_password), the authenticate method takes request as the first argument, so it should be: user = authenticate(request, username=username, password=raw_password), therefore you got the Error 'AnonymousUser' object has no attribute '_meta'.
Try:
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('post_list')
Edit UserManager:
Reaname all created users to some other name (ex. my_user) because you have tow varibales with the same name (the USERNAME_FIELD and the user created)
Here is the signature of create_user and create_superuser
create_user(*username_field*, password=None, **other_fields)
create_superuser(*username_field*, password, **other_fields)
They take the USERNAME_FIELD as the first argument, and yours is user
class UserManager(BaseUserManager):
def create_user(self, user, password=None):
"""
Creates and saves a User with the given username and password.
"""
if not user:
raise ValueError('Error: The User you want to create must have an username, try again')
my_user = self.model(
user=self.model.normalize_username(user),
)
my_user.set_password(password)
my_user.save(using=self._db)
return my_user
def create_staffuser(self, user, password):
"""
Creates and saves a staff user with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.save(using=self._db)
return my_user
def create_superuser(self, user, password):
"""
Creates and saves a superuser with the given username and password.
"""
my_user = self.create_user(
user,
password=password,
)
my_user.staff = True
my_user.admin = True
my_user.save(using=self._db)
return my_user
I hope this will help.

django admin not working with custom user

I feel like I'm missing somehting obvious on this one.
I've created a custom user and user manger
class UserManager(BaseUserManager):
# create a normal user
# an email and password must be provided
def create_user(self, email, password, first_name, last_name,
location, date_of_birth):
if not email:
raise ValueError("User must have an email")
if not password:
raise ValueError("User must have a password")
email = email.lower()
user = self.model(
email=email,
first_name=first_name,
last_name=last_name,
location=location,
date_of_birth=date_of_birth
)
user.set_password(password)
user.save(using=self._db)
return user
# Make an administrator
def create_superuser(self, email, password, first_name, last_name,
location, date_of_birth):
user = self.create_user(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
location=location,
date_of_birth=date_of_birth
)
user.is_admin = True
user.is_moderator = 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=50)
last_name = models.CharField(max_length=50)
location = models.ForeignKey(Location)
date_of_birth = models.DateField()
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_moderator = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'location', 'date_of_birth']
def __unicode__(self):
return self.email
def get_full_name(self):
return self.first_name + ' ' + self.last_name
def get_age(self):
age = date.today() - self.date_of_birth
return age.days / 365
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
However if I visit the admin site, It will happily authorize a user who is not an admin is_admin=False
Has anyone run into this problem, Is there something I need to change when using django admin with a custom user?
EDIT
setting.py
AUTH_USER_MODEL = 'userAccount.User'
AUTHENTICATION_BACKEND = (
'django.contrib.auth.backends.ModelBackend',
)
is_admin is not something that django's authentication system knows about. In the authentication form that is used, it is only checking if the user is active or is staff:
class AdminAuthenticationForm(AuthenticationForm):
"""
A custom authentication form used in the admin app.
"""
error_messages = {
'invalid_login': _("Please enter the correct %(username)s and password "
"for a staff account. Note that both fields may be "
"case-sensitive."),
}
required_css_class = 'required'
def confirm_login_allowed(self, user):
if not user.is_active or not user.is_staff:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name}
)
In the original user model, is_staff is a model field. You do not have such a field, but rather a method. This could be a why its not working.
You can solve this problem two ways:
Create your own AdminAuthenticationForm and adjust the confirm_login_allowed method to check for is_admin rather than is_staff.
Create a is_staff property in your custom user model:
#property
def is_staff(self):
return self._is_admin