Search code examples
pythondjangopython-2.7django-1.7

How to reuse create_user code in create_superuser?


I have a custom BaseUserManager and AbstractBaseUser. I want to reuse the create_user function in AbstractBaseUser for my superuser code since the requirements are the same.

From what I understand, I could pass the arguments passed to create_superuser right over to create_user and then save that locally inside the function, change the is_admin to True and then return it. That would recycle a lot of code and keep things clean. Is this a proper approach?

def create_superuser(self, email, var2, var3, var4, etc...):
    user = create_user(email, var2, var3, var4, etc...)
    user.is_admin = True
    user.save(using=self._db)
    return user

I'm mostly wondering if calling user.save(using=self._db) twice, once in create_user and once in create_superuser on the same user is safe?


Solution

  • Taking a look at how Django did it:

    class MyCustomUserManager(models.Manager):
        def _create_user(self, email, is_staff, is_superuser, ...):
            ...
    
        def create_user(self, email, ...):
            return self._create_user(email, False, False, ...)
    
        def create_superuser(self, email, ...):
            return self._create_user(email, True, True, ...)
    

    This will minimize both extra code and database access. While there is nothing particularly wrong with saving the user twice, it is utterly unnecessary.