Django. Python社交认证. 在流程结束时创建用户档案
我想在认证流程的最后加一个功能,这个功能是检查一下用户是否有一个叫“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)
每个用户都必须有一个“Profiles”表。所以,我在流程的最后加了一个功能:
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社交认证还很陌生,感觉我可能漏掉了什么简单的东西。任何帮助都非常感谢。
1 个回答
6
好的,我来回答我自己的问题,希望对将来有人有用。我不是专家,但我来分享一下我的经验:
我在跟着这个教程,结果因为他做了
email = kwargs['details']['email']
我以为我可以这样做
username = kwargs['details']['username']
但是没有成功,出现了一个KeyError的错误。
然后我试了这个:
username = details['username']
结果成功了。不过我又遇到了一个新问题,details字典里的用户名是类似u'Firstname Lastname'这样的格式,而当我试图获取用户对象时
user_object = User.objects.get(username=username)
却找不到,因为用户模型里的用户名是u'FirstnameLastname'(没有空格)。
最后我又看了一遍文档,发现其实我可以直接使用用户对象,它会作为"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