繁体   English   中英

在 django 管理面板中注册一个只有电子邮件 ID 的管理员用户,然后通过电子邮件发送帐户激活/密码链接以开始使用管理面板

[英]register an admin user in django admin panel with only email id and then email account activation/password link to start using the admin panel

我参考了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 密码生成器作为第一步,设置激活标志,发送电子邮件,然后让用户执行您希望用户执行的任何操作。

希望有帮助。 对于未来的问题,请包括特定的代码。 :)

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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