django 自定义重置密码表单

use*_*539 4 python django django-forms recaptcha reset-password

我是 django 的初学者(django 1.7 python 2.7)。

我正在尝试在我的 django 重置密码表单中添加不验证码recaptcha

我正在尝试使用这个recaptcha djano 插件

我已按照说明操作并添加了必要的设置:

Installed django-recaptcha to the Python path.

Added captcha to the INSTALLED_APPS setting.

将以下内容添加到我的 settings.py 文件中:

RECAPTCHA_PUBLIC_KEY = '76wtgdfsjhsydt7r5FFGFhgsdfytd656sad75fgh' # fake - for the purpose of this post.
RECAPTCHA_PRIVATE_KEY = '98dfg6df7g56df6gdfgdfg65JHJH656565GFGFGs' # fake - for the purpose of this post.
NOCAPTCHA = True
Run Code Online (Sandbox Code Playgroud)

然后说明建议将验证码添加到表单中,如下所示:

from django import forms
from captcha.fields import ReCaptchaField

class FormWithCaptcha(forms.Form):
    captcha = ReCaptchaField()
Run Code Online (Sandbox Code Playgroud)

如何访问内置的重置密码表单?作为初学者,我怀疑我必须自定义内置的重置密码表单,但我该怎么做?我什至不确定内置的重置密码表单在哪里。如何在重置密码表单中自定义构建或推送到教程的示例会很方便。

我已经搜索过 SO & google,但找不到任何合适的东西。

Ala*_*air 7

您想自定义PasswordReset视图。默认情况下,它使用PasswordResetForm您可以自定义的 。

# in e.g. myapp/forms.py
from django.contrib.auth.forms import PasswordResetForm

class CaptchaPasswordResetForm(PasswordResetForm):
    captcha = ReCaptchaField()
    ...
Run Code Online (Sandbox Code Playgroud)

然后在您的 中urls.py,导入您的表单,并使用form_class来指定表单。

from django.contrib.auth import views as auth_views
from django.urls import path
from web.forms import CaptchaPasswordResetForm

urlpatterns = [
    path("accounts/password_reset/", auth_views.PasswordResetView.as_view(form_class=CaptchaPasswordResetForm)),
]
Run Code Online (Sandbox Code Playgroud)

对于 Django < 1.11,需要自定义password_reset视图的 URL 模式,并设置password_reset_form

from django.contrib.auth import views as auth_views
from myapp.forms import CaptchaPasswordResetForm

urlpatterns = [
    ...
    url(
        r'^password_reset/',
        auth_views.password_reset,
        {'password_reset_form': CaptchaPasswordResetForm},
    )
]
Run Code Online (Sandbox Code Playgroud)

有关在 url 中包含密码重置视图的更多信息,请参阅文档