Home > OS >  Customizing Django Admin Add User With Blank Password
Customizing Django Admin Add User With Blank Password

Time:01-01

I'm am creating a Django web app with customised users authentication policy: only the superuser has a password and the users identification field is the email field. Normal users are only able to login by OAuth protocol so I don't need to store passwords for them. I created a custom user by overriding and extending AbstractBaseUser class.

Is there a way in Django Admin to allow to add/edit users with a blank password field (unusable password)? Thank you.

CodePudding user response:

class UserAccountManager(BaseUserManager):

def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
    if not username:
        raise ValueError('Username is required.')
    now = timezone.now()
    username = self.model.normalize_username(username)
    user = self.model(
        username=username,
        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, username=None, password=None, **extra_fields):
    return self._create_user(username, password, False, False, **extra_fields)

def create_superuser(self, username, password, **extra_fields):
    user = self._create_user(username, password, True, True, **extra_fields)
    user.save(using=self._db)
    return user

CodePudding user response:

Add this following line of code to your custom user model:

password = models.CharField(_('password'), max_length=128 , blank=True, null=True)

This will allow Django Admin to allow adding user without password. If it does not work, then use AbstractUser instead of AbstractBaseUser. When I was working for my projects I have tested this type of problem.

  • Related