使用django-allauth中的社交数据预填充自定义表单

时间:2014-10-09 21:00:07

标签: python django django-allauth

在注册期间与Facebook建立联系后,如何在django-allauth中使用额外数据预先填写注册表单?

在我的设置中,我有以下

settings.py

SOCIALACCOUNT_AUTO_SIGNUP = False

假设我有一个UserProfile模型,其中包含一些与用户相关的数据。

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    gender = models.CharField(max_length=1)

如果我使用以下表格,非注册用户可以与Facebook连接并收到填写的注册表(UserSignupForm的实例),其中第一个名称和姓氏已经预先填充。如何使用从Facebook收集的数据自动填写性别? 换句话说,我想使用从facebook额外数据中获取的性别作为注册表单的初始数据。

settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'UserSignupForm'

forms.py

class UserSignupForm(forms.ModelForm):
    first_name = forms.CharField(label=_('First name'), max_length=30)
    last_name = forms.CharField(label=_('Last name'), max_length=30)

    class Meta:
        model = UserProfile
        fields = ['first_name', 'last_name', 'gender']

    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        self.instance.user = user

        self.instance.user.save()
        self.instance.save()

在我看来,我应该更换适配器。

adapter.py

class UserProfileSocialAccountAdapter(DefaultSocialAccountAdapter):
    def populate_user(self, request, sociallogin, data):
        user = super(UserProfileSocialAccountAdapter, self).populate_user(request, sociallogin, data)

        # Take gender from social data
        # The following line is wrong for many reasons
        # (user is not saved in the database, userprofile does not exist)
        # but should give the idea
        # user.userprofile.gender = 'M'

        return user

1 个答案:

答案 0 :(得分:0)

我正在使用不使用适配器的解决方案,但会覆盖注册表单的初始化。

forms.py

class UserSignupForm(forms.ModelForm):
    first_name = forms.CharField(label=_('First name'), max_length=30)
    last_name = forms.CharField(label=_('Last name'), max_length=30)

    class Meta:
        model = UserProfile
        fields = ['first_name', 'last_name', 'gender']

    def __init__(self, *args, **kwargs):
        super(UserSignupForm, self).__init__(*args, **kwargs)
        if hasattr(self, 'sociallogin'):
            if 'gender' in self.sociallogin.account.extra_data:
                if self.sociallogin.account.extra_data['gender'] == 'male':
                    self.initial['gender'] = 'M'
                elif self.sociallogin.account.extra_data['gender'] == 'female':
                    self.initial['gender'] = 'F'