2

I'm trying to figure out how to handle this situation in which my user class (which extends AbstractUser) contains a foreign key to another object. For example,

Class Store(models.Model):
    #attributes

Class Employee(AbstractUser):
    store = models.ForeignKey('Store')
    #other attributes

When I run syncdb, I get the error:

django.db.utils.IntegrityError: (1048, "Column 'store_id' cannot be null")

I believe I'm getting this error because it's trying to create a superuser in the syncdb script that is also an employee, and the employee/superuser can't have a null store_id.

If that's true, how does one go about changing this so that either 1) the superuser isn't an "employee", or 2) I can still create a superuser employee without this error? Thanks in advance.

Edit: I would also like to maintain the fact that every employee must have a store, and avoid setting null=true & blank=true in the model definition.

Anthony F.
  • 545
  • 1
  • 5
  • 20
  • You can implement your custom 'pre_save' signal, so every time before you save a user into your DB, you can create it's custom store foreign key – Mihai Zamfir May 22 '14 at 07:00

1 Answers1

0

You can rewrite create_user and create_superuser commands, example:

from django.contrib.auth.models import BaseUserManager

class EmployeeManager(BaseUserManager):

    def create_user(self, email, password=None, **kwargs):
        user = self.model(email=email, **kwargs)
        user.set_password(password)
        user.store = default_user_store
        user.save()
        return user

    def create_superuser(self, email, password, **kwargs):
        user = self.model(
            email=email, is_staff=True, is_superuser=True, **kwargs)
        user.set_password(password)
        user.store = default_superuser_store
        user.save()
        return user

and add objects = EmployeeManager() to your Employee model

zymud
  • 2,221
  • 16
  • 24
  • I won't have time until later tonight to test this out, but thanks for the information. Would I be putting this code into an admin.py file or elsewhere? – Anthony F. May 22 '14 at 14:18
  • no need to put this code into admin.py, by default you can put it in your models.py (where Employee is defined) or into managers.py - near models.py or elsewhere. It`s up to you. – zymud May 22 '14 at 14:33
  • Sorry for taking so long today in getting back to you. It looks like that'll work for me. Thanks. Marked as accepted. – Anthony F. May 22 '14 at 21:49