gpt4 book ai didi

python - 索引错误 : list index out of range in Django

转载 作者:太空狗 更新时间:2023-10-30 01:48:36 26 4
gpt4 key购买 nike

我正在使用 Django 1.7 和 Django Rest Framework。我编写了一个 API 来检测用户的登录,如下所示:

def login_check(request):
user = request.user
if user.is_anonymous():
return HttpResponse(json.dumps({
'success': False
}))
else:
try:
user_obj = UserProfile.objects.get(user__pk=user.id)
except UserProfile.DoesNotExist:
main_obj = User.objects.get(pk=user.id)
user_obj = UserProfile(user=main_obj)
user_obj.save()
fb_uid = SocialAccount.objects.filter(user_id=user.id, provider='facebook')
print fb_uid[0].uid
user_obj.profile_photo_url = "http://graph.facebook.com/{}/picture?width=300&height=300".format(fb_uid[0].uid)
user_obj.save()
serialized = UserProfileSerializer(user_obj)
return Response(serialized.data, status=status.HTTP_200_OK)

我在这个 View 中遇到错误,它显示了以下回溯

IndexError at /loginCheck/
list index out of range
Request Method: GET
Request URL: http://localhost:8000/loginCheck/
Django Version: 1.7.4
Exception Type: IndexError
Exception Value:
list index out of range
Exception Location: f:\App\venv\lib\site-packages\django\db\models\query.py in __getitem__, line 178
Python Executable: f:\App\venv\Scripts\python.exe
Python Version: 2.7.6
Python Path:
['f:\\App',
'f:\\App\\venv\\lib\\site-packages\\psycopg2-2.6-py2.7-win32.egg',
'C:\\WINDOWS\\SYSTEM32\\python27.zip',
'f:\\App\\venv\\DLLs',
'f:\\App\\venv\\lib',
'f:\\App\\venv\\lib\\plat-win',
'f:\\App\\venv\\lib\\lib-tk',
'f:\\App\\venv\\Scripts',
'c:\\Python27\\Lib',
'c:\\Python27\\DLLs',
'c:\\Python27\\Lib\\lib-tk',
'f:\\App\\venv',
'f:\\App\\venv\\lib\\site-packages']

我不完全确定这是我的代码错误还是 Django 的 query.py 错误。如果能帮我解决这里的问题,我将不胜感激

最佳答案

尝试使用 first()方法而不是查询集的 [0] 索引:

so_account = SocialAccount.objects.filter(user_id=user.id,
provider='facebook').first()
if so_account:
fb_uid = so_account.uid
...

关于python - 索引错误 : list index out of range in Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com