Home > Mobile >  The difference between create() method and create_user() in Django
The difference between create() method and create_user() in Django

Time:11-30

I created the user model myself and I don't use Django's default model. To create a user, if I use the create() method, the date field will set value that field, but if I use the create_user() method, I have to give a value to the date field. Why does this happen?

class UserManager(BaseUserManager):
    def create_user(self, email, f_name, l_name, phone, create, password):
        user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone,
                          create=create, )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, f_name, l_name, phone, create, password):
        user = self.create_user(email, f_name, l_name, phone, create, password)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


    class User(AbstractBaseUser):
        f_name = models.CharField(max_length=50)
        l_name = models.CharField(max_length=50, blank=True, null=True, )
        email = models.EmailField(unique=True, blank=True, null=True)
        phone = models.BigIntegerField(blank=True, null=True, )
        data = models.DateTimeField(auto_now_add=True)
        is_active = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
        is_superuser = models.BooleanField(default=False)
        permission = models.ManyToManyField(Permission, related_name='users')
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['phone', 'f_name', 'l_name', 'create']
        objects = UserManager()

CodePudding user response:

Your own create_user() method does't receive and process **extra_fields. **extra_fields are parameters that not specified. In your case email, f_name, l_name, phone, create, password are specified, and the others are **extra_fields.

create_user() and _create_user() methods in django.contrib.auth.models handle **extra_fields like this.

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, email, password, **extra_fields):
        """
        Create and save a user with the given username, email, and password.
        """
        if not username:
            raise ValueError("The given username must be set")
        email = self.normalize_email(email)
        # Lookup the real model class from the global app registry so this
        # manager method can be used in migrations. This is fine because
        # managers are by definition working on the real model.
        GlobalUserModel = apps.get_model(
            self.model._meta.app_label, self.model._meta.object_name
        )
        username = GlobalUserModel.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user

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

And create() method defined in django.db.models.query also receive and process both specified and not specified parameter using **kwargs like this.

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

so if you add **extra_fields in your create_user() method, date will be assigned automatically.

class UserManager(BaseUserManager):
    def create_user(self, email, f_name, l_name, phone, create, password, **extra_fields):
        user = self.model(email=self.normalize_email(email), f_name=f_name, l_name=l_name, phone=phone,
                          create=create, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
  • Related