How to create user from django shell
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 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
Answer for those using django 1.9 or greater since from django.contrib.auth.models import User
has been deprecated (possibly even earlier) but definitely by 1.9.
Instead do: in bash:
python manage.py shell
In the python shell to create a user with a password:
from django.apps import apps
User = apps.get_model('user', 'User')
me = User.objects.create(first_name='john', email='[email protected]') # other_info='other_info', etc.
me.set_password('WhateverIwant') # this will be saved hashed and encrypted
me.save()
If coming from an API you should probably apply a Form as such:
import json
User = get_model('User')
class UserEditForm(BaseModelForm):
"""This allows for validity checking..."""
class Meta:
model = User
fields = [
'first_name', 'password', 'last_name',
'dob', # etc...
]
# collect the data from the API:
post_data = request.POST.dict()
data = {
'first_name': post_data['firstName'],
'last_name': post_data['firstName'],
'password': post_data['password'], etc.
}
dudette = User() # (this is for create if its edit you can get the User by pk with User.objects.get(pk=kwargs.pk))
form = UserEditForm(data, request.FILES, instance=dudette)
if form.is_valid():
dudette = form.save()
else:
dudette = {'success': False, 'message': unicode(form.errors)}
return json.dumps(dudette.json()) # assumes you have a json serializer on the model called def json(self):