基于Django类的视图中'数据'处的关键错误

时间:2018-09-27 12:38:23

标签: python django

我在数据上遇到关键错误!意味着数据不存在,但我正在访问它,但是我已经为此指定了条件,如果数据为None,则执行此方法,否则仍然会引发错误。还是我错误地处理了错误路径?我应该如何正确处理此错误?请纠正我。

class ApiListView(TemplateView):
        def get(self, request):
            list_view = GetList().get_list_data()
            movie_list= list_view.json()
            cart_list_view = GetCartList().get_list_data(request).json()
            print(request.user)
            print(cart_list_view['data'])


            total = 0
            l = []
            if cart_list_view['data'] is not None:
                for object in cart_list_view['data']:
                    obj = object['cart_id']
                    l.append(obj)
                    total = len(l)
            else:
                pass

            if self.request.session.session_key:
                #session = self.request.session_key
                context = {
                    'movie_list':movie_list,
                    'home_status':'Show LoggedIn Page',
                    'total_items': total,

                           }
                return render(request,'content-list.html' , context)
            else:
                context = {'movie_list':movie_list}
                return render(request, 'content-list.html', context)

回溯错误

Environment:


Request Method: GET
Request URL: http://localhost:8000/

Django Version: 2.1
Python Version: 3.6.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myuser']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "D:\customuser\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "D:\customuser\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "D:\customuser\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\customuser\venv\lib\site-packages\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "D:\customuser\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "D:\customuser\venv\signup\myuser\views.py" in get
  24.         print(cart_list_view['data'])

Exception Type: KeyError at /
Exception Value: 'data'

2 个答案:

答案 0 :(得分:2)

否,这不是您检查字典中是否存在键或是否将代码更改为cart_list_view.get('data')的方式,如果键不存在,或者您可以使用类似{{1 }}

希望有帮助

答案 1 :(得分:2)

回溯显示错误在行print(cart_list_view['data'])上。即在之前检查您是否为None

请注意,如果缺少if cart_list_view['data'] is not None键,data将给出错误。要进行检查,您可以执行以下操作:

if 'data' in cart_list_view:  # check whether key is in data

if cart_list_view.get('data'):  # check that 'data' is in dictionary and is truthy