如何在Django的createsuperuser命令中移除password2字段?
移除Django createsuperuser命令中的password2字段方法
要实现执行python manage.py createsuperuser时只输入邮箱和一次密码,无需重复确认,需要从自定义用户管理器和重写创建超级用户命令两部分入手,具体步骤如下:
1. 自定义用户管理器(UserManager)
Django自带的BaseUserManager中createsuperuser方法默认要求输入password2做密码确认,我们需要重写该方法,去掉相关逻辑:
在你的app的models.py中添加:
from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('超级用户必须设置is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('超级用户必须设置is_superuser=True') # 直接使用传入的password,无需二次确认 return self.create_user(email, password, **extra_fields) def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('必须设置邮箱字段') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() # 将邮箱设为唯一标识字段 USERNAME_FIELD = 'email' # 无需额外必填字段,留空即可 REQUIRED_FIELDS = [] def __str__(self): return self.email
2. 重写createsuperuser命令
默认命令会提示输入password2,需要自定义命令移除该输入步骤:
在你的app下创建management/commands目录(如果没有的话),新建createsuperuser.py文件:
from django.contrib.auth.management.commands import createsuperuser class Command(createsuperuser.Command): def add_arguments(self, parser): super().add_arguments(parser) # 移除命令行中password2的参数选项 parser._actions = [action for action in parser._actions if action.dest != 'password2'] def handle(self, *args, **options): password = options.get('password') if not password: # 只提示用户输入一次密码 password = self.get_input_data('密码', options) # 绕过原方法的密码验证逻辑,直接赋值 options['password1'] = password options['password2'] = password super().handle(*args, **options)
3. 配置与迁移
在项目的settings.py中指定自定义用户模型:
AUTH_USER_MODEL = '你的app名称.CustomUser'
然后执行数据库迁移:
python manage.py makemigrations python manage.py migrate
完成以上步骤后,再执行python manage.py createsuperuser,就只会要求输入邮箱和一次密码,无需重复确认了。
内容的提问来源于stack exchange,提问作者Nima Asoud
相关产品推荐
相关产品推荐

