如何避免这个"'元组'对象在我的自定义用户模块中没有属性'photo'"错误?

Boe*_*oel 1 python django python-social-auth

我正在尝试存储有关使用facebook登录到我的网站的用户的其他信息,因此我创建了一个UserProfile模型.

这是我定义UserProfile的方式:

models.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    photo = models.TextField()

    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

    post_save.connect(create_user_profile, sender=User)
Run Code Online (Sandbox Code Playgroud)

settings.py

AUTH_PROFILE_MODULE = 'blog.UserProfile'
Run Code Online (Sandbox Code Playgroud)

而且,由于我使用python-social-auth进行身份验证,我正在实现一个自定义管道,用于在UserProfile中存储用户的图像URL.

from blog.models import UserProfile

def get_profile_picture(
    strategy,
    user,
    response,
    details,
    is_new=False,
    *args,
    **kwargs
    ):
    img_url = 'http://graph.facebook.com/%s/picture?type=large' \
        % response['id']
    profile = UserProfile.objects.get_or_create(user = user)
    profile.photo = img_url
    profile.save()
Run Code Online (Sandbox Code Playgroud)

但是我得到了以下错误:'tuple'对象没有属性'photo'

我知道UserProfile具有属性"photo",因为这是该表的定义:

table|blog_userprofile|blog_userprofile|122|CREATE TABLE "blog_userprofile" (
    "id" integer NOT NULL PRIMARY KEY,
    "user_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id"),
    "photo" text NOT NULL
)
Run Code Online (Sandbox Code Playgroud)

那么我的代码出了什么问题呢?

Dan*_*man 5

如错误所述,您的profile变量是元组,而不是UserProfile实例.那是因为get_or_create返回(实例,创建)的元组.