【问题标题】:object of type 'NoneType' has no len() in django ClassBased ListView'NoneType' 类型的对象在基于 django 类的 ListView 中没有 len()
【发布时间】:2013-12-23 18:45:55
【问题描述】:

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

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()

搜索表单

                            <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 没有任何东西时,我遇到了错误

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

【问题讨论】:

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


    【解决方案1】:

    当您没有在request.GET 中为q 填写内容时,方法get_queryset 不会返回任何内容。因此它返回None,它不是一个有效的QuerySet 或可迭代的。因此 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
    

    【讨论】:

    • 这 3 个 if 可以只替换为一个 if self.request.GET.get('q'):
    • @AlexanderLarikov- 如果找不到 q 会引发什么错误,我认为它只会返回 None 对吗?
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2012-04-30
    • 2021-03-03
    • 2012-08-02
    • 2015-07-30
    • 1970-01-01
    相关资源
    最近更新 更多