Django migration failed : the field value was declared with a lazy reference

I am trying to enforce my User's email should be unique. In my app called accounts I have the below models.py where I created a CustomUser. Then the Employeee model below there is a 1:1 relationship to CustomUser.

from django.db import models
from django.conf import settings
from django.contrib.auth.models import AbstractUser


class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
    groups = models.ManyToManyField(
        'auth.Group',
        related_name='customuser_set',  # Unique related_name to avoid conflict
        blank=True,
        help_text='The groups this user belongs to.',
        verbose_name='groups',
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        related_name='customuser_set',  # Unique related_name to avoid conflict
        blank=True,
        help_text='Specific permissions for this user.',
        verbose_name='user permissions',
    )


    def __str__(self):
        return self.username


# Create your models here.
class Employee(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    number_work_hour_per_week = models.FloatField(
        help_text="Number of working hour per week"
    )
    work_hour_limit = models.BooleanField(
        default=False,
        help_text="If true number_work_hour_per_week applies in the time registration",
    )
    flexible_time_registration = models.BooleanField(
        default=True,
        help_text="Allow the user to register working hour flexible without preregistered time",
    )

    def __str__(self):
        return self.user.username

In my settings.py I have overwrite the default User to be accounts.CustomUser

AUTH_USER_MODEL = 'accounts.CustomUser'

When I do python manage.py migrate I get the below error stack

dimsum-dk-py3.10jianwu@localhost:~/webapp/HD_website/website$ poetry run python manage.py migrate accounts zero
Operations to perform:
  Unapply all migrations: accounts
Traceback (most recent call last):
  File "/home/jianwu/webapp/HD_website/website/manage.py", line 22, in <module>
    main()
  File "/home/jianwu/webapp/HD_website/website/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute
    output = self.handle(*args, **options)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 107, in wrapper
    res = handle_func(*args, **kwargs)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 303, in handle
    pre_migrate_apps = pre_migrate_state.apps
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/utils/functional.py", line 47, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/db/migrations/state.py", line 565, in apps
    return StateApps(self.real_apps, self.models)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/db/migrations/state.py", line 636, in __init__
    raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field accounts.Employee.user was declared with a lazy reference to 'accounts.customuser', but app 'accounts' doesn't provide model 'customuser'.
dimsum-dk-py3.10jianwu@localhost:~/webapp/HD_website/website$ poetry run python manage.py makemigrations
No changes detected
dimsum-dk-py3.10jianwu@localhost:~/webapp/HD_website/website$ poetry run python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, catering, contenttypes, emailSubscriber, pos, restaurant, sessions, sites, takeawayWebshop, timeRegistration, webshopCart, webshopCatalog, webshopCustomer
Traceback (most recent call last):
  File "/home/jianwu/webapp/HD_website/website/manage.py", line 22, in <module>
    main()
  File "/home/jianwu/webapp/HD_website/website/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute
    output = self.handle(*args, **options)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/base.py", line 107, in wrapper
    res = handle_func(*args, **kwargs)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 303, in handle
    pre_migrate_apps = pre_migrate_state.apps
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/utils/functional.py", line 47, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/db/migrations/state.py", line 565, in apps
    return StateApps(self.real_apps, self.models)
  File "/home/jianwu/.cache/pypoetry/virtualenvs/dimsum-dk-NvCIYZlw-py3.10/lib/python3.10/site-packages/django/db/migrations/state.py", line 636, in __init__
    raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field accounts.Employee.user was declared with a lazy reference to 'accounts.customuser', but app 'accounts' doesn't provide model 'customuser'.

I am not sure about this error since in settings.py I am pointing AUTH_USER_MODEL = 'accounts.CustomUser', so how come that the error stack say that I in accounts there is no model customuser (when in fact it should be CustomUser)

In my migrations folder under accounts I have 3 py files

0001_initial.py

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name="Employee",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "number_work_hour_per_week",
                    models.FloatField(help_text="Number of working hour per week"),
                ),
                (
                    "work_hour_limit",
                    models.BooleanField(
                        default=False,
                        help_text="If true number_work_hour_per_week applies in the time registration",
                    ),
                ),
                (
                    "flexible_time_registration",
                    models.BooleanField(
                        default=True,
                        help_text="Allow the user to register working hour flexible without preregistered time",
                    ),
                ),
                (
                    "user",
                    models.OneToOneField(
                        on_delete=django.db.models.deletion.CASCADE,
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
        ),
    ]

0002_customuser.py

# Generated by Django 5.1 on 2024-08-18 16:18

import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0001_initial"),
        ("auth", "0012_alter_user_first_name_max_length"),
    ]

    operations = [
        migrations.CreateModel(
            name="CustomUser",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("password", models.CharField(max_length=128, verbose_name="password")),
                (
                    "last_login",
                    models.DateTimeField(
                        blank=True, null=True, verbose_name="last login"
                    ),
                ),
                (
                    "is_superuser",
                    models.BooleanField(
                        default=False,
                        help_text="Designates that this user has all permissions without explicitly assigning them.",
                        verbose_name="superuser status",
                    ),
                ),
                (
                    "username",
                    models.CharField(
                        error_messages={
                            "unique": "A user with that username already exists."
                        },
                        help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
                        max_length=150,
                        unique=True,
                        validators=[
                            django.contrib.auth.validators.UnicodeUsernameValidator()
                        ],
                        verbose_name="username",
                    ),
                ),
                (
                    "first_name",
                    models.CharField(
                        blank=True, max_length=150, verbose_name="first name"
                    ),
                ),
                (
                    "last_name",
                    models.CharField(
                        blank=True, max_length=150, verbose_name="last name"
                    ),
                ),
                (
                    "is_staff",
                    models.BooleanField(
                        default=False,
                        help_text="Designates whether the user can log into this admin site.",
                        verbose_name="staff status",
                    ),
                ),
                (
                    "is_active",
                    models.BooleanField(
                        default=True,
                        help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
                        verbose_name="active",
                    ),
                ),
                (
                    "date_joined",
                    models.DateTimeField(
                        default=django.utils.timezone.now, verbose_name="date joined"
                    ),
                ),
                ("email", models.EmailField(max_length=254, unique=True)),
                (
                    "groups",
                    models.ManyToManyField(
                        blank=True,
                        help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
                        related_name="user_set",
                        related_query_name="user",
                        to="auth.group",
                        verbose_name="groups",
                    ),
                ),
                (
                    "user_permissions",
                    models.ManyToManyField(
                        blank=True,
                        help_text="Specific permissions for this user.",
                        related_name="user_set",
                        related_query_name="user",
                        to="auth.permission",
                        verbose_name="user permissions",
                    ),
                ),
            ],
            options={
                "verbose_name": "user",
                "verbose_name_plural": "users",
                "abstract": False,
            },
            managers=[
                ("objects", django.contrib.auth.models.UserManager()),
            ],
        ),
    ]

and 0003_alter_customuser_groups_and_more.py

# Generated by Django 5.1 on 2024-08-18 16:37

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0002_customuser"),
        ("auth", "0012_alter_user_first_name_max_length"),
    ]

    operations = [
        migrations.AlterField(
            model_name="customuser",
            name="groups",
            field=models.ManyToManyField(
                blank=True,
                help_text="The groups this user belongs to.",
                related_name="customuser_set",
                to="auth.group",
                verbose_name="groups",
            ),
        ),
        migrations.AlterField(
            model_name="customuser",
            name="user_permissions",
            field=models.ManyToManyField(
                blank=True,
                help_text="Specific permissions for this user.",
                related_name="customuser_set",
                to="auth.permission",
                verbose_name="user permissions",
            ),
        ),
    ]

I cannot delete my database since the database is in production.

Back to Top