January 9, 2023

Adding Captcha to Django project

  1. add django-recaptcha to requirements.txt

  2. Add captcha’ to your installed apps in settings.py

  3. 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)
  1. 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)

        
  1. 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
  1. 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!


Previous post
Wash Trading Mousepads I love Icemat glass mousepads. I’ve bought about 5 of them (only because I’ve broken a couple with phones falling on them or
Next post
How to Save A Life When You Are Wealthy Have a doctor friend or a set of concierge doctors in different timezones Buy a fancy EKG machine You’ll
Share this post if you enjoyed it :)
Subscribe to my newsletter to get notified of new posts
Follow Me On Twitter