Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django customize reset password form

I am a beginner in django (django 1.7 python 2.7).

I am trying to add no captcha recaptcha onto my django reset password form.

I am trying to use this recaptcha djano plugin.

I have followed the instructions and added the necessay settings:

Installed django-recaptcha to the Python path.

Added captcha to the INSTALLED_APPS setting.

Added the following to my settings.py file:

RECAPTCHA_PUBLIC_KEY = '76wtgdfsjhsydt7r5FFGFhgsdfytd656sad75fgh' # fake - for the purpose of this post.
RECAPTCHA_PRIVATE_KEY = '98dfg6df7g56df6gdfgdfg65JHJH656565GFGFGs' # fake - for the purpose of this post.
NOCAPTCHA = True

The instructions then advise to add the captcha to the form, like so:

from django import forms
from captcha.fields import ReCaptchaField

class FormWithCaptcha(forms.Form):
    captcha = ReCaptchaField()

How do I access the built in reset password form? As a beginner, I suspect that I have to customise the built in reset password form, but how do I do that? I am not even sure where the built in reset password form is. An example of how to customise the build in reset password form or a push to a tutorial would be handy.

I have searched SO & google, but could not find anything suitable.

like image 711
user3354539 Avatar asked Mar 14 '23 18:03

user3354539


1 Answers

You want to customise the PasswordReset view. By default, it uses the PasswordResetForm, which you can customize.

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

class CaptchaPasswordResetForm(PasswordResetForm):
    captcha = ReCaptchaField()
    ...

Then in your urls.py, import your form, and use the form_class to specify the form.

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)),
]

For Django < 1.11, you need to customise the URL pattern for the password_reset view, and set password_reset_form to

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},
    )
]

For more information about including password reset views in your urls, see the docs.

like image 87
Alasdair Avatar answered Mar 25 '23 08:03

Alasdair