NOT NULL constraint failed issue when creating a Custom user model with oneToOne Settings Field


I have created a custom user model inheriting the AbstractUser class. This works fine.

But I want to add a Settings Model in my user fields. I used a OneToOneField relation as it seems the most appropriate.

Here is the code:

class Settings(models.Model):
     Define the custom settings of each user like the language, date format etc...
    timezone = models.CharField(max_length=100, blank=False,

class CustomUser(AbstractUser):
    settings = models.OneToOneField(Settings, on_delete=models.CASCADE)

    objects = CustomUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['password']

    def __str__(self):
        return self.username

The problem is that when I want to create a user using my model, I get the above issue:
django.db.utils.IntegrityError: NOT NULL constraint failed: access_customuser.settings_id

I understand that the settings field must be provided, but I am wondering how it can be automatically created when creating a user ?

Many thanks for your help, any suggestion is welcomed :slight_smile:

I’ll answer to myself…

The solution is to instance a Settings in the create_user method defined in the CustomUserManager