Is there any solutions to add captcha to Django-allauth?

人盡茶涼 提交于 2019-11-29 22:32:14

问题


Is there any solutions to use captcha with django-allauth? I want to use captcha on registration form for standard email+password registrations.


回答1:


I too needed to do this with django-allauth and found that implementing the django-recaptcha package to be relatively simple.

Configure django-recaptcha

Sign up for a recaptcha account.

Plug your settings in

# settings.py

RECAPTCHA_PUBLIC_KEY = 'xyz'
RECAPTCHA_PRIVATE_KEY = 'xyz'

RECAPTCHA_USE_SSL = True     # Defaults to False

Customize SignupForm

After installing django-recaptcha, I followed some (seemingly outdated) guidelines for customizing the SignupForm.

from django import forms
from captcha.fields import ReCaptchaField

class AllauthSignupForm(forms.Form):

    captcha = ReCaptchaField()

    def signup(self, request, user):
        """ Required, or else it throws deprecation warnings """
        pass

You also need to tell allauth to inherit from this form in settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.AllauthSignupForm'

Wire up signup form template

{{ form.captcha }} and {{ form.captcha.errors }} should be available on the signup template context at this point.

That was it! Seems like all the validation logic is tucked into the ReCaptchaField.




回答2:


To get the ReCaptcha field to the bottom of the form, simply add the other fields before the captcha field. So what was user, email, captcha, password1, password2 becomes user, email, password1, password2, captcha with this form:

from allauth.account.forms import SignupForm, PasswordField
from django.utils.translation import ugettext_lazy as _
from captcha.fields import ReCaptchaField

class UpdatedSignUpForm(SignupForm):
    password1 = PasswordField(label=_("Password"))
    password2 = PasswordField(label=_("Password (again)"))
    captcha = ReCaptchaField()

    def save(self, request):
        user = super(UpdatedSignUpForm, self).save(request)
        return user

You then just need to add this form into the settings.py file as described in the previous answer.



来源:https://stackoverflow.com/questions/22665211/is-there-any-solutions-to-add-captcha-to-django-allauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!