首页 > 解决方案 > 使用 PasswordResetConfirmView 时如何处理错误

问题描述

我正在使用django.auth.contrib基于会话的身份验证框架。

我已经成功实现了重置密码功能,通过PasswordResetConfirmView该功能需要将有效令牌发送到用户的电子邮件以设置新密码。

 path('password_reset/confirm/<uidb64>/<token>/', 
     auth_views.PasswordResetConfirmView.as_view(
     template_name='accounts/password_reset/password_reset_confirm.html'), 
     name='password_reset_confirm'),

如果令牌有效,这可以正常工作。但是,如果令牌无效(例如不正确或过期),那么我可以预见会得到一个错误:

未找到带有参数 '('', '')' 的 'password_reset_confirm' 的反向操作。尝试了 1 种模式:['accounts/password_reset/confirm/(?P[^/]+)/(?P[^/]+)/$']

为用户处理此异常的最佳做法是什么?理想情况下,我想抓住它并用“对不起,你的令牌无效”来拦截它。django.contrib.auth在框架内是否有现有的方法可以做到这一点?寻找最好的 DRY 方法。

编辑我已经validlink在模板中使用上下文。错误似乎在此之前:

{% block content %}
<h1>{{ title }}</h1>
{% if validlink %}

<p>Please enter your new password twice so we can verify you typed it in correctly.</p>

<form method="post">{% csrf_token %}
<fieldset>
    <div>
        {{ form.new_password1.errors }}
        <label for="id_new_password1">New password:</label>
        {{ form.new_password1 }}
    </div>
    <div>
        {{ form.new_password2.errors }}
        <label for="id_new_password2">Confirm password:</label>
        {{ form.new_password2 }}
    </div>
    <input type="submit" value="Change my password">
</fieldset>
</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 %}

标签: djangodjango-views

解决方案


推荐阅读