【问题标题】:Use an image of an ImageField for an other ImageField. Django将 ImageField 的图像用于另一个 ImageField。姜戈
【发布时间】:2012-11-19 13:01:11
【问题描述】:

我正在使用 django_facebook。每次用户注册 fb 时,她的头像都会加载到一个名为“image”的字段中

在我的 models.py 中,我有一个名为profilpic 的字段,允许用户拥有个人资料图片:

        class UserProfile(FacebookProfileModel):
            user = models.OneToOneField(User)
            profilpic = models.ImageField(upload_to="profilepics/", default="profilepics/shadow_user.jpg")


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

        post_save.connect(create_facebook_profile, sender=User)

我想做的是,当用户在 facebook 上注册时,'profilpic' 取 'image' 的值(即 profilpic 成为 facebook 图片)。

这是我尝试过的:

        def create_facebook_profile(sender, instance, created, **kwargs):
             if not created:
                return
             UserProfile.objects.create(user=instance)
             instance.userprofile.profilpic = instance.userprofile.image
             instance.save()

        post_save.connect(create_facebook_profile, sender=User)

但它不起作用。关于如何实现这一点的任何想法?

非常感谢。

【问题讨论】:

  • instanceUser 对象,而不是UserProfile 对象,因此您需要调用instance.userprofile.save() 而不是instance.save()

标签: python django django-models django-facebook


【解决方案1】:

您在错误的实例上调用了 save 方法。如果你说 instance.save() 它只会调用它的保存方法而不是用户配置文件保存方法。

def create_facebook_profile(sender, instance, created, **kwargs):
             if not created:
                return
             UserProfile.objects.create(user=instance)
             instance.userprofile.profilpic = instance.userprofile.image
             instance.userprofile.save()

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 2010-11-05
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多