在Django-allauth中添加验证码的解决方案有哪些?

8
有没有办法在django-allauth中使用验证码? 我想在标准的电子邮件+密码注册表单上使用验证码。
4个回答

31

我也需要使用django-allauth来实现此功能,并发现使用django-recaptcha包相对简单。

配置django-recaptcha

注册recaptcha账户

将您的设置插入其中。

# settings.py

RECAPTCHA_PUBLIC_KEY = 'xyz'
RECAPTCHA_PRIVATE_KEY = 'xyz'

RECAPTCHA_USE_SSL = True     # Defaults to False

自定义注册表单

安装 django-recaptcha 后,我遵循指南自定义了注册表单。

from django import forms
from captcha.fields import ReCaptchaField

class AllAuthSignupForm(forms.Form):

    captcha = ReCaptchaField()

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

您还需要在settings.py中告诉allauth继承此表单

ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.AllAuthSignupForm'

连接注册表单模板

此时,{{ form.captcha }}{{ form.captcha.errors }}应该在注册模板上下文中可用。

就这样!看起来所有的验证逻辑都被嵌入了ReCaptchaField中。


1
我已经尝试了最新版本的django-allauth,它不需要模板更改。只需在模型中添加新的验证码字段即可。 - webbyfox
太棒了。有没有办法将验证码字段添加到最后?我正在使用django-allauth应用程序。 - Prithviraj Mitra
@PrithvirajMitra,你成功把验证码字段放在最后了吗?我也遇到了同样的问题。 - Zorgan
@Zorgan 不行(使用django-allauth)。所以我不得不使用django-recaptcha包,然后在forms.py中的signupform中,我放置了captcha = ReCaptchaField(attrs={'theme' : 'clean'})。在此之前,我必须导入from captcha.fields import ReCaptchaField - Prithviraj Mitra
django-recaptcha不允许验证码是可选的,因此我为服务器端验证码自己编写了解决方案 https://github.com/praekelt/django-recaptcha/issues/217 - Harry Moreno
我认为对这篇文章的编辑可能是不正确的...请参见https://bhoey.com/blog/integrating-recaptcha-with-django-allauth/,该文章与原始文章相同,并且截至2020年10月仍然有效。 - dangel

3
要将ReCaptcha字段移动到表单底部,只需在验证码字段之前添加其他字段即可。因此,user、email、captcha、password1、password2变成了以下表单:user、email、password1、password2、captcha
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

您只需要按照前面的答案所述,将此表单添加到settings.py文件中即可。

2

您还可以查看表单字段顺序

因此,使用django-allauth的简单注册表单,带有验证码和按您希望的顺序排序的字段,将如下所示:

from allauth.account.forms import SignupForm
from captcha.fields import ReCaptchaField


class MyCustomSignupForm(SignupForm):
    captcha = ReCaptchaField()

    field_order = ['email', 'password1', 'captcha']

在这种情况下,验证码将位于最后。

1
接受的答案大部分都可以,但当我提交注册表单时,它为我生成了这个错误:
save() missing 1 required positional argument: 'user'

为了解决这个问题,您的自定义表单应该像这样。
class AllAuthSignupForm(forms.Form):

    captcha = ReCaptchaField()

    def signup(self, request, user):
        pass

注意:如果自定义注册表单没有signup方法,django-allauth也会发出警告。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接