mevaereR
mevaereR

Reputation: 63

Test Django create_user of an AbstractUser without username

I'm trying to test the creation of an user in Django. But my user model is not the standard one (email is the username).

models.py

from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager

class UserManager(AbstractUserManager):
    def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError('Users must have an email address')
        user = self.model(
            email=self.normalize_email(email),
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

class CustomUser(AbstractUser):
    objects = UserManager()
    username = None
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    email = models.EmailField(unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

tests.py

from django.contrib.auth import get_user_model

class CustomUserTests(TestCase):
    def test_create_user(self):
        user = get_user_model()
        utilisateur = user.create_user(
            email='[email protected]',
            password='testpass123',
        )
        self.assertEqual(utilisateur.email, '[email protected]')

Error line 10, in test_create_user utilisateur = user.create_user( AttributeError: type object 'CustomUser' has no attribute 'create_user'

Something is missing but I don't know how to test well this...

Thanks a lot

Upvotes: 2

Views: 528

Answers (1)

AKS
AKS

Reputation: 19841

CustomUser' has no attribute 'create_user'

create_user is not present on the CustomUser model and that's what the error is saying. The method is present on the UserManager and the manager is defined on the user model as objects = UserManager().

So to access the method, you need to use user.objects.create_user.

Upvotes: 4

Related Questions