#35410: Can't Set a Default Value for ForeignKey Field in Custom User Model
-------------------------------------+-------------------------------------
               Reporter:  Ebram      |          Owner:  nobody
  Shehata                            |
                   Type:  Bug        |         Status:  new
              Component:             |        Version:  5.0
  contrib.auth                       |       Keywords:  migrations,
               Severity:  Normal     |  foreignkey, user, models
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 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.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35410>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/0107018f1b612f6e-c35b5762-1d23-4b20-af3a-2ecfad0a85d8-000000%40eu-central-1.amazonses.com.

Reply via email to