gpt4 book ai didi

django - 如何使用 factory_boy 设置用户组

转载 作者:行者123 更新时间:2023-12-01 09:24:11 27 4
gpt4 key购买 nike

我对 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

最佳答案

下面的代码使用了标准的 django 组。您必须使用 factory boy post generation 向用户添加组。

工厂

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)

关于django - 如何使用 factory_boy 设置用户组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28367637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com