Opened 7 months ago

Last modified 7 months ago

#35410 closed Bug

Can't Set a Default Value for ForeignKey Field in Custom User Model — at Initial Version

Reported by: Ebram Shehata Owned by: nobody
Component: contrib.auth Version: 5.0
Severity: Normal Keywords: migrations, foreignkey, user, models
Cc: Ebram Shehata Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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"
  1. 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"
  1. 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.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top