Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

python - Django - adding google recaptcha v2 to login form

I'm triying to add Recaptcha to my login form in Django. I tried different libraries but none of them seems to work, since the captcha form just doesn't appear in my template.

Here is my current work:

urls.py

path(r'captcha/', include('captcha.urls'))

forms.py

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

    class YourForm(forms.Form):
        captcha = CaptchaField()

    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

And here is my login.html template

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

In this case, only the Submit button will appear, but not the captcha form. This is what happened with any other library I tried. Can anyone give me some help? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@knopch1425 suggestion will invalidate the captcha token only on successful login.

The LoginView form implementation states that the form_valid method is only called after a successful login

def form_valid(self, form):
    """Security check complete. Log the user in."""
    auth_login(self.request, form.get_user())
    return HttpResponseRedirect(self.get_success_url())

Instead you can override the post method in the following manner

def post(self, request, *args, **kwargs):
    request_body = self.request.POST
    if not request_body:
        return None

    recaptcha_token = request_body['g-recaptcha-response']
    ip_addr, _ = get_client_ip(self.request)
    if not _validate_recaptcha(recaptcha_token, ip_addr):
        # your logic
        return redirect('login')

    return super().post(self, request, *args, **kwargs)
 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...