[Fixed]-Create a simple password for unittest user using PASSWORD_HASHERS


self.user = User.objects.create(username='testuser',password='!')
self.user.save() # <--- You need this ;)

OR: from here

self.user = User.objects.create_user(username='user', email='email@example.com', password='pass')


While searching for a solution i found one more thing that would work, allthough i will most probably use Thomas User.objects.create_user solution, as that is really simple.

But for whatever it’s worth, that’s what i came up with:

from django.contrib.auth.hashers import make_password

pwd = make_password('some_password')
self.user = User.objects.create(username='testuser', password = pwd)

Works fine too.

As i just found out this is extremely helpfull when creating fixtures manually. When you create a fixture for testing you probably want a user like this one:

username: user_01
password: password_01

But how do i know what password_01 would look like when it is hashed? That hashed value is what has to be stored in the fixture for testing, and make_password is doing exactly that: it creates password hashes from a password. Just write the return value of make_password('password_01') to the fixture and you’re done.


Leave a comment