如何在Django中使用内置的“password_reset”视图?

7
我在urls.py中设置了以下内容。
(r'^password_reset/$', 'django.contrib.auth.views.password_reset'),

但是当我访问 http://127.0.0.1:8000/password_reset/ 时,我收到了错误信息:

NoReverseMatch at /password_reset/
Reverse for 'django.contrib.auth.views.password_reset_done' with arguments '()' and keyword arguments '{}' not found.

我原本期望password_reset_done视图也可以直接使用。那么在这个阶段我该怎么办?

更新

尝试了Blair的解决方案后,我又向前迈进了一步。

(r'^password_reset_done/$', 'django.contrib.auth.views.password_reset_done'),

根据《Django 1.0网站开发》一书,这些内置视图应该可以直接使用,无需进一步麻烦。但是自Django 1.0以来可能已经有所改变......如果有人能够解决这个问题就太好了。谢谢。

为什么有人投了-1票却没有任何解释?这是一个合理的问题!!! - Houman
3个回答

3
我终于找到了解决方案。我认为MVC和MTV模式之间总是存在一些轻微的误解。在MTV(Django)中,View代表控制器,Template代表View。
因此,虽然"Views"更改密码已经内置在盒子里,但实际的模板(外观)仍需由用户生成,而底层的表格(小部件)则由Django自动生成。查看代码后,这一点就变得更加明显。
因此,请在 url.py 中添加以下两行。
(r'^change-password/$', 'django.contrib.auth.views.password_change'), 
(r'^password-changed/$', 'django.contrib.auth.views.password_change_done'),

在myproject/templates/registration目录下添加以下两个文件:
- password_change_done.html
{% extends "base.html" %}
{% block title %}Password Change Successful{% endblock %}
{% block head %}Password Change Completed Successfully{% endblock %}
{% block content %}
    Your password has been changed successfully. Please re-login with your new credentials 
    <a href="/login/">login</a> or go back to the
    <a href="/">main page</a>.
{% endblock %}

password_change_form.html

{% extends "base.html" %}
{% block title %}Change Registration{% endblock %}
{% block head %}Change Registration{% endblock %}
{% block content %}
    <form method="post" action=".">
        {{form.as_p}}
        <input type="submit" value="Change" />
        {% csrf_token %}
    </form>
{% endblock %}

enter image description here


2

Django需要知道用户在password_reset页面完成表单后要重定向到哪个URL。因此,在您的URL配置中添加另一行:

(r'^password_reset_done/$', 'django.contrib.auth.views.password_reset_done'),

我已经按照你的建议做了,现在它显示:在/password_reset/处找不到模板...异常值:registration/password_reset_form.html。如果我必须自己创建模板,这对我来说没有太多意义。我是否漏掉了什么? - Houman
不是很确定,我一直都是创建定制的模板以便与其它网站主题相匹配。话虽如此,在django.contrib.admin应用程序中似乎有一些匹配的模板,因此如果您启用了Django管理界面,则可能会使用它们? - Blair

1
自 Django 1.11 起,password_change 视图已被弃用。

自版本1.11起已弃用:应该使用基于类的 PasswordChangeView 替换 password_change 函数视图。

对我有用的是:

urls.py 中:

from django.contrib.auth import views as auth_views
...
url('^account/change-password/$',
    auth_views.PasswordChangeView.as_view(
        template_name='registration/passwd_change_form.html'),
    name='password_change'),
url(r'^account/password-change-done/$',
    auth_views.PasswordChangeDoneView.as_view(
        template_name='registration/passwd_change_done.html'),
    name='password_change_done'),

然后在registration下添加两个模板:passwd_change_form.htmlpasswd_change_done.html

请注意,我没有使用默认名称,因为某些原因,当我这样做时,它默认为Django管理视图。


谢谢提醒。同样适用于 password_reset,它被替换为 PasswordResetView,我会处理的。 - Chiheb Nexus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接