bltzr75
bltzr75

Reputation: 3

How to create a user in django with custom attributes using create_user?

I'm trying to run a test of the middleware of a django app. Looks like this:

    class TestAuthenticationMiddleware(TestCase):
        @classmethod
        def setUpTestData(cls):
            cls.user = User.objects.create_user('test_user', '[email protected]', 'test_password')

        def setUp(self):
            self.middleware = AuthenticationMiddleware(lambda req: HttpResponse())
            self.client.force_login(self.user)
            self.request = HttpRequest()
            self.request.session = self.client.session

But I'm getting this attribute error:

    queryset = user.get_subscriptions_all()
AttributeError: 'User' object has no attribute 'get_subscriptions_all'

because the User class is defined like this:

User(AbstractBaseUser, LimitHelpers):
    [...]
    def get_subscriptions_all(self):
        return self.subscriptions.all().union(self.account.subscriptions.all())

and on my utils.py:

        @receiver(user_logged_in)
    def callback_user_loggedin(sender, request, user, **kwargs):
        if not user.is_staff and not user.is_superuser:
            # Activating user's language
            saveCodeCountryFromUser(request, user)
            # Updating subscriptions
            queryset = user.get_subscriptions_all()
            for sub in queryset:
                cls = get_subscription_class(sub)
                if cls is not None:
                    cls.callback_user_loggedin()

Any idea about how to use the create_user to include the get_subscriptions_all attr?

Upvotes: 0

Views: 249

Answers (1)

sytech
sytech

Reputation: 41051

You must set the setting AUTH_USER_MODEL = 'myapp.models.User'

See: substituting a custom user model.

Without this setting, Django will continue to use the default builtin User. You should also ensure your tests also have this configuration (if you use a separate config for tests)

Upvotes: 1

Related Questions