Can users and superusers have the same email/username in a Django application?
I have a CustomUser
class for my users which is as follows.
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=150, unique=True, null=True, blank=True)
email = models.EmailField(max_length=240, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = CustomUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'password']
class Meta:
verbose_name = 'user'
It works pretty much as expected, I am able to signup, signin with normal users. The issue is when I try to create a superuser with the same email/username. I encounter the following error,django.db.utils.IntegrityError duplicate key value violates unique constraint "accounts_customuser_email_key"
.
I understand that there is a uniqueness constraint on the username and email field, but shouldn't a user be able to create a user and an admin account with the same credentials ideally?
I have a user with the following username and email. username: test_user email:test_user@test.com
, I decided to create an admin with the same email and usernames. Doing so leads to a unique constraint violation. I expected that Django would internally handle this.
Users and superusers cannot have the same email or username, because both are just users in your CustomUser model. Superusers are just users with the is_superuser=True flag set. All users, regardless of their permissions (is_staff, is_superuser, etc.), are stored in the same database table.
Your username and email are unique, so you cannot have two accounts - one regular and one superuser - with the same value.
If you want to make a user an admin, all you have to do is to set the is_staff attribute of that user to True.
So admins and superusers are users in the same table with is_staff and is_superuser attributes set to True. Also note that all superusers have is_staff set to True.