Reputation: 115
I have UserManager class below:
class UserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError(_('The Email 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)
extra_fields.setdefault('is_active', 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)
In the create_superuser function, i would like to add one more field to set tenant_id. This has to be taken from the command line, when using python manage.py createsuperuser
.
If i add tenant_id in create_superuser function like this:
create_superuser(self, email, password, tenant_id, **extra_fields):
I'm getting the following error
UserManager.create_superuser() missing 1 required positional argument: 'tenant_id'.
Is there any way i can pass tenant_id from command line?
Upvotes: 1
Views: 1244
Reputation: 16666
Feras Alfrih's suggestion with REQUIRED_FIELDS
is one way as suggested in the documentation.
Another possibility:
You can subclass the management command and override get_input_data() if you want to customize data input and validation. Consult the source code for details on the existing implementation and the method’s parameters. For example, it could be useful if you have a ForeignKey in REQUIRED_FIELDS and want to allow creating an instance instead of entering the primary key of an existing instance.
See https://docs.djangoproject.com/en/4.0/ref/django-admin/#createsuperuser
Upvotes: 0
Reputation: 520
have you tried to add it to create user aswell, like this:
class UserManager(BaseUserManager):
def create_user(self, tenant_id email, password, **extra_fields):
if not email:
raise ValueError(_("The Email 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, tenant_id email, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
extra_fields.setdefault("is_active", 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(tenant_id email, password, **extra_fields)
and in models.py insert these lines:
REQUIRED_FIELDS = ['tenant_id', 'email', 'password']
objects = UserManager()
Upvotes: 1