TAGS :Viewed: 16 - Published at: a few seconds ago

[ Python error NameError: global name 'user' is not defined ]

Hi i am new to python and trying to write factory boy test but getting this error

self.client.login(username=user.first_name, password='abc')
NameError: global name 'user' is not defined

class UserFactory(factory.Factory):
class Meta:
    model = User

first_name = factory.Sequence(lambda n: "Agent %03d" % n)
last_name = 'Steve'
email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.first_name)


class UserTest(TestCase):

    user = UserFactory()

    def test_user_login_client(self):
        self.client.login(username=user.first_name, password='some')

Answer 1


user is not a global name, but an attribute of UserTest:

def test_user_login_client(self):
    self.client.login(username=self.user.first_name, password='some')