Skip to content Skip to sidebar Skip to footer

Django - Changing Auth Username To Autofield Breaks The Code

I've an application where I need to change username field to Autofield. Use-case - I'am building an application where when the users will be created, usernames should be like Cust

Solution 1:

You must create a custom manager for your user model. It can inherit from BaseManager, but not from the default UserManager:

classCustomUserManager(BaseUserManager):
    use_in_migrations = Truedef_create_user(self, email, password, **extra_fields):
        """
        Create and save a user with the given email, and password.
        """
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    defcreate_user(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    defcreate_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') isnotTrue:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') isnotTrue:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


classUser(AbstractUser):
    username = models.BigAutoField(primary_key=True)
    user_id = models.UUIDField(default=uuid.uuid4, unique=True,
                               editable=False)

    objects = CustomUserManager()

    def__str__(self):
        returnstr(self.username)

Note that I've completely removed username, as it doesn't make sense to pass an explicit value for an AutoField.

Post a Comment for "Django - Changing Auth Username To Autofield Breaks The Code"