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',)}),
)
Related
I’m new to django and am sure this is probably a quick spot for most. I essentially want to:
Change the default User model to use an email (and password) to log in (instead of username)
Add extra fields to the default User model
I’ve followed a video tutorial that resulted in me writing this code:
Models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyAccountManager(BaseUserManager):
def create_user(self, email, password=None):
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), # converts chars to lowercase
password=password,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password): # password=None?
user = self.create_user(
email=self.normalize_email(email),
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email",
max_length=100, unique=True)
date_joined = models.DateTimeField(
verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=100, null=True, blank=True)
last_name = models.CharField(max_length=100, null=True, blank=True)
# username field unwanted - only added to get rid of fielderror "Unknown field(s) (username) specified for Account. Check fields/fieldsets/exclude attributes of class AccountAdmin."
username = models.CharField(max_length=30, unique=True, blank=True)
# #todo: add more new fields
USERNAME_FIELD = 'email' # so users use email to log in
REQUIRED_FIELDS = ['password']
objects = MyAccountManager()
def __str__(self): # add -> str: type?
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
Admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from accounts.models import Account
class AccountAdmin(UserAdmin):
list_display = ('email', 'date_joined', 'is_staff', 'is_admin')
search_fields = ('email', 'date_joined')
readonly_fields = ('date_joined', 'last_login') # make fields immutable
filter_horizontal = ()
list_filter = ()
fieldsets = ()
ordering = ()
admin.site.register(Account, AccountAdmin)
My questions are as follows:
When using the createsuperuser command, why does it only require me to type in a password once? (I thought it should ask again to confirm; it just asks for email and password fields once)
When clicking on ‘add account’ in django admin, why doesn’t it ask for an email and password? (It asks for an un-required username and required password (and 2nd password-retype)
The point of these classes is to just try to user the default User model (instead of creating my own Account class for example) and edit it to rid the username field and add other new fields. Am I overcomplicating the solution here and, instead, should I just create a new class that simply extends the User model like the example below?
class Account(User):
new_field = models.BooleanField(default=False)
objects = UserManager()
Is this way just simpler and better for me: https://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
When clicking ‘add account’ in the django admin, does it try to create a new super user, or just a new instance of the MyAccountManager, Account or AccountAdmin class?
Thanks for helping a beginner out here.
The application does what you have told it to do, and as per your MyAccountManager class you have to enter the password only once.
I would think that the problem occurs in the admin.py bit. Your AccountAdmin inherits from UserAdmin class, which aims at serving the Django User model. In order to work with your custom user model, use ModelAdmin.
from django.contrib import admin
from accounts.models import Account
class AccountAdmin(admin.ModelAdmin):
list_display = ('email', 'date_joined', 'is_staff', 'is_admin')
search_fields = ('email', 'date_joined')
readonly_fields = ('date_joined', 'last_login') # make fields immutable
filter_horizontal = ()
list_filter = ()
fieldsets = ()
ordering = ()
admin.site.register(Account, AccountAdmin)
I would say the Django User model will not work for you, because you need to set a unique email field, get rid of the username, and use email when logging the user in. As per Django documentation in this situation you need to implement a custom user model.
I'm working on a project using Python(3.7) and Django(2.2) in which I have to implement multiple types of users as:
Personal Account - below 18
Personal Account - above 18
Parent Account
Coach Account
Admin
along with that, I also need to use email as the username field for login/authentication.
The strategy I'm trying to use is to build a custom base model as User inherited from AbstractBaseUser and also created a custom User Manager to make the email as username but it's not working.
Here's my complete model code:
class UserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
if not email:
raise ValueError('Users must have an email address')
now = timezone.now()
email = self.normalize_email(email)
user = self.model(
email=email,
is_staff=is_staff,
is_active=True,
is_superuser=is_superuser,
last_login=now,
date_joined=now,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
user = self._create_user(email, password, True, True, **extra_fields)
user.save(using=self._db)
return user
def generate_cid():
customer_number = "".join([random.choice(string.digits) for i in range(10)])
return customer_number
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
is_personal_above_18 = models.BooleanField(default=False)
is_personal_below_18 = models.BooleanField(default=False)
is_parent = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % self.pk
def get_email(self):
return self.email
class PersonalAccountAbove18(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True, related_name='profile')
customer_id = models.BigIntegerField(default=generate_cid)
class PersonalAccountBelow18(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True, related_name='profile')
customer_id = models.BigIntegerField(blank=False)
class ParentAccount(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True, related_name='profile')
customer_id = models.BigIntegerField(default=generate_cid)
I'm confused about my approach and even it's also return an error when I run makemigrations as:
users.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.
Update:
I removed the PermissionMixin and related_name attributes from child models and migrations are running now but it still require the username instead of email.
The errors in makemigrations, and later (after dropping PermissionsMixin) requiring username instead of email for authentication are hints that you have not set your custom model as the default user model to be used by the Django auth app. As a result, Django is using the auth.User model as the default user model and your one being added to the project like any other model. So both of the user models exist simultaneously with the auth.User being the default/active one used for authentication purposes.
In essence, edit your settings.py to add the following:
AUTH_USER_MODEL = '<your_app>.User'
Now Django will use your customized User model instead of the one from auth app (the default) and the auth.User model will be dropped. The auth app uses the get_user_model (django.contrib.auth.get_user_model) function to get the currently active user model for the project which checks for settings.AUTH_USER_MODEL, and by default the rest of the system (e.g. the admin app) also checks for this setting to get the current user model. So as long as you're using the auth app the above should suffice.
For using email as login, I recommend the django-allauth package. It takes care of all the heavy lifting and you can use it to login with email instead of username. Will Vincent has a write up on this at:
https://wsvincent.com/django-allauth-tutorial-custom-user-model/
Will also has a good write up on creating custom user models at:
https://wsvincent.com/django-custom-user-model-tutorial/
In short, he recommends subclassing AbstractUser. Here is an example from one of my projects where a user collects points throughout their journey on the site and I must record these points.
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
points = models.IntegerField(default=0)
def user_id(self):
return self.id.__str__()
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
Is there any way to implement form only with email field (without password and username)? User will receive email with link to confirm his account and set password.
Any information will be helpfull, thanks.
To user Temka:
I've already have cutom RegistrationForm:
from registration.forms import RegistrationForm
class UserForm(RegistrationForm):
username = forms.CharField(
max_length=254,
required=False,
widget=forms.HiddenInput(),
)
password1 = forms.CharField(
widget=forms.HiddenInput(),
required=False,
)
password2 = forms.CharField(
widget=forms.HiddenInput(),
required=False,
)
def clean_email(self):
email = self.cleaned_data['email']
self.cleaned_data['username'] = email
return email
def clean_password2(self):
pass
Also thanks for "unusable password" info.
User model
First you need to create custom User manager and model.
Documentation can be found here https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#a-full-example
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class EmailUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
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):
user = self.create_user(email, password=password,)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class EmailUser(AbstractBaseUser, PermissionsMixin):
email = EmailField(
verbose_name='email',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = EmailUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
#property
def is_staff(self):
return self.is_admin
And register it in your settings.py with this line AUTH_USER_MODEL = 'app.EmailUser'.
Now your EmailUser model can be used with from django.contrib.auth import get_user_model and from django.conf.settings import AUTH_USER_MODEL.
Example usage (foreign key):
from django.db import models
from django.conf.settings import AUTH_USER_MODEL
class Profile(models.Model):
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
user = models.OneToOneField(AUTH_USER_MODEL, verbose_name='User',
related_name='profile')
full_name = models.CharField('Full name', max_length=64, blank=False)
phone = models.CharField('Phone', max_length=64, blank=True)
Registration
When using django-registration-redux two-step registration:
Create User with None password on registration. This will make User model with unusable password https://docs.djangoproject.com/es/1.9/ref/contrib/auth/#django.contrib.auth.models.User.has_usable_password. It may be necessary to create custom RegistrationForm and RegistrationView to avoid password checking.
On activation form submit (activation form template with password field) use methods RegistrationManager.activate_user(key) and User.set_password(password)
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