python - 在 django 管理面板中注册一个管理员用户,仅使用电子邮件 ID,然后使用电子邮件帐户激活/密码链接开始使用管理面板
问题描述
我从https://github.com/DjangoGirls/djangogirls参考了创建用户电子邮件而不是用户名的用户模型。但是在超级管理员级别,我想添加一个电子邮件地址并设置激活标志,然后发送一封带有密码设置链接的电子邮件。一旦管理员用户单击链接并激活他的帐户,他应该能够登录并开始使用管理面板。
任何指导将不胜感激......在此先感谢......
模型.py
class UserManager(auth_models.BaseUserManager):
def create_user(self, email, password=None):
if email is None:
raise TypeError('Users must have an email address.')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(email, password=password)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin, TimestampedModel):
email = models.EmailField(db_index=True, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_staff = models.BooleanField(default=False, help_text='Allow the user access to the admin site')
is_superuser = models.BooleanField(
default=False,
help_text='User has all permissions'
)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
# def __str__(self):
# if self.first_name == '' and self.last_name == '':
# return '{0}'.format(self.email)
# return '{0} ({1})'.format(self.get_full_name(), self.email)
@property
def token(self):
return self._generate_jwt_token()
def get_full_name(self):
return "{0} {1}".format(self.first_name, self.last_name)
def get_short_name(self):
return self.first_name
def _generate_jwt_token(self):
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
def generate_password(self):
password = User.objects.make_random_password()
self.set_password(password)
self.save()
return password
def email_user(self, from_email=None):
subject= "Welcome to the Site"
message= "Your Credentials are {0} ({1})".format(self.email, self.password)
from_email= settings.DEFAULT_FROM_EMAIL
send_mail(subject, message, from_email, [self.email])
class Meta:
verbose_name="Site Admin"
verbose_name_plural= 'Site Admins'
表格.py
class UserCreationForm(forms.ModelForm):
error_messages = {
'password_mismatch': "The two password fields didn't match.",
}
password1 = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(
label="Password confirmation",
widget=forms.PasswordInput,
help_text="Enter the same password as above, for verification."
)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
解决方案
如果没有您的 models.py 的任何代码,很难判断哪些选项可能是可行的。假设您的 User 模型有一个电子邮件和一个密码字段,既不可为空又是必需的,那么无论如何您都必须提供一个任意密码。您可以使用Django 密码生成器作为第一步,设置激活标志,发送电子邮件,然后让用户做任何您希望用户做的事情。
希望有帮助。对于未来的问题,请包含特定代码。:)
干杯
推荐阅读
- c++ - Omnet++ 中的 .vec 和 .sca 输出有什么区别?
- c# - 在 InitializeComponent 之后未初始化 UWP 绑定
- javascript - ANTLR:遍历 if/elseif/else javascript
- spring-boot - 为外部系统发布 Swagger 文件
- javascript - 如何在 React js 中的模板文字内调用 onclick 函数
- azure - 是否可以查看 Azure 应用服务的重启历史记录?
- javascript - Ajax 不适用于 .htaccess 重写
- php - php can't get the POST data
- python - 如何绘制随机森林的误差和树大小
- airflow - 在 Airflow 中每小时运行 dag