In Django I am getting an Integrity Error while testing to create an object

In my Django REST API project I am getting an Integrity Error when I run my tests.

models.py

class Tag(models.Model):
    """Tag for filtering recipes."""
    name = models.CharField(max_length=255)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.name

And here is my test that fails:

def test_create_tag(self):
    user = get_user_model().objects.create_user(email="user@example.com",password="password123")
    tag = models.Tag.objects.create(user=user, name="Tag1")

    self.assertEqual(str(tag), tag.name)

This is the error that I have been getting:

Traceback (most recent call last):
File "/app/core/tests/test_models.py", line 80, in test_create_tag
tag = models.Tag.objects.create(user=user, name="Tag1")

django.db.utils.IntegrityError: null value in column "user_id" of relation "core_tag" violates not-null constraint DETAIL: Failing row contains (1, Tag1, null).

Why while this test running creates an error?

Back to Top