如何在 Django 密码重置中为密码重置添加用户名和电子邮件选项?

Posted

技术标签:

【中文标题】如何在 Django 密码重置中为密码重置添加用户名和电子邮件选项?【英文标题】:How to add username and e-mail option for password reset in Django password reset? 【发布时间】:2013-05-19 17:07:52 【问题描述】:

我正在使用 Django 内置密码来允许用户重置密码。我的 password_reset_form.html 看起来像这样:

% block title %Reset Password% endblock %

% block content %
<p>Please specify your email address to receive instructions for resetting it.</p>

<form action="" method="post">
    <div style="display:none">
        <input type="hidden" value=" csrf_token " name="csrfmiddlewaretoken">
    </div>
      form.email.errors 
    <p><label for="id_email">E-mail address:</label>  form.email  <input type="submit" value="Reset password" /></p>
</form>
% endblock %

现在,用户可以输入他们的电子邮件地址和密码重置指令发送给用户。我想修改它,以便用户可以输入他们的用户名或电子邮件地址并在电子邮件中接收密码重置指令。我应该直接去 dist-packages 并开始编辑密码重置文件还是应该做其他事情? 如果用户输入用户名,我可以使用用户名找到用户的电子邮件地址:

if not '@' in new_mail:
      email = User.objects.filter(username=new_mail).values_list('email')
      new_mail1 = email[0]

我该怎么做?谢谢

【问题讨论】:

【参考方案1】:

您绝对不应该编辑 dist-packages 文件。内置视图和表单不支持您想要的行为。我认为复制所涉及的视图和表单的实现并修改它们是可以的。将django.contrib.auth.views.password_reset 视图复制到您的视图文件中。将django.contrib.auth.forms.PasswordResetForm 复制到您的表单文件中,并在其中添加用户名字段并修改用户搜索代码以根据指定的内容搜索电子邮件或用户名。将password_reset 视图中使用的表单类更改为新的PasswordResetForm。应该够了。

【讨论】:

【参考方案2】:

我会做这样的事情

% block title %Reset Password% endblock %

% block content %
<p>Please specify your username or email address to receive instructions for resetting it.</p>

<form action="" method="POST">
  % csrf_token %
   form.email.errors 
  <p> form.email.label  form.email  <button type="submit">Reset Password</button></p>
</form>
% endblock %

在您的 POST 变量中,您现在有一个电子邮件或密码。您必须猜测人们是否会更多地使用电子邮件或用户名。基于此,以下应该可以工作

from django.db.models import Q
email = request.POST.get('email, "")
u = User.objects.filter(Q(username=email)|Q(email=email))
if u.count() == 1:
  email_address = u[0].email
  # now you can send the user an email with instructions
if u.count() < 1:
  # invalid username or email
  return
if u.count() > 1:
  # unlikely but lets account for this anyway. I'll leave this up to you
  return

可能有一种更优雅的方式来检查用户,但这种方式基本上只有一个查询,并且可能比在 try/except 块中单独匹配电子邮件和用户名更快。就我个人而言,我更喜欢过滤/计数的检查方式,而不是 try/except,但这不是重点。

【讨论】:

以上是关于如何在 Django 密码重置中为密码重置添加用户名和电子邮件选项?的主要内容,如果未能解决你的问题,请参考以下文章

如何自定义 django rest auth 密码重置电子邮件内容/模板

如何使用 django-rest-auth 和 Mailgun 从 Django 发送密码重置电子邮件

使用 Django 的密码重置通知用户电子邮件无效

Django 在密码重置时不会重定向到正确的路径

Django如何重设Admin密码(转)

在ubuntu ec2实例中拒绝访问用户时如何重置root密码