如何使用 POST 数据中的 allauth save_user 方法设置自定义用户字段

How to set custom User field using allauth save_user method from POST data

所以我有 2 种类型的用户,在我网站的其中一个页面上,我想提供额外的字段 cardholder 并在用户注册期间通过 Google[检查它是否正确] =16=]

class DefaultSocialAccountAdapterCustom(DefaultSocialAccountAdapter):

    def save_user(self, request, sociallogin, form=None):
        """Check if it's cardholder registration"""

        user = super().save_user(request, sociallogin, form)

        if request.data.get('cardholder', False): # <-- how to get this POST value??
            user.cardholder = True
            user.save()

        return user

但我收到错误:

'WSGIRequest' object has no attribute 'data'

如何在用户通过社交适配器注册期间从请求中读取 cardholder 值并将用户的持卡人字段设置为 True?

如果你想获取持卡人的POST值,我相信你将不得不执行以下代码....

if request.type == 'POST': cardholder = request.POST['cardholder']

希望对您有所帮助...

我使用 GoogleAuthView 的自定义序列化程序 class 解决了我的问题:

class GoogleAuthView(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    serializer_class = CardholderSocialLoginSerializer

这里我通过覆盖序列化程序的 validate() 方法来设置自定义字段 cardholder,如下所示:

class CardholderSocialLoginSerializer(SocialLoginSerializer):
    """Adds cardholder field for Google registration"""

    cardholder = serializers.BooleanField(required=False, default=False)

    def validate(self, attrs):
        attrs = super().validate(attrs)
        user = attrs['user']
        if attrs.get('cardholder'):
            user.cardholder = True
            user.save()
        return attrs