Search code examples
pythondjangorecaptcha

Including captcha in a django form


I'm trying to add Captcha to my Django form. I tried three different libraries but none of them worked for me and i don't know what i'm doing wrong. Here is my last try:

I used this library. My forms.py looks like this:

class NewUserForm(UserCreationForm):
    email = forms.EmailField(required=True)
    captcha = NoReCaptchaField()

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self, commit=True):
        user = super(NewUserForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

This is urls.py: path("login/", views.login_request, name="login").

This is the frontend: login.html: <script src="https://www.google.com/recaptcha/api.js" async defer></script>

I updated my settings.py file, so the error must not be there.


Solution

  • You can use django-simple-captcha.

    1. Install it
    pip install  django-simple-captcha
    
    1. Add captcha to the INSTALLED_APPS in your settings.py
    2. Run python manage.py migrate
    3. Add an entry to your urls.py:
    urlpatterns += [
           path(r'captcha/', include('captcha.urls')),
        ]
    

    in forms.py:

    from django import forms
    from captcha.fields import CaptchaField
        
    class YourForm(forms.Form):
        captcha = CaptchaField()
    

    in template:

    <form action="/your-name/" method="post">
       {% csrf_token %}
       {{ form.captcha }}
       <input type="submit" value="Submit">
    </form>