Reputation: 5730
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?
Upvotes: 5
Views: 4930
Reputation: 69755
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.
Upvotes: 2
Reputation:
Or this way:
class CustomUser(User):
objects = MyManager()
class Meta(object):
proxy=True
Upvotes: 0
Reputation: 4512
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()
Upvotes: 6