I create custom User
model inheriting from AbstractUser
in Django
:
class ChachaUser(AbstractUser):
birth = models.DateField()
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
and my CustomUserCreationForm
:
GENDER_CHOICES = (
('M', '남'),
('F', '여'),
)
class MyUserCreationForm(UserCreationForm):
birth = forms.DateField(
widget=forms.SelectDateWidget(
years=range(1970, 2015)
),
required=True,
)
gender = forms.ChoiceField(choices=GENDER_CHOICES, initial='M')
class Meta(UserCreationForm.Meta):
model = ChachaUser
fields = UserCreationForm.Meta.fields + ('birth', 'gender')
But I want to create a superuser using python manage.py createsuperuser
, I have to implement CustomUserManager
, too.
Any idea or example, please?
There are two modern ways to create a custom user model in Django: AbstractUser and AbstractBaseUser . In both cases we can subclass them to extend existing functionality however AbstractBaseUser requires much, much more work.
To implement a custom authentication scheme, subclass BaseAuthentication and override the . authenticate(self, request) method. The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.
You're interested in UserManager
(code).
Example:
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
# your methods
class CustomUser(AbstractUser):
# fields
objects = CustomUserManager()
You should implement a class that inherits from BaseUserManager
. You must implement methods .create_user
and .create_superuser
. I strongly suggest you to put this class in a file managers.py
in the same app as your custom ChachaUser
model.
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('Email for user must be set.')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self.create_user(email, password, **extra_fields)
For a complete guidance on creating a custom user model using either AbstractUser
or AbstractBaseUser
see this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With