如果我为测试创建示例用户帐户,则会出现此错误:
未知密码哈希算法'password1'。你有没有指定它? PASSWORD_HASHERS设置?
class ExampleTest(TestCase):
def test_sample_data(self):
for i in range(0,1):
user = content.factories.UserFactory.create()
factories.py:
class UserFactory(factory.Factory):
FACTORY_FOR = User
username = factory.Sequence(lambda n: 'User' + n)
email = 'mail@gmail.com'
password = 'password1'
如何解决?
编辑:
解决方案:
user = content.factories.UserFactory.create()
user.set_password('yourpassword')
user.save()
答案 0 :(得分:1)
更新。在documentation中有描述,您应该使用factory.PostGenerationMethodCall
:
class UserFactory(factory.Factory):
class Meta:
model = User
username = 'user'
password = factory.PostGenerationMethodCall('set_password',
'defaultpassword')
OLD ANSWER 。 实际上,这在factory-boy documentation:
中有所描述class UserFactory(factory.Factory):
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', None)
user = super(UserFactory, cls)._prepare(create, **kwargs)
if password:
user.set_password(password)
if create:
user.save()
return user
更好地使用此解决方案,以便您可以正确使用UserFactory.build()
,UserFactory.create()
和UserFactory.attributes()
(稍后将返回未使用的密码)
答案 1 :(得分:0)
class UserFactory(factory.Factory):
FACTORY_FOR = User
username = 'user'
password = factory.PostGenerationMethodCall('set_password',
'defaultpassword')
请参阅此处的文档https://factoryboy.readthedocs.org/en/v1.3.0/reference.html#postgenerationmethodcall