我想在auth管道的末尾添加一个函数,该函数用于检查是否存在" Profiles"该用户的表,如果没有,它将创建一个表。 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 social auth的新手,看起来我错过了一些明显的东西。任何帮助将不胜感激。
答案 0 :(得分:4)
好的,所以我会回答我自己的问题,以防它对将来有用。我不是专家,但现在是:
我正在关注this教程,因为他做了
email = kwargs['details']['email']
我以为我能做到
username = kwargs['details']['username']
但它没有用,它给了我一个KeyError。
然后我尝试了:
username = details['username']
它有效。但是我遇到了一个新问题,详细信息中的用户名就像你的名字姓氏'当我试图获取用户对象
时user_object = User.objects.get(username=username)
未找到,因为用户模型中的用户名是你的姓名和姓名' (没有空格)。
最后我再次阅读了文档,我发现我可以直接使用用户对象,它会被传递给函数" user":
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