我已经成功从facebook api获取了个人资料图片的url。但是我想保存在图片中。
我尝试了一些来自堆栈溢出的代码,但是存储的图像什么都没有。请帮我吗?
这是我的代码
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']
让我知道您还需要其他细节。谢谢!