Home > Software design >  calling create_superuser and create_user function in abstractuser in DRF
calling create_superuser and create_user function in abstractuser in DRF

Time:10-19

I have customuser model which inherits the Abstratuser from Django. However, I didn't understand the create_user and create_superuser. For eg when is the create_user function is called and when the create_superuser function is called.

The model looks like this.

class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
    def create_user(self,first_name,last_name,email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError("The email must be set")
        first_name = first_name.capitalize()
        last_name = last_name.capitalize()
        email = self.normalize_email(email)

        user = self.model(
            first_name=first_name, last_name=last_name, email=email, **extra_fields
        )
        #user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self.db)
        return user

    def create_superuser(self, first_name,last_name,email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(first_name,last_name,email, password, **extra_fields)


ROLE = (('admin','ADMIN'),('manager','MANAGER'),('staff','STAFF'))
class CustomUser(AbstractUser):
    username = None
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    role = models.CharField(max_length=15, choices=ROLE, default='staff')
    objects = CustomUserManager()

    def __str__(self):
        return self.email

For eg for other regular models like Contacts, we don't write create_contact function inside the model rather we create a post api and write logic inside view and serializer that creates a contact object. But why in CustomUser why we have to create functions explicitly although we again write creating a user logic inside register view. Also, is there any difference using AbstractUser and AbstractBase user.

CodePudding user response:

If you closely inspect the create_user_XYZ(...) methods, you will find that all those methods are creating the User (or YourCustomModel) instances. These methods are nicely separated as they are intended. For example, create_superuser(...) will create a superuser and create_user() will create a normal instance.

Apart from that, when it comes to auth models, we need to set the password, which shouldn't be stored in plain text rather than it must be hashed before saves into DB. So, these create_XYZ methods also handle some extra logic for us.

  • Related