Reputation: 2952
I extended my user model by adding a mandatory Company
field, so that every user belongs to some company. The Company
field is a foreign key to another model that defines what a company is.
This works great, except for the fact that ./manage createsuperuser
broke, since it doesn't know to add this custom mandatory field.
Turns out that I can add REQUIRED_FIELDS = ['company']
to my custom user model, which will tell createsuperuser
to ask for this field. That's better, but since the company field is a Foreign Key, it asks for an ID of the company, which has to be looked up by anyone using the createsuperuser
command - not exactly user friendly. I want all admins created with the createsuperuser
command to belong to the same company, and for that company to be created automatically if it doesn't exist.
Reading django's documentation on createsuperuser, it mentions the exact thing I want to do, and the exact reason I want to do it:
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.
I'm just not sure where in my project I should be overriding the get_input_data() method.
Edit:
The way I extended the user model is by adding this to models.py of one of my apps (login_app):
class User(AbstractUser):
company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=False, null=False)
and adding this to settings.py:
AUTH_USER_MODEL = 'login_app.User'
Upvotes: 2
Views: 2292
Reputation: 1910
You need to create a custom command, see Django's related documentation here. Try something like below:
from django.contrib.auth.management.commands import createsuperuser
class Command(createsuperuser.Command):
def get_input_data(self, field, message, default=None):
"""
Override this method if you want to customize data inputs or
validation exceptions.
"""
raw_value = input(message)
if default and raw_value == '':
raw_value = default
try:
val = field.clean(raw_value, None)
except exceptions.ValidationError as e:
# here you FK code
return val
Upvotes: 2