当社交用户在facebook.com上更改其性别时,我使用信号更新性别。 信号很好。我可以注册并登录,性别正在为fb用户更新。
#app/models.py
@receiver(user_signed_up)
@receiver(user_logged_in)
def set_gender(sender, **kwargs):
user = kwargs.pop('user')
extra_data = user.socialaccount_set.filter(provider='facebook')[0].extra_data
gender = extra_data['gender']
if gender == 'male':
user.gender = u'M'
elif gender == 'female':
user.gender = u'F'
user.save()
但我注意到,对于普通账户来说 我尝试在 / accounts / signup 注册或登录 / accounts / login 我收到此错误:
Exception Type: IndexError
Exception Value: list index out of range
然而,普通用户已成功保存到数据库,我在注册和登录后才会出现此错误。
我认为这会导致问题:
extra_data = user.socialaccount_set.filter(provider='facebook')[0].extra_data
答案 0 :(得分:0)
你是对的,这是有问题的一行。你可能想要更像的东西:
from django.db.models import ObjectDoesNotExist
@receiver(user_signed_up)
@receiver(user_logged_in)
def set_gender(sender, **kwargs):
user = kwargs.pop('user')
try:
extra_data = user.socialaccount_set.get(provider="facebook").extra_data
except ObjectDoesNotExist:
pass
else:
gender = extra_data['gender']
if gender == 'male':
user.gender = 'M'
elif gender == 'female':
user.gender = 'F'
user.save()