1

I have a Python 3.7 / Django project using the auth module. I want to write a script to create users, but I'm very confused about how to do it. I have created this

from django.contrib.auth.models import User
import sys

firstarg=sys.argv[1]
secondarg=sys.argv[2]

user=User.objects.create_user(firstarg, password=secondarg)
user.is_superuser=False
user.is_staff=False
user.save()

I would liek to pass a username and password argument to this script. I tried the below

localhost:dental davea$ source venv/bin/activate; python manage.py shell < create_users.py "user1" "password"
/Users/davea/Documents/workspace/dental/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
usage: manage.py shell [-h] [--no-startup] [-i {ipython,bpython,python}]
                       [-c COMMAND] [--version] [-v {0,1,2,3}]
                       [--settings SETTINGS] [--pythonpath PYTHONPATH]
                       [--traceback] [--no-color]
manage.py shell: error: unrecognized arguments: user1 password

but you can see the error it results in. How do I invoke my script from teh command line, while creating the virtual environment it shoudl be running in?

1 Answer 1

3

You should write a custom admin command by creating a class called Command in the directory <app>/management/commands/<your_cmd.py>:

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = 'Adds a user to django'

    def add_arguments(self, parser):
        parser.add_argument('username')
        parser.add_argument('password')

    def handle(self, *args, **options):
        if User.objects.create_user(options['username'], password=options['password']):
            self.stdout.write("Successfully added user {}.".format(options['username']))

This allows you to call

python manage.py your_cmd <username> <password>

to create a new user.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.