我想在 auth 管道的末尾添加一个函数,该函数用于检查该用户是否有“配置文件”表,如果没有,它将创建一个表。 Profiles 模型是一个表,我在其中存储了一些关于用户的额外信息:
class Profiles(models.Model):
user = models.OneToOneField(User, unique=True, null=True)
description = models.CharField(max_length=250, blank=True, null=True)
points = models.SmallIntegerField(default=0)
posts_number = models.SmallIntegerField(default=0)
每个用户都必须有一个配置文件表。所以,我在管道的末尾添加了一个函数:
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
'app.utils.create_profile' #Custom pipeline
)
#utils.py
def create_profile(strategy, details, response, user, *args, **kwargs):
username = kwargs['details']['username']
user_object = User.objects.get(username=username)
if Profiles.ojects.filter(user=user_object).exists():
pass
else:
new_profile = Profiles(user=user_object)
new_profile.save()
return kwargs
我得到错误:
KeyError at /complete/facebook/
'details'
...
utils.py in create_profile
username = kwargs['details']['username']
我是 python 社交身份验证的新手,看起来我遗漏了一些明显的东西。任何帮助将不胜感激。
最佳答案
好的,我会回答我自己的问题,以防将来对某人有用。我不是专家,但它是:
我正在关注 this教程,因为他这样做
email = kwargs['details']['email']
我以为我能做到
username = kwargs['details']['username']
但它没有用,它给了我一个 KeyError。
然后我尝试了:
username = details['username']
它奏效了。但是我遇到了一个新问题,详细信息字典中的用户名类似于 u'Firstname Lastname',当我尝试获取 User 对象时
user_object = User.objects.get(username=username)
没有找到,因为 User 模型中的用户名是 u'FirstnameLastname'(没有空格)。
最后我再次阅读文档,发现我可以直接使用用户对象,它作为“用户”传递给函数:
def create_profile(strategy, details, response, user, *args, **kwargs):
if Profiles.objects.filter(usuario=user).exists():
pass
else:
new_profile = Profiles(user=user)
new_profile.save()
return kwargs
关于python - Django 。 Python 社交认证。在管道末端创建配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000074/