“NoneType”类型的对象在django基于类的ListView中没有len()

时间:2013-12-06 12:07:56

标签: django listview django-class-based-views nonetype

我有以下视图显示搜索记录列表

class ListOfSearchedRecords(LoginRequiredMixin, ListView):
    template_name = 'list_of_searched_records.html'
    context_object_name = 'filtered_records'
    paginate_by = 10

    def get_queryset(self):
        """
        Returns the Records 
        """
        if self.request.method == "GET" and self.request.GET:
            if 'q' in self.request.GET:
              if self.request.GET['q']:
                keyword = self.request.GET.get('q', None)
                log.debug("Filtered keyword: %s", keyword)
                result = Product.objects.order_by('-created').filter(
                  Q(products__name__icontains=keyword))
                if result:
                  return result
                else:
                  return []

    def get_context_data(self, **kwargs):
        context = super(ListOfSearchedRecords, self).get_context_data(**kwargs)
        context.update(
           {
           'context_list':['Data_one', 'Data_two', 'Data_three']}
           )
        return context

回溯

Traceback (most recent call last):
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/views/generic/base.py", line 86, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/views/generic/list.py", line 139, in get
    context = self.get_context_data(object_list=self.object_list)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/views/generic/list.py", line 99, in get_context_data
    paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/views/generic/list.py", line 53, in paginate_queryset
    page = paginator.page(page_number)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/core/paginator.py", line 40, in page
    number = self.validate_number(number)
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/core/paginator.py", line 31, in validate_number
    if number > self.num_pages:
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/core/paginator.py", line 63, in _get_num_pages
    if self.count == 0 and not self.allow_empty_first_page:
  File "/home/user/Envs/proj/local/lib/python2.7/site-packages/django/core/paginator.py", line 56, in _get_count
    self._count = len(self.object_list)
TypeError: object of type 'NoneType' has no len()

SearchForm

                            <form id="changelist-search" class="form-search" action="{% url 'filtered_list_of_records' %}" method="get">
                                <input id="searchbar" name="q" type="text" class="search_ico pull-right search_bar input-xlarge fnt16" placeholder="Search">                                    
                            </form>                                

因此,当我们为搜索输入任何值时,上面的代码正常工作,我的意思是q是否有任何值,但是当我们提交Search form时没有任何内容时,我会遇到错误< / p>

那么为什么我得到它以及如何避免它呢?

1 个答案:

答案 0 :(得分:8)

如果您未在get_queryset中为q填写任何内容,则request.GET方法不会返回任何内容。因此它返回None,它不是有效的QuerySet或iterable。因此,Django无法在其上调用len()

您需要确保get_queryset始终返回值:

def get_queryset(self):
    """
    Returns the Records 
    """
    if self.request.method == "GET" and self.request.GET:
        if 'q' in self.request.GET:
          if self.request.GET['q']:
            # ...
    return [] # add this line here