This one has me completely stumped. I have a model which extends the base User model in Django, so I am writing a custom manage.py
command to create superusers. It seems to be working fine, but for some reason any users that I create via this custom command cannot be authenticated by Django. When I check the database, the users are indeed being created and all of the information is correct.
Here's the code for my custom command in a file called createadmin.py
(I've omitted the bits of code irrelevant to the problem):
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
help = 'Creates a Django admin user'
def handle(self, *args, **options):
username = raw_input('Admin username: ')
password = raw_input('Admin password: ')
try:
new_user = User.objects.create_user(username, password, '')
new_user.is_superuser = True
new_user.is_staff = True
new_user.save()
self.stdout.write('Admin created successfully')
except:
self.stdout.write('Sorry, there was a problem creating a new user in the database.')
Now, if I run this command using python manage.py createadmin
, everything seems to work and the user is created in the database.
To demonstrate the problem, here is the output from testing with createadmin
and shell
:
createadmin
Admin username: testadmin
Admin password: admin
Admin created successfully
shell
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> user = User.objects.get(username='testadmin')
>>> user.is_superuser
True
>>> user.is_active
True
>>> user.is_staff
True
>>> authenticate(username='testadmin', password='admin') is None
True
So as you can see, the user exists, but I cannot authenticate them. I get similar behavior when I try to authenticate the user on the server from within a login
view. Any ideas what could be the problem?
The second positional argument to create_user
is email, not password.
You should use keyword arguments:
new_user = User.objects.create_user(username, password=password)