如果在 django 中重置密码电子邮件链接错误,则找不到页面(404)错误

Posted

技术标签:

【中文标题】如果在 django 中重置密码电子邮件链接错误,则找不到页面(404)错误【英文标题】:Page not found(404) error if reset password email link is wrong in django 【发布时间】:2018-02-04 06:43:12 【问题描述】:

我正在使用 django 默认密码重置功能。我通过电子邮件获得设置新密码的电子邮件链接。

如果网址正确,那就没问题了。现在,如果我输入了错误或无效的链接,那么我会得到,

The current URL, account/reset/NTQ/4ox-7f135b9b74e7a4aa909fdd/, didn't match any of these.

accounts/urls.py --

url(r'^password_reset/$', auth_views.password_reset, name='password_reset'),
url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]1,13-[0-9A-Za-z]1,20)/$',
    auth_views.password_reset_confirm, name='password_reset_confirm'),
#url(r'^reset/',auth_views.password_reset_confirm, name='empty_password_reset_confirm'),
url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),

模板密码_reset_confirm.html --

% extends 'base.html' %

% block content %
  % if validlink %
    <h3>Change password</h3>
    <form method="post">
      % csrf_token %
       form.as_p 
      <button type="submit">Change password</button>
    </form>
  % else %
    <p>
      The password reset link was invalid, possibly because it has already been used.
      Please request a new password reset.
    </p>
  % endif %
% endblock %

我试过 --

url(r'^reset/',auth_views.password_reset_confirm, name='empty_password_reset_confirm')

但在这种情况下,我会收到AssertionError at /account/reset/NTQ/4ox-7f135b9b74e7a4aa909fdd/

非常感谢任何帮助。

【问题讨论】:

您已经描述了当前的预期行为。但是你想拥有什么呢? 如果 url 错误,它不应该显示 404 错误。相反,它应该显示 password_reset_confirm.html 文件的 else 部分。 【参考方案1】:

您必须修改 url 的正则表达式以使其适用于每个 url

url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]1,13-[0-9A-Za-z]1,23)/$',
    auth_views.password_reset_confirm, name='password_reset_confirm'),

对于您上面提到的示例链接,将起作用。您可以根据您的要求以相同的方式修改正则表达式以适应更多情况。

当您的 url 进入带有错误标记的链接时,它会抛出错误,因此您的模板的 else 部分将显示出来。

【讨论】:

太棒了。有效。但我不知道为什么它是 1,20 而不是 1,23。这是我能看到的唯一变化。 他们必须将其设置为仅此而已。你可以随意修改。 你能再解释一下吗,我不明白这是怎么工作的。你说可以随心所欲地修改,但我怎么知道需要什么修改才能匹配模式。

以上是关于如果在 django 中重置密码电子邮件链接错误,则找不到页面(404)错误的主要内容,如果未能解决你的问题,请参考以下文章

在使用 Django 框架构建的博客 Web 应用程序中单击重置密码时,我没有收到密码重置电子邮件链接

链接到 django 密码重置不显示

Django密码重置生成http链接而不是https

NoReverseMatch at /accounts/password-reset/ 用于 Django 中的密码重置

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

/ password-reset /时的IndexError:重置密码时字符串索引超出范围