簡體   English   中英

Django的。 Python社交認證。 在管道末端創建配置文件

[英]Django. Python social auth. create profiles at the end of pipeline

我想在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的新手,看起來我錯過了一些明顯的東西。 任何幫助將不勝感激。

好的,我會回答我自己的問題,以防它對將來有用。 我不是專家,但在這里是:

我正在學習這個教程,因為他做到了

 email = kwargs['details']['email']

我以為我能做到

username = kwargs['details']['username']

但它沒有用,它給了我一個KeyError。

然后我嘗試了:

username = details['username']

它奏效了。 但是我遇到了一個新問題,來自詳細信息dict的用戶名就像u'Firstname Lastname',當我試圖獲取User對象時

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM