我是Django的新手。我正在尝试使用groups
为User
设置factory_boy
字段。默认的User
类有一个字段_groups
。我尝试过设置,但这没有帮助。
class GroupFactory(factory.django.DjangoModelFactory):
class Meta:
model = Group
name = Sequence(lambda n: "group_{0}".format(n))
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda n: "user_{0}".format(n))
password = "test"
first_name = u'ßhamra'
last_name = u'ßhamra'
_groups = factory.SubFactory(GroupFactory)
@classmethod
def _create(cls, model_class, *args, **kwargs):
"""
Override the default ``_create`` with our custom call.
Due to internal behavior or create user create method that forces is_staff kwarg
"""
g = GroupFactory("abc")
manager = cls._get_manager(model_class)
is_staff = kwargs.pop('is_staff', None)
user = manager.create_user(*args, **kwargs)
if is_staff:
user.is_staff = is_staff
user.save()
return user
答案 0 :(得分:7)
以下代码使用标准的django组。您必须使用工厂男孩后期生成来向用户添加组。
工厂
import factory
import django.contrib.auth.models as auth_models
from django.contrib.auth.hashers import make_password
user_password = 'password'
class SubscribedGroupFactory(factory.django.DjangoModelFactory):
class Meta:
model = auth_models.Group
name = 'subscribed'
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = auth_models.User
first_name = "Sophia"
last_name = "Ball"
username = "clowngirl@heaven.com"
password = make_password(user_password)
email = "clowngirl@heaven.com"
is_active = True
@factory.post_generation
def groups(self, create, extracted, **kwargs):
if not create:
return
if extracted:
for group in extracted:
self.groups.add(group)
测试
from app.factories import UserFactory, SubscribedGroupFactory, user_password
class TestCenterTest(TestCase):
def test_test_center_redirect(self):
user = UserFactory.create(groups=(SubscribedGroupFactory.create(),))
self.client.login(username=user.email, password=user_password)
response = self.client.get('/test-center/')
self.assertEqual(302, response.status_code)
答案 1 :(得分:0)
由于Group
与ManyToManyField
的关联User
,您无法使用SubFactory
(仅适用于ForeignKey
字段):with { {1}},SubFactory
将首先创建factory_boy
,然后将其传递给Group
,UserFactory
将其用作User.objects.create(_groups=Group)
。这不会奏效。
请查看文档的Recipes
部分:http://factoryboy.readthedocs.org/en/latest/recipes.html#simple-manytomany
此处,以下代码应该有效:
class UserFactory(factory.django.DjangoModelFactory):
# All other declarations here
groups = factory.List([
factory.RelatedFactory(GroupFactory),
])