【问题标题】:Django. Python social auth. create profiles at the end of pipeline姜戈。 Python 社交身份验证。在管道末端创建配置文件
【发布时间】:2014-09-19 22:13:05
【问题描述】:

我想在身份验证管道的末尾添加一个函数,该函数旨在检查该用户是否有一个“配置文件”表,如果没有,它将创建一个表。 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 social auth 的新手,看起来我遗漏了一些明显的东西。任何帮助将不胜感激。

【问题讨论】:

  • 从您显示的错误跟踪中,似乎 kwargs 缺少密钥 details
  • 嗯,是的,这就是问题所在。我正在关注this 教程,因为他做了email = kwargs['details']['email'] 我想我可以做username = kwargs['details']['username']。无论如何,我通过username = details['username'] 解决了它。但是现在我有一个新问题......'用户匹配查询不存在'。 :P...无论如何。谢谢。

标签: python django python-social-auth


【解决方案1】:

好的,我会回答我自己的问题,以防将来对某人有用。我不是专家,但这里是:

我在关注 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

【讨论】:

  • +1Up。有一个疑问,如果你想传递一些额外的参数,这将在创建配置文件时使用?额外参数的值会因链接而异。?有办法吗?
猜你喜欢
  • 2011-12-09
  • 2014-04-18
  • 2012-12-06
  • 2015-04-13
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多