# How to create a factory for a Django model with a password

Say you're using the default Django User model, how can you create a factory-boy (opens new window) factory for the model that includes setting a password?

You can use the PostGenerationMethodCall declaration (opens new window) like this:

class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.User
        exclude = ('plaintext_password',)

    email = factory.sequence(lambda n: 'test{}@example.com'.format(n))
    plaintext_password = factory.PostGenerationMethodCall(
        'set_password', 'defaultpassword'
    )
1
2
3
4
5
6
7
8
9

The first argument to PostGenerationMethodCall is the method that needs to be called on the generated object. In this case, set_password (opens new window) which is a Django method to hash and store a password.

The second argument is an optional default value that will be passed to the method above if the plaintext_password value is not provided.

To create a user from the factory with a password 'my-awesome-password', you can run:

user = UserFactory(plaintext_password='my-awesome-password')
1

Newsletter

If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.

Powered by Buttondown.

Last Updated: 11/20/2023, 10:04:51 AM