我使用django-rest-auth
和django-allauth
使用用户的Facebook个人资料进行用户注册/登录。
现在,我可以从Facebook获取一些标准信息(默认为所有身份验证)。
是否可以检索头像图片列表? 如何在allAuth中制作它?
答案 0 :(得分:17)
如果你想在django模板中获取头像图片:
<img src="{{ user.socialaccount_set.all.0.get_avatar_url }}" />
这是你想要做的吗?
答案 1 :(得分:7)
让我快速描述我是如何做到的(使用all_auth和rest_auth)。
基本上, &#39; allauth =&gt; socialaccount&#39; 提供 user_signed_up 和 user_logged_in 信号。所以你需要抓住他们并获得 sociallogin对象的额外数据并填充您的avatar_url。
#models.py
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, primary_key=True, verbose_name='user', related_name='profile')
avatar_url = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return force_text(self.user.email)
class Meta():
db_table = 'user_profile'
# signals.py
from allauth.account.signals import user_signed_up, user_logged_in
@receiver(user_signed_up)
def social_login_fname_lname_profilepic(sociallogin, user):
preferred_avatar_size_pixels=256
picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format(
hashlib.md5(user.email.encode('UTF-8')).hexdigest(),
preferred_avatar_size_pixels
)
if sociallogin:
# Extract first / last names from social nets and store on User record
if sociallogin.account.provider == 'twitter':
name = sociallogin.account.extra_data['name']
user.first_name = name.split()[0]
user.last_name = name.split()[1]
if sociallogin.account.provider == 'facebook':
f_name = sociallogin.account.extra_data['first_name']
l_name = sociallogin.account.extra_data['last_name']
if f_name:
user.first_name = f_name
if l_name:
user.last_name = l_name
#verified = sociallogin.account.extra_data['verified']
picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format(
sociallogin.account.uid, preferred_avatar_size_pixels)
if sociallogin.account.provider == 'google':
f_name = sociallogin.account.extra_data['given_name']
l_name = sociallogin.account.extra_data['family_name']
if f_name:
user.first_name = f_name
if l_name:
user.last_name = l_name
#verified = sociallogin.account.extra_data['verified_email']
picture_url = sociallogin.account.extra_data['picture']
user.save()
profile = UserProfile(user=user, avatar_url=picture_url)
profile.save()
希望这会对你有所帮助。
答案 2 :(得分:0)
如果您不想使用 Django Signals,您可以从 DefaultSocialAccountAdapter
扩展 allauth.socialaccount.adapter
并覆盖 populate_user
:
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.account.utils import user_field
class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
def populate_user(self, request, sociallogin, data):
user = super().populate_user(request, sociallogin, data)
try:
picture = sociallogin.account.extra_data['picture']
user_field(user, "profile_photo", picture)
except (KeyError, AttributeError):
pass
return user
请注意,您还应该更改 DefaultSocialAccountAdapter
中的 settings.py
:
SOCIALACCOUNT_ADAPTER = 'some_app.path.to.CustomSocialAccountAdapter'