Randy Tang
Randy Tang

Reputation: 4353

Creating a Django admin account: null value of password

In a Django project, I have the following script to create an admin account:

User.objects.all().delete()
admin = User()
admin.username = 'admin'
admin.password = admin.set_password('admin')
admin.save()

But I got the error message:

psycopg2.IntegrityError: null value in column "password" violates not-null constraint

Why is that?

Upvotes: 3

Views: 547

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52203

.set_password() already sets the password of the given user, so doesn't return anything. Thus, you should just do:

>>> admin.set_password('admin')
>>> admin.save()

Assuming you want to create a user that will have permission for everything, why don't you use .create_superuser() instead:

>>> User.objects.create_superuser(username="admin", password="admin", email=None)

so you don't have to manually set .is_superuser and .is_staff to True.

Upvotes: 4

Seb D.
Seb D.

Reputation: 5195

From the docs:

set_password(raw_password): Sets the user’s password to the given raw string, taking care of the password hashing.

It sets the password for you, and then returns None, so don't assign it back to user.password. In other words, just do:

admin.username = 'admin'
admin.set_password('admin')
admin.save()

Upvotes: 5

Related Questions