简体   繁体   中英

Create user in Django : User, Staff, SuperUser

I want to create and save a user with the given username, password, first name, last name and email such as simple user, staff and superuser in models.py and in the front end user can select whether it is simple user, staff or superuser because of some restrictions. Here is my code in models.py . After this code I get some System Check Error.

class CustomUserManager(UserManager):

    def _create_user(self, username, email, password, **extra_fileds):
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        username = self.model.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fileds)
        user.set_password(password)
        user.save(using=self._db)
        return user

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

    def create_superuser(self, username, email, password, **extra_fileds):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', 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(username, email, password, **extra_fileds)

class CustomUser(AbstractUser):
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        # validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    password = models.CharField(_('password'), max_length=128)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    objects = CustomUserManager()

ERRORS:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10a7dd598>
Traceback (most recent call last):
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
    self.check(display_num_errors=True)
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/core/management/base.py", line 410, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:

auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'CustomUser.groups'.
        HINT: Add or change a related_name argument to the definition for 'User.groups' or 'CustomUser.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'CustomUser.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'CustomUser.user_permissions'.
testapp.CustomUser.groups: (fields.E304) Reverse accessor for 'CustomUser.groups' clashes with reverse accessor for 'User.groups'.
        HINT: Add or change a related_name argument to the definition for 'CustomUser.groups' or 'User.groups'.
testapp.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'CustomUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'CustomUser.user_permissions' or 'User.user_permissions'.

System check identified 4 issues (0 silenced).

You should extend abstract AbstractBaseUser and create new modal for user, here I can provide you my code as an example

class UserManager(BaseUserManager):

def create_user(self, username, email, password):
    if not email:
        raise ValueError('Users must have an email address')

    elif not username:
        raise ValueError('Users must have an username')

    user = self.model(
        email=self.normalize_email(email),
        username=username,
    )

    user.set_password(password)
    user.save(using=self._db)
    return user

def create_superuser(self, username, email, password):
    user = self.create_user(
        email=email,
        username=username,
        password=password,
    )
    user.is_admin = True
    user.save(using=self._db)
    return user


class User(AbstractBaseUser):
email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
)
username = models.CharField(
    verbose_name='username',
    max_length=30,
    unique=True,
)

phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13,
                null=True,unique=True)
name = models.CharField(max_length=30, blank=True)

display_username = models.CharField(
    verbose_name='display_username',
    max_length=30,
    unique=True,null= True
)


is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()

# REQUIRED_FIELDS = ['email',]
USERNAME_FIELD = 'email'


def get_full_name(self):
    return self.name

def get_short_name(self):
    return self.name

def __str__(self):
    return self.display_username

def has_perm(self, perm, obj=None):
    return True

def has_module_perms(self, app_label):
    return True

def get_absolute_url(self):
    return reverse('accounts:profile', kwargs={'username': self.username})

@property
def is_staff(self):
    return self.is_admin

In your settings.py

AUTH_USER_MODEL = 'accounts.User' #accounts is your app name

now you can edit user as per you requirement, hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM