Unable to create superuser with custom model in Django 1.5


my goal is to create a custom model in Django 1.5

# myapp.models.py from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, db_index=True, ) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) company = models.ForeignKey('Company') ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['company'] 

I cannot create superuser because of the company field (models.ForeignKey ('Company') (python manage.py creates superuser). My question is:
How to create a superuser for my application without a company. I tried to create a custom MyUserManager without any success:

 class MyUserManager(BaseUserManager): ... def create_superuser(self, email, company=None, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.save(using=self._db) return user 

Or do I need to create a fake company for this user? Thanks you

+7
source share
2 answers

In this case, there are three ways:

1) Make a connection with comapany No company = models.ForeignKey('Company',null=True) required company = models.ForeignKey('Company',null=True)

2) Add a default company and specify it as the default value for the foreign key field company = models.ForeignKey('Company',default=1) #where 1 is the identifier of the created company

3) Leave the model code as is. Add a fake company for a superuser named, for example, "Superusercompany" set it in the create_superuser method.

UPD: according to your comment 3 will be the best solution so as not to violate your bush logic.

+3
source

Thanks to your feedback, this is the decision I made: Custom MyUserManager, where I created the default company

  def create_superuser(self, email, password, company=None): """ Creates and saves a superuser with the given email and password. """ if not company: company = Company( name="...", address="...", code="...", city="..." ) company.save() user = self.create_user( email, password=password, company=company ) user.is_admin = True user.save(using=self._db) return user 
+2
source

All Articles