This question is about saving Facebook Profile pictures in the Django model automatically, using https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 library.
Edit:
There are 2 ways to solve this question: Save the URL of the image in CharField()
or Save the image itself using ImageField()
. Both solutions will do.
The above library allows me to create and authenticate users using bearer tokens. I have the created the profile model:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile')
photo = models.FileField(blank=True) # OR
######################################
url = 'facebook.com{user id}/picture/'
photo = models.CharField(default=url)
@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()
Which automatically creates user profiles for each user. Now, I would like to add the following code to save the photo from Facebook. Facebook API requires user id
to get this picture.
photo = 'https://facebook/{user-id}/picture/'
UserProfile.objects.create(user=instance, photo=photo)
The above is not working because
1) I can't figure out where to get the user id
from.
2) The image can't be stored like that, I need to convert it to bytes or some other method.