Adding Captcha to Django project
add django-recaptcha to requirements.txt
Add ‘captcha’ to your installed apps in settings.py
Create your own custom login form. I usually have a custom folder for forms that I am subclassing so project_name/overrides/login/forms.py
from django.contrib.auth import forms as auth_forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
class ProjectLoginForm(auth_forms.AuthenticationForm):
captcha = ReCaptchaField(
public_key=captcha_public_key,
private_key=captcha_private_key,
widget=ReCaptchaV2Checkbox(
attrs={
}
)
)
def __init__(self, *args, **kwargs):
super().__init__(**kwargs)
- Create your own custom login view
project_name/overrides/login/views.py
from django.shortcuts import redirect
from django.contrib.auth import views as auth_views
class ProjectLoginView(auth_views.LoginView):
def __init__(self, *args, **kwargs):
super().__init__(**kwargs)
- Go to urls.py and add in your new subclasses
from project_name.overrides.login.views import ProjectLoginView
from project_name.overrides.login.forms import ProjectLoginForm
- Create a new /account/login url as so
url(r'^account/login/$', ProjectLoginView.as_view(template_name='project_name/login.html', form_class=ProjectLoginForm), name='login')
All done!