定制Django allauth的socialaccount注册表单:添加密码字段

4

我想修改社交账户提供商登录时用户看到的注册表单。

以下是我的自定义注册表单代码:

from allauth.socialaccount.forms import SignupForm
from allauth.account.forms import SetPasswordField, PasswordField


class SocialPasswordedSignupForm(SignupForm):

    password1 = SetPasswordField(label=_("Password"))
    password2 = PasswordField(label=_("Password (again)"))

    def confirm_password(self):
        print('entered confirm_password')
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):
            print('password fields found')
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                print('passwords not equal')
                raise forms.ValidationError(_("You must type the same password"
                                              " each time."))
            print('passwords equal')
            return self.cleaned_data["password1"]
        else:
            print('passwords not found in form')
            raise forms.ValidationError(_("Password not found in form"))

    def signup(self, request, user):
        print('signup in SocialPasswordedSignupForm')
        password = self.confirm_password()
        user.set_password(password)
        user.save()

settings.py:

SOCIALACCOUNT_FORMS = {
    'signup': 'users.forms.SocialPasswordedSignupForm'
}
但问题是,我的注册方法从未被调用,因此confirm_password方法也不会被调用,密码验证也没有进行。也就是说,如果我输入两个不同的密码,第一个密码将被保存。 可能出了什么问题?
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4

您是否将此值设置为SOCIALACCOUNT_AUTO_SIGNUP = False?这是确保在成功验证后,用户被重定向到您的注册表单的方法。

我来到您的链接,因为我必须实现完全相同的功能。以下是我在我的端口上如何完成的。

forms.py

class SocialPasswordedSignupForm(SignupForm):

    password1 = SetPasswordField(max_length=6,label=("Password"))
    password2 = PasswordField(max_length=6, label=("Password (again)"))

    #taken from https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py

    def clean_password2(self):
        if ("password1" in self.cleaned_data and "password2" in self.cleaned_data):
            if (self.cleaned_data["password1"] != self.cleaned_data["password2"]):
                raise forms.ValidationError(("You must type the same password each time."))
        return self.cleaned_data["password2"]

    def signup(self, request, user):
        user.set_password(self.user, self.cleaned_data["password1"])
        user.save()
我得到了一个探索原始代码的想法,它位于https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py,我发现没有像clean_password1()这样的函数,但是有一个clean_password2()函数可以完成预期的工作。所以我将其复制并保持不变,一切都正常工作:) 如果它对您有用,请不要忘记将其接受为答案。

1
我基本上创建了自己的SignupForm类:
from allauth.account.forms import SetPasswordField, PasswordField
from allauth.account import app_settings
from allauth.account.utils import user_field, user_email, user_username
from django.utils.translation import ugettext_lazy as _


class SocialPasswordedSignupForm(BaseSignupForm):

    password1 = SetPasswordField(label=_("Password"))
    password2 = SetPasswordField(label=_("Confirm Password"))

    def __init__(self, *args, **kwargs):
        self.sociallogin = kwargs.pop('sociallogin')
        user = self.sociallogin.user
        # TODO: Should become more generic, not listing
        # a few fixed properties.
        initial = {'email': user_email(user) or '',
                   'username': user_username(user) or '',
                   'first_name': user_field(user, 'first_name') or '',
                   'last_name': user_field(user, 'last_name') or ''}
        kwargs.update({
            'initial': initial,
            'email_required': kwargs.get('email_required',
                                         app_settings.EMAIL_REQUIRED)})
        super(SocialPasswordedSignupForm, self).__init__(*args, **kwargs)

    def save(self, request):
        adapter = get_adapter()
        user = adapter.save_user(request, self.sociallogin, form=self)
        self.custom_signup(request, user)
        return user

    def clean(self):
        super(SocialPasswordedSignupForm, self).clean()
        if "password1" in self.cleaned_data \
                and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] \
                    != self.cleaned_data["password2"]:
                raise forms.ValidationError(_("You must type the same password"
                                              " each time."))

    def raise_duplicate_email_error(self):
        raise forms.ValidationError(
            _("An account already exists with this e-mail address."
              " Please sign in to that account first, then connect"
              " your %s account.")
            % self.sociallogin.account.get_provider().name)

    def custom_signup(self, request, user):
        password = self.cleaned_data['password1']
        user.set_password(password)
        user.save()
我的实现完美地运行了。你们可以比较 socialaccount.forms 中的默认 SignupForm 和我的实现,看看它们之间的区别。

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