14

I'm using Django 1.7 with Django Rest Framework. I've written an API that detects the login of a user as follows:

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)

I face an error with this view which shows the following traceback

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']

I'm not entirely sure if this is an error in my code or Django's query.py. I'd appreciate help in figuring out the problem here

3
  • You might be having problem with line print fb_uid[0].uid when search returns empty result. Commented May 4, 2015 at 11:33
  • Have you checked SocialAccount.objects.filter actually returns a list that isn't empty? You could try print len(fb_uid) straight after that call. You may need more defensive code to handle when there are no results. Commented May 4, 2015 at 11:34
  • So I just use a try and except. If it's empty. w3schools.com/python/python_try_except.asp Commented Oct 11, 2022 at 6:14

2 Answers 2

25

Try to use the first() method instead of [0] indexing of queryset:

so_account = SocialAccount.objects.filter(user_id=user.id,
                                          provider='facebook').first()
if so_account:
    fb_uid = so_account.uid
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

The return type of filter function is always django.db.models.query.QuerySet. Isn't it possible to get one of the records like so_account[2] if there are more than 2 records in queryset? Then why is it not possible to use so_account[0] if the number of records is one.
It is possible to use so_account[0] if the number of records is one (or more). But if the number of records is zero, then the IndexError will be thrown.
-1

In the django documentation

Says that:

Entry.objects.order_by('headline')[0]
Entry.objects.order_by('headline')[0:1].get()

Note, however, that the first of these will raise IndexError while the second will raise DoesNotExist if no objects match the given criteria. See get() for more details.

So if that is possible that your query will return no data at all. You might want to use Entry.objects.order_by('headline')[0:1].get() instead of its shortcut [0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.