How to create user from django shell
You should not create the user via the normal User(...)
syntax, as others have suggested. You should always use User.objects.create_user()
, which takes care of setting the password properly.
user@host> manage.py shell
>>> from django.contrib.auth.models import User
>>> user=User.objects.create_user('foo', password='bar')
>>> user.is_superuser=True
>>> user.is_staff=True
>>> user.save()
The fastest way creating of super user for django, type in shell:
python manage.py createsuperuser
To automate the script you can use the pipe feature to execute the list of commands without having to type it out every time.
### content of "create_user.py" file
from django.contrib.auth import get_user_model
# see ref. below
UserModel = get_user_model()
if not UserModel.objects.filter(username='foo').exists():
user=UserModel.objects.create_user('foo', password='bar')
user.is_superuser=True
user.is_staff=True
user.save()
Ref: get_user_model()
Remember to activate VirtualEnv first, then run the command below (for Linux):
cat create_user.py | python manage.py shell
If you using window then substitute the cat command with the type command
type create_user.py | python manage.py shell
OR for both Linux and Windows
# if the script is not in the same path as manage.py, then you must
# specify the absolute path of the "create_user.py"
python manage.py shell < create_user.py
Pitfall: don't include blank lines in any of the indented blocks, think of it as you pasting your code in the REPL. If you have any empty lines it won't work.
You use user.set_password
to set passwords in the django shell. I'm not even sure if directly setting the password via user.password
would even work, since Django expects a hash of the password.
The password
field doesn't store passwords; it stores them as <algorithm>$<iterations>$<salt>$<hash>
, so when it checks a password, it calculates the hash, and compares it. I doubt the user actually has a password whose calculated password hash is in <algorithm>$<iterations>$<salt>$<hash>
form.
If you get the json
with all the information needed to create the User, you could just do
User.objects.create_user(**data)
assuming your passed json is called data.
Note: This will throw an error if you have extra or missing items in data
.
If you really want to override this behavior, you can do
def override_setattr(self,name,value):
if name == 'password':
self.set_password(value)
else:
super().__setattr__(self,name,value) #or however super should be used for your version
User.__setattr__ = override_setattr
I haven't tested this solution, but it should work. Use at your own risk.