Django django.db.utils.IntegrityError: duplicate key value

Viewed 73

I have a problem with simple user model.I wrote a test for email normalize function and in response i've got a " django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists. " When I added a "user.delete()"after "self.assertEqual(user.email, expected)" all test passed.What is wrong ? Is that test creates users with the same username field ?
Models.py

class UserManager(BaseUserManager):
"""Manager for user"""

    def create_user(self, email, password=None, **extra_fields):
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self._db)

        return user


class User(AbstractUser, PermissionsMixin):
    """User model"""
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()
    REQUIRED_FIELDS = []

    USERNAME_FIELD = 'email'

test.py

class ModelTest(TestCase):

def test_create_user_with_email(self):
    """Testing creating user with email address"""
    email = 'testaddress@example.com'
    password = 'testpassword1234'
    user = get_user_model().objects.create_user(
        email=email,
        password=password,
    )
    self.assertEqual(user.email, email)
    self.assertTrue(user.check_password(password))

def test_user_email_normalized(self):
    """Testing email normalize function"""
    test_emails = [
        ['test1@EXAMPLE.Com', 'test1@example.com'],
        ['TesT2@exaMple.com', 'TesT2@example.com'],
    ]
    for email, expected in test_emails:
        user = get_user_model().objects.create_user(email, 'password123')
        self.assertEqual(user.email, expected)
        user.delete()
1 Answers

It creates a user with the same username. You inherited this from the parent model, and did not remove the username field. You should specify this as None, so:

class User(AbstractUser, PermissionsMixin):
    """User model"""
    username = None
    # …

In the tests you thus do not have to delete the user: the system should be capable to register multiple users with each a different email.

Related