﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35410	Can't Set a Default Value for ForeignKey Field in Custom User Model	Ebram Shehata	nobody	"Hello,

So, I'm trying to add a `ForeignKey` field with a default value in a custom user model.
The use case is that each user should be assigned to a department. But all new users
should have a default department with name 'UNASSIGNED'.

- How to reproduce:
1. Create a blank Django project.
2. Create a new 'profiles' app.
3. Register the app in settings.py and point `AUTH_USER_MODEL` to `""profiles.UserProfile""`.

{{{
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ""profiles""
]
AUTH_USER_MODEL = ""profiles.UserProfile""
}}}

4. Add the following models to profiles/models.py:

{{{
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin

from django.db import models


class Department(models.Model):
    name = models.CharField(max_length=256, unique=True)


def unassigned_department():
    return Department.objects.get_or_create(name=""UNASSIGNED"")[0].pk


class UserProfile(AbstractBaseUser, PermissionsMixin):
    department = models.ForeignKey(
        Department,
        on_delete=models.CASCADE,
        default=unassigned_department,
        related_name=""user_profiles"",
    )
    username = models.CharField(max_length=256, unique=True)

    is_active = models.BooleanField(default=True, null=False)
    is_superuser = models.BooleanField(default=False, null=False)
    is_staff = models.BooleanField(default=False, null=False)

    USERNAME_FIELD = ""username""
}}}

5. Run `python manage.py makemigrations`.

You'll get the following error:
`django.db.utils.OperationalError: no such table: profiles_department`

Django versions I tried: 4.2.7 and 5.0.4.

I also noticed that if I inherit from `django.db.models.Model` in `UserProfile` de-register it
from `AUTH_USER_MODEL` setting, I can create migrations successfully and migrate the
database too! I also could create instances that have the default department as expected.
"	Bug	new	contrib.auth	5.0	Normal		migrations, foreignkey, user, models	Ebram Shehata	Unreviewed	0	0	0	0	0	0
