Сохранение изображения в Models.ImageField с использованием URL-адреса (URL-адреса изображения профиля), полученного из FacebookAPI. - PullRequest
0 голосов
/ 11 июня 2019

Я успешно получил URL профиля с Facebook api. Но хочу сохранить изображение в виде поля.

Я пробовал код из переполнения стека, но сохраненное изображение ничего не содержит. Помогите мне с этим?

вот мой код

Models.py

class Userinfo (models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length = 200)
    email = models.CharField(max_length = 200)
    city = models.CharField(max_length = 100, null = True)
    headline = models.CharField(max_length = 200, null= True)
    contact_number = models.CharField(max_length = 200,null = True)
    gender = models.IntegerField(null = True)
    image_url = models.CharField(max_length = 500, null = True)
    image_file = models.ImageField(upload_to='media/profile_pics/',blank =True)
    interests = models.CharField(max_length = 400,null = True)
    about = models.CharField(max_length = 400, null = True)
    fb_link = models.CharField(max_length = 400, null = True)
    linkedin_link = models.CharField(max_length = 400, null = True)
    headline = models.CharField(max_length = 100, null = True) 

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if self.image_url and not self.image_file:
            img_temp = NamedTemporaryFile(delete=True)
            img_temp.write(urlopen(self.image_url).read())
            img_temp.flush()
            self.image_file.save(f"image_{self.pk}", File(img_temp))
        super(Userinfo, self).save(*args, **kwargs)

и вот мой взгляд

views.py

def login(request):
    if request.method == 'POST':
        res = json.loads(request.body)
        user = Userinfo.objects.filter(email = res['email'])
        if user :
            userinfo = Userinfo.objects.all().filter(email = res['email'])
        else :
            userinfo = Userinfo.objects.all().filter(email = res['email'])
            if not userinfo:
                userinfo = Userinfo()
                usr = User()
                usr.username = res['name']
                usr.save()
                userinfo.user_id = usr
                userinfo.email = res['email']
                userinfo.name = res['name']
                userinfo.image_url = res['picture']['data']['url']
                    if 'link' in res:
                    userinfo.fb_link = res['link']
                if 'location' in res:
                    userinfo.city = res['location']['name']
                userinfo.save()

        usr = {}
        usr['id'] = userinfo[0].user_id.id
        usr["name"] = userinfo[0].name
        usr["email"] = userinfo[0].email
        usr["city"] = userinfo[0].city
        usr["headline"] = userinfo[0].headline
        usr["contact_number"] = userinfo[0].contact_number
        usr["image_url"] = userinfo[0].image_file.url
        usr["about"] = userinfo[0].about
        usr["fb_link"] = userinfo[0].fb_link
        usr["linkedin_link"] = userinfo[0].linkedin_link
        return JsonResponse ({'user': usr})

Вот мои settings.py

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    )
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
        'fields': 'id,name,email',
        }
SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name',         'email']

дайте мне знать, что вы хотите получить какие-либо дополнительные подробности. Спасибо !!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...