使用django-allauth在模型中保存facebook的个人资料图片链接

时间:2018-11-18 20:49:00

标签: django

我正在使用DRF和django-allauth。我正在尝试在模型中保存个人资料图片的链接。第一次通过Facebook登录应用程序时,我得到django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile.user_id。第二次通过Facebook登录我的应用程序时,我得到Not Found: /profile/user/36/并进入我的应用程序。 我真的不知道如何解决它。 这是我的模型。py

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

from allauth.account.signals import user_signed_up, user_logged_in


from allauth.socialaccount.models import SocialAccount
import hashlib


try:
    from django.utils.encoding import force_text
except ImportError:
    from django.utils.encoding import force_unicode as force_text


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile')
    city = models.CharField(max_length=30, blank=True)
    about = models.TextField(blank=True)
    avatar = models.ImageField(upload_to='avatars/', verbose_name='Images', blank=True)
    sound = models.BooleanField(default=False)
    points = models.DecimalField(max_digits=4, decimal_places=2, default=0.00)
    energy = models.IntegerField(default=0)
    avatar_url = models.URLField(max_length=256, blank=True, null=True)

    class Meta:
        db_table = 'user_profile'
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

    def __str__(self):
        return str(self.user)


// GET PICTURE FROM SOCIAL
@receiver(user_logged_in)
def set_initial_user_names(request, user, sociallogin=None, **kwargs):
    preferred_avatar_size_pixels = 256

    if sociallogin:

        if sociallogin.account.provider == 'facebook':
            picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format(
                sociallogin.account.uid, preferred_avatar_size_pixels)

    profile = UserProfile(user=user, avatar_url=picture_url)

    profile.save()


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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.userprofile.save()

0 个答案:

没有答案