2

I'm trying to work through the tutorials for a Django custom user manager. Most of them override create_user() and create_super_user() like the documentation says to do, but this tutorial leaves those two methods alone and instead overrides _create_user()

http://www.caktusgroup.com/blog/2013/08/07/migrating-custom-user-model-django/

Is this correct? What is the difference between overriding _create_user() vs create_user()?

aris
  • 22,725
  • 1
  • 29
  • 33

1 Answers1

3

Here is both of the code of the _create_user, create_super_user and create_user method.

def _create_user(self, username, email, password,
                 is_staff, is_superuser, **extra_fields):
    """
    Creates and saves a User with the given username, email and password.
    """
    now = timezone.now()
    if not username:
        raise ValueError('The given username must be set')
    email = self.normalize_email(email)
    user = self.model(username=username, email=email,
                      is_staff=is_staff, is_active=True,
                      is_superuser=is_superuser, last_login=now,
                      date_joined=now, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_user(self, username, email=None, password=None, **extra_fields):
    return self._create_user(username, email, password, False, False,
                             **extra_fields)

def create_superuser(self, username, email, password, **extra_fields):
    return self._create_user(username, email, password, True, True,
                             **extra_fields)

As you can see that the create_user and create_super_user method is calling the _create_user function. underscore at the beginning of a method means that the function is only for internal use. It is fine to override the internal method, but, according to my opinion, it is better by design to override the public method.

Edwin Lunando
  • 2,726
  • 3
  • 24
  • 33