Reputation: 749
I'm working on an app in which I've made my customized 'User'
model which takes email as user name and it is dependent on another model called 'Company'
. When running command 'python manage.py createsuperuser'
I need that django asks me for company first and create company instance, than asks for User model fields in which 'company'
is a foreign key and then user provides company id possibly '1'
which the user already created when making company object.
I'm trying to implement above by creating management folder in my app, but it doesn't seems to work.
Can anybody please tell me the correct approach to do it.
Thanks in Advance.
Upvotes: 5
Views: 12037
Reputation: 1260
Late but may save time for someone.
I had requirements to override the default createsuperuser
command, After trials & errors & reading the documentation, This worked for me:
INSTALLED_APPS
list.management/
__init__.py
commands/
createsuperuser.py
N.B:. the same name of the default command to replace it, different name to extend it.
my_app.management.commands.createsuperuser.py
, subclass the default command and override its method. from django.contrib.auth.management.commands.createsuperuser import Command as SuperUserCommand
class Command(SuperUserCommand):
## Override properties and methods to customize the command behaviour.
Notes for your specific needs:
company
field as required.Command.handle
method to insert your logics inside it (create comapany, add it to user_data dictionary) .This guide worked for me in django==4.0.6
Upvotes: 1
Reputation: 741
Yes you can, these commands are called management commands and you can write one following guide in docs Writing custom django-admin commands
Asking for user input can be done with input()
function:
#/django/contrib/auth/management/commands/createsuperuser.py
from django.utils.six.moves import input
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:
self.stderr.write("Error: %s" % '; '.join(e.messages))
val = None
return val
Full source code for Django's createsuperuser can be found on Github.
Upvotes: 0
Reputation: 27047
Most definitely! The createsuperuser
function isn't too special; it just creates a user with the is_superuser
flag set to True
. You can write your own method that creates users and sets the superuser flag, along with whatever else you want, by following the instructions in the first link.
Upvotes: 6