I've created a CustomUser from AbstractUser in Django 1.9. Add on admin.sites.register when I was create superuser, django have created successful but when I was log in on system the user didn't exists.
Follow the code:
On customuser/models.py:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, username, email, first_name, last_name, cpf, password=None):
user = self.model(
username=username,
email=email,
first_name=first_name,
last_name=last_name,
cpf=cpf
)
return user
def create_superuser(self, username, email, first_name, last_name, cpf, password):
user = self.create_user(username, email, first_name, last_name, cpf,
password=password)
user.is_super_user = True
user.save()
return user
class CustomUser(AbstractUser):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
cpf = models.BigIntegerField(unique=True)
phone = models.CharField(max_length=15, blank=True)
is_super_user = models.BooleanField(default=False)
data_de_nascimento = models.DateField(null=True)
sexo = models.CharField(max_length=9, null=True, choices=SEXO_CHOICES)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'cpf']
objects = CustomUserManager()
On settins.py, I add the line:
INSTALLED_APPS = [
...
'customuser',
]
...
AUTH_USER_MODEL = 'customuser.CustomUser'
And my customuser/admin.py:
from django.contrib import admin
from models import CustomUser, CustomUserManager
admin.site.register(CustomUser)
Thanks a lot for your help.
See these docs on making custom user work with admin site.
UPDATE:
Sorry, previously I thought, you were inheriting your model from AbstractBaseUser, therefore that answer was giving you error.
Since, you're inheriting from AbstractUser, your subclass will automatically get is_staff field. So, you'll just need to set is_staff to True in create_superuser method.
class CustomUserManager(...):
# ...
def create_superuser(...):
# ...
user.is_staff = True
user.save()
return user
Related
Here is my model in the user app
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserTable(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD='email'
objects = UserManager()
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
phone = models.CharField(max_length=255, default=None)
is_active = models.BooleanField(default=False)
Here is my admin.py inside the user app.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import UserTable
admin.site.register(UserTable, UserAdmin)
I also included in my settings.py
INSTALLED_APPS = [
....
'user.apps.UserConfig',
....
]
This is the error when I run python manage.py migrate
(admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.UserTable'.
The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'user.UserTable'.
I dont know why, I thought when I set objects = UserManager() fields like username, first_name, last_name is setted up. I also user USERNAME_FIELD to set email replacing the username primary key.
You are supposed to write ur own UserManager
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('User must have an email address')
user = self.model(
email=self.normalize_email(email),
**extra_fields
)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
user = self.create_user(
email,
password,
**extra_fields
)
return user
Just a small comment in UserTable model, make
is_active = models.BooleanField(default=True) To be able to login
And in settings.py file add
AUTH_USER_MODEL = 'user.UserTable'
Edit
I noticed that you are calling AbstractBaseUser, BaseUserManager in a wrong way
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
Try it out and told me if there is any problem!
The problem is because you are inheriting from AbstractBaseUser (which does not come with a username field):
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
... # No definition for usename in this class
and then using UserAdmin (which requires username as field) as your admin:
#admin.register(User)
class UserAdmin(admin.ModelAdmin):
...
# The admin needs the username field as described by ordering
# But your custom user model doesn't have it
ordering = ('username',)
There are a number of ways to fix this, but one way is to define your own model admin for your custom user:
from django.contrib import admin
class MyAdmin(admin.ModelAdmin):
pass
admin.site.register(UserTable, MyAdmin)
I can't seem to figure out why my unit test is failing for the following
Traceback (most recent call last):
File "/app/core/tests/test_admin.py", line 26, in test_users_listed
self.assertContains(res, self.user.name)
AttributeError: 'AdminSiteTests' object has no attribute 'user'
test_admin.py
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setup(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='admin#test.com',
password='test123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
email='test#test.com',
password='test123',
name='test name'
)
def test_users_listed(self):
"""Test that users are listed on user page"""
url = reverse('admin:core_user_changelist')
res = self.client.get(url)
self.assertContains(res, self.user.name)
self.assertContains(res, self.user.email)
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from core import models
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
admin.site.register(models.User, UserAdmin)
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if not email:
raise ValueError('Users must have a email address')
user = self.model(email=self.normalize_email(email), **extra_fields)
# Must encrypt password using set_password() that comes with BaseUserManager
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""Creates and saves new superuser"""
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using email instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
I am creating the user in the setup function for the rest of my tests but I'm thinking maybe the setup function isn't getting called to create the user?
All other tests are passing. Including a test that checks whether a user has been created. Any help would be apperciated
I created a custom user model and I can create new superuser with manage.py but when I login to admin panel, I can't add new user (although is_superuser column is true in database).
This is my models.py:
class MyUser(AbstractUser):
email = models.EmailField(unique=True)
department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'password']
I also tried with custom UserManager but still not working:
class MyUserManager(UserManager):
def create_superuser(self, username, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
u = self._create_user(username, email, password, **extra_fields)
u.save()
return u
class MyUser(AbstractUser):
email = models.EmailField(unique=True)
department = models.ForeignKey(to=Department, on_delete=models.CASCADE, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'password']
objects = MyUserManager()
Here is my admin panel screenshot:
screenshot
This solution helped me to solve the problem (but with a few changes).
I just needed to register my custom model in admin. Here is what I did:
from .models import MyUser, Department
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
#admin.register(MyUser)
class MyUserAdmin(UserAdmin):
fieldsets = UserAdmin.fieldsets + (
('Departmet', {'fields': ('department',)}),
)
The custom authentication I wrote follows the instructions from the docs. I am able to register, login, and logout the user, no problem there. Then, when I create a superuser python manage.py createsuperuser, it creates a user in the database, but it does not let me login when I go to the admin page and try to login saying
Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.
Here is my code:
models.py:
from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractUser, AbstractBaseUser, Group, Permission
from django.contrib.auth.models import BaseUserManager
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist, MultipleObjectsReturned
from datetime import datetime
from django.contrib.auth.models import PermissionsMixin
import re
class CustomUserManager(BaseUserManager):
def create_user(self, email, password = None):
'''Creates and saves a user with the given email and password '''
if not email:
raise ValueError('Email address is requied.')
user = self.model(email = self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
''' Creates and saves a superuser with the given email and password '''
user = self.create_user(email, password = password)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""
Custom user class
"""
email = models.EmailField(verbose_name = 'email address',unique = True, db_index = True)
# email is the unique field that can be used for identification purposes
first_name = models.CharField(max_length = 20)
last_name = models.CharField(max_length = 30)
joined = models.DateTimeField(auto_now_add = True)
is_active = models.BooleanField(default = True)
is_admin = models.BooleanField(default = False)
is_superuser = models.BooleanField(default = False)
group = models.ManyToManyField(Group, related_name = 'users')
permission = models.ManyToManyField(Permission, related_name = 'users')
objects = CustomUserManager()
USERNAME_FIELD = 'email' # the unique identifier (mandatory) The filed must have unique=True set in its definition (see above)
def get_full_name(self):
return self.email
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj=None):
''' Does the user have a specific permission'''
return True # This may need to be changed depending on the object we want to find permission for
def has_module_perms(self, app_label):
''' Does the user have permission to view the app 'app_label'? The default answer is yes.
This may be modified later on. '''
return True
#property
def is_staff(self):
''' IS the user a member of staff? '''
return self.is_admin
def __unicode__(self):
return '{user_email}, {user_title} joined on {joined_date}'.format(user_email = self.email,
user_title = self.user_type,
joined_date = self.joined)
In backends.py:
from django.conf import settings
from django.contrib.auth.hashers import check_password
from accounts.models import User
class EmailAuthBackend(object):
''' Custom authentication backend. Allows users to login using their email address '''
def authenticate(self, email=None, password = None):
''' the main method of the backend '''
try:
user = User.objects.get(email = email)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk = user_id) # Note that you MUST use pk = user_id in getting the user. Otherwise, it will fail and even though the user is authenticated, the user will not be logged in
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
in admin.py:
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from accounts.models import User as CustomUser
class UserCreationForm(forms.ModelForm):
''' A Form for creating new users. Includes all the required field, plus a repeated password.'''
password1 = forms.CharField(label = 'Password', widget = forms.PasswordInput)
password2 = forms.CharField(label = 'Password Confirmation', widget = forms.PasswordInput)
class Meta:
model = CustomUser
fields = ('email',)
def clean_password2(self):
''' Checks that the two password entries match '''
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Passwords do NOT match!')
return password2
def save(self, commit = True):
''' Save the provided password in hashed format '''
user = super(UserCreationForm, self).save(commit = False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
''' A form for updating users. Includes all the field on the user, but replaces the password field with admin's password hash display field '''
password = ReadOnlyPasswordHashField()
class Meta:
model = CustomUser
fields = ('email', 'password', 'first_name', 'last_name', 'is_active', 'is_admin')
def clean_password(self):
''' Regardless of what the user provides, return the initial value. This is done here rather than on the field because the field
does not have access to the initial value'''
return self.initial['password']
class UserAdmin(BaseUserAdmin):
''' The form to add and change user instances '''
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the user model.
# These override the defintions on the base UserAdmin
# that reference specific fields on auth.User
list_display = ('email', 'first_name', 'last_name', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal Info',{'fields': ('first_name', 'last_name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user
add_fieldsets = (
(None, {'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now, register the new UserAdmin...
admin.site.register(CustomUser, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
And, finally, in settings.py:
AUTHENTICATION_BACKENDS = ['accounts.backends.EmailAuthBackend',]
So what's missing?
I think the problem is in your EmailAuthBackend. If you add some printing/logging to the backend, you'll find that the login form calls the authenticate method with username and password. This means that email is None, and therefore the user = User.objects.get(email = email) lookup fails.
In your case, the regular ModelBackend will work fine for you, because you have USERNAME_FIELD = 'email'. If you remove AUTHENTICATION_BACKENDS from your settings then the login should work. You can then remove your EmailAuthBackend.
If you wanted to log in users with their cell number and password (and cell_number was not the USERNAME_FIELD, then you would need a custom authentication backend. You would also need a custom authentication form that called authenticate(cell_number=cell_number, password=password). Another example of a custom authentication backed is RemoteUserBackend, which logs in the user based on an environment variable set by the server.
Had the same issue. Instead of password=None, I changed it to password only. And passed 'password=password' , together with 'username=username' as you can 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)
And as Denis has already said above, make sure to add AUTH_USER_MODEL = 'accounts.User' to settings.py
In my current project I'm replacing the default django user model. As the number of models started growing I decided to split the implementation into several folders, but now django can't find my user model.
I had this, which works:
djutils
models.py
UserManager
User
I changed to this and it doesn't work anymore
djutils
models
__init__.py
from djutils.models.user import UserManager, User
user.py
UserManager
User
Shouldn't it still import the models? I get:
CommandError: One or more models did not validate:
auth.user: Model has been swapped out for 'djutils.User' which has not been installed or is abstract.
I have this in my settings.py
AUTH_USER_MODEL = 'djutils.User'
(Notice the first case works)
Please advise!
Regards
Edit
djutils
models
__init__.py
from __future__ import absolute_import
from djutils.models.base import Manager, PrivateModel, Model
from djutils.models.user import UserManager, User
from djutils.models.passwordrecovery import PasswordRecoveryManager, PasswordRecovery
user.py
from djutils.models.base import Manager, Model
from djutils import mail
from djutils import settings
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from djutils import fields
class UserManager(Manager, BaseUserManager):
def create_user_instance(self, email, password, first_name, last_name, **extra_fields):
return user
def create_user(self, email, password, first_name, last_name, **extra_fields):
return user
def create_superuser(self, email, password, first_name, last_name, **extra_fields):
return user
class User(Model(20), AbstractBaseUser, PermissionsMixin):
# Basico info
first_name = fields.NameField(max_length=20, help_text=_('First name'))
last_name = fields.NameField(max_length=20, help_text=_('Last name'))
email = fields.EmailField(max_length=255, unique=True, help_text=_('Email'))
url = fields.URLField(help_text=_('Personal homepage'))
bio = fields.TextField(help_text=_('Biographic details'))
#picture = fields.ImageField(help_text=_('Profile picture'))
# Permissions
is_active = fields.BooleanField(default=False, help_text=_('Active user'))
is_staff = fields.BooleanField(default=False, help_text=_('Staff member'))
# Logging
date_joined = fields.DateTimeField(default=timezone.now)
# A string describing the name of the field on the User model that is used as the unique identifier
USERNAME_FIELD = 'email'
# A list of the field names that must be provided when creating a user via the createsuperuser management command
REQUIRED_FIELDS = ['first_name', 'last_name', 'password']
# Fields that are not returned by get_public
PRIVATE = ['is_active', 'is_superuser', 'is_staff', 'last_login', 'groups', 'user_permissions', 'password', 'id']
# Model manager
objects = UserManager()
class Meta:
swappable = 'AUTH_USER_MODEL'
permissions = ()
def send_mail(self, request, subject, body, context={}):
mail.send_mail(request, subject, body, [self.email], context)
def send_confirmation_email(self, request, context={}):
self.send_mail(request, settings.CONFIRMATION_SUBJECT, settings.CONFIRMATION_TEMPLATE, dict(context, **{
'redirect': request.build_absolute_uri(settings.CONFIRMATION_REDIRECT_URL)
}))
Set app_label = 'djutils' in your User model's Meta class.
See the app_label docs for more info.