IndexError:列表索引超出范围,Django

时间:2017-10-22 06:25:14

标签: django

def homepage(request):
    if request.user.is_authenticated():
        # get authenticated rfuser
        rfuser = RFUser.objects.filter(user=request.user)[0]
        print rfuser
        # show info of current user
        project_list = rfuser.project_set.all().order_by('project_name')
#       project_list = RFUser.objects.filter(user=request.user).order_by('project_name')
        context_dict = {'projects': project_list}
        return render(request, 'homepage.html', context_dict)
    else:
        return render(request, 'homepage.html')

我收到以下错误:

Internal Server Error: /
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\rfui_web\myaccoutsite\views.py", line 13, in homepage
    rfuser = RFUser.objects.filter(user=request.user)[0]
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 295, in __getitem__
    return list(qs)[0]
IndexError: list index out of range

列表索引超出范围但是找不到原因的原因是,不知道索引是不是由于数组的相关值

1 个答案:

答案 0 :(得分:0)

这是因为您的查询返回一个空的查询集。因此返回IndexError:列表索引超出范围 。如果你想知道查询是否给出了某些东西,请先使用以下方法检查:

if RFUser.objects.filter(user=request.user).exists():
     // then do things which you need