I have the a ForeignKey
field on the User
model.
company = models.ForeignKey('crm.Company')
So every user needs to have a company.
The problem is the create_super_user
method does not have a company
at the start of a project and I get the following error:
django.db.utils.OperationalError: (1054, "Unknown column 'users_user.company_id' in 'field list'")
So would it be best to just create a default Company
and assign it with get_or_create
like:
def create_superuser(self, email, password, **kwargs):
company, created = Company.objects.get_or_create(
name='Default Company',
)
kwargs.setdefault('company', company)
kwargs.setdefault('is_staff', True)
kwargs.setdefault('is_superuser', True)
kwargs.setdefault('is_active', True)
if kwargs.get('is_staff') is not True:
raise ValueError('Superuser must have staff=True')
if kwargs.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True')
return self.create_user(email, password, **kwargs)
The problem may arise when I create a new superuser from command line and the Default company
has changed. Now a new Default Company
will be created.
On the other hand I can make the company
field optional with null=True
but now that breaks the system rules that each user is associated to a company.
How else can I ensure a company has been created already?