KeyError:request.sessions Django 3

问题描述 投票:-1回答:1

[尝试在Django应用上搜索书籍时,出现KeyError。数据库中没有书籍记录。但是'isbn_list_of_dicts'被分配给request.sessions。似乎是什么问题?如果没有记录,为什么不显示状态消息?

def search(request):
    """Book search based on authors, and/or publisher, and/or title, and/or subject"""
    if request.method == 'GET':
        # create a form instance and populate it with data from the request:
        form = SearchForm(request.GET)
        # print (request.GET['search_value'])
        isbn_list_of_dicts = []

        # check whether it's valid:
        if form.is_valid():
            temp_dict = {}

            # Gets the search values, which is determined by what the user has typed into search bar
            search_values = form.cleaned_data['search_value'].split(" ")
            search_values = list(filter(None, search_values))

            #print ("Search form")
            #print (search_values)


            # calls the query function to get list of dictionaries of book data
            isbn_list_of_dicts = query(search_values, 'all')

            # No such results could be found
            if len(isbn_list_of_dicts) == 0:
                return render(request, 'bookstore/search_results.html', {'books': request.session['isbn_list_of_dicts'], 'status': 'No results could be found :('})

            request.session['isbn_list_of_dicts'] = isbn_list_of_dicts
            request.session.modified = True
            return render(request, 'bookstore/search_results.html', {'books': request.session['isbn_list_of_dicts'] , 'status': 'Search results for "%s"'%(' '.join(search_values))})

# Filters the search results by author
def search_filter_author(request):
    return render(request, 'bookstore/search_filter_author.html', {'books': request.session['isbn_list_of_dicts']})

# Filters the search results by year
def search_filter_year(request):
    return render(request, 'bookstore/search_filter_year.html', {'books': request.session['isbn_list_of_dicts']})

堆栈跟踪:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/bookstore/search/?search_value=Dan+Brown

Django Version: 3.0.2
Python Version: 3.7.4
Installed Applications:
['polls.apps.PollsConfig',
 'bookstore.apps.BookstoreConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
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 (most recent call last):
  File "C:\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Kaleab\Desktop\bookstore\django-bookstore\db-project\bookstore\views.py", line 70, in search
    return render(request, 'bookstore/search_results.html', {'books': request.session['isbn_list_of_dicts'], 'status': 'No results could be found :('})
  File "C:\Python37\lib\site-packages\django\contrib\sessions\backends\base.py", line 64, in __getitem__
    return self._session[key]

Exception Type: KeyError at /bookstore/search/
Exception Value: 'isbn_list_of_dicts'
django keyerror
1个回答
0
投票

我在这里可以理解的是,如果isbn_list_of_dicts的长度为0,您就不会在会话中存储数据。因此,最好在此之前存储它,或者像这样传递变量:

isbn_list_of_dicts = query(search_values, 'all')
# No such results could be found
if len(isbn_list_of_dicts) == 0:
    return render(request, 'bookstore/search_results.html', {'books': isbn_list_of_dicts, 'status': 'No results could be found :('})
© www.soinside.com 2019 - 2024. All rights reserved.