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.
You can use django-simple-captcha.
pip install django-simple-captcha
INSTALLED_APPS
in your settings.pypython manage.py migrate
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>
Have your views inherit from a mixin that validates a recaptcha, c.greys solution is probably easier tbh but you may want to do other things with the request outside the template.
import requests
from django.http.response import HttpResponseForbidden
from ipware import get_client_ip
from .settings import RECAPTCHA_KEY, RECAPTCHA_SECRET
class GoogleRecaptchaMixin:
def post(self, request, *args, **kwargs):
g_recaptcha_response = request.POST.get('g-recaptcha-response', None)
client_ip, is_routable = get_client_ip(request)
response = requests.post(
"https://www.google.com/recaptcha/api/siteverify",
data={
"secret": RECAPTCHA_SECRET,
"response": g_recaptcha_response,
"remoteip": client_ip
}
)
response_dict = response.json()
if response_dict.get("success", None):
return super().post(request, *args, **kwargs)
else:
return HttpResponseForbidden(*args, **kwargs)
In the same directory as the code above you would have a settings file with your key and secret or you could directly import from django.conf
#settings.py
from django.conf import settings
RECAPTCHA_SECRET = getattr(settings, "RECAPTCHA_SECRET", '')
RECAPTCHA_KEY = getattr(settings, "RECAPTCHA_KEY", '')
In your template you would have something like:
<form id="form-00" method="post" action="/process">{% csrf_token %}
<button class="g-recaptcha"
data-sitekey="your recaptcha key"
data-callback="formSubmit">Recaptcha this</button>
</form>
<script type="text/javascript" src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
function formSubmit(token) {
document.getElementById("form-00").submit();
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With