Flask and Jinja template throwing error: object of type 'Cursor' has no len()

Question:

I have looked at similar errors but I can not see how they are being fixed unfortunately. I am very new to Flask (Python in general). I built a little search function for my database and the search works. Unless there’s nothing there that matches the search parameter. Then I get a blank line. Instead, I would like to throw a message saying "No result found" or similar.

So in the app.py file I have this search function:

@app.route("/search", methods=["GET", "POST"])
def search():
    query = request.form.get("query")
    questions = list(mongo.db.questions.find({"$text": {"$search": query}}))    
    return render_template("questions.html", questions=questions)

This does work. I can find the posts with various text etc and display them appropriately.

In my HTML file I run a form that returns the search:

 <form action="{{ url_for('search') }}" method="POST">
<input type="text" name="query" id="query" minlength="3" class="validate" required>
<button type="submit">Search</button>
 </form>

This all works currently (I removed the body part from this code, but this should be the minimum,m required to get it working).

Now, on this page I display all the questions that are available to this user. They’re all in a for loop:

  <ul class="collapsible">
        {% for question in questions %}
        <li></li> 
  </ul>

Etc…

Above that for loop I put:

{% if questions|length > 0 %}

Then at the bottom of the </ul> I put this:

{% else %}
<h3>No Questions found matching that search</h3>
{% endif %}

Only when I put the {% if questions|length > 0 %} do things stop working and I get that length error. I really do not know how to solve this one even after searching and seeing similar posts.

Full error traceback:
Traceback (most recent call last):
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflask_compat.py", line 39, in reraise
    raise value
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflask_compat.py", line 39, in reraise
    raise value
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflaskapp.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:UserspauldOneDriveDocumentsGitHubpros_and_consapp.py", line 26, in get_questions
    return render_template("questions.html", questions=questions)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflasktemplating.py", line 137, in render_template
    return _render(
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesflasktemplating.py", line 120, in _render
    rv = template.render(context)
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesjinja2environment.py", line 1090, in render
    self.environment.handle_exception()
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesjinja2environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "C:UserspauldAppDataRoamingPythonPython38site-packagesjinja2_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "C:UserspauldOneDriveDocumentsGitHubpros_and_constemplatesquestions.html", line 1, in top-level template code
    {% extends "base.html" %} {% block content %}
  File "C:UserspauldOneDriveDocumentsGitHubpros_and_constemplatesbase.html", line 100, in top-level template code
    {% block content %} {% endblock %}
  File "C:UserspauldOneDriveDocumentsGitHubpros_and_constemplatesquestions.html", line 23, in block "content"
    {% if questions|length > 0 %}
TypeError: object of type 'Cursor' has no len()
Asked By: Paul Davis

||

Answers:

may be you are missing the {% endfor %} tag in

<ul class="collapsible">
  {% for question in questions %}
    <li></li>

  {% endfor %} {# -- the missing tag -- #}

</ul>

anyway jinja2 offers already an other way to work with loops, it combines the if and for loop in one : {% for .. %} .. {% else %} .. {% endfor %}

refer to this topic https://jinja.palletsprojects.com/en/2.11.x/templates/#for

try the code below :

<ul class="collapsible">

  {% for question in questions %}

    <li>{{ question.. }}</li>

  {% else %}

    <li>No Questions found matching that search</li>

  {% endfor %}
</ul>

Update 1

rather than returning a list in your search() function, try

    # questions = list(mongo.db.questions.find({"$text": {"$search": query}})) 
    # print(questions) 
    # it will return a list object

    questions = mongo.db.questions.find({"$text": {"$search": query}})  # remove 'list()' function
    # print(questions)
    # it will return the appropriate object : Cursor

Update 2

try

{% if questions.count() > 0 %}

instead of

{% if questions|length > 0 %}
Answered By: cizario

I have the same problem. But when I put space after "tasks" and before "length" like this {% if tasks | length > 0 %}, SORTED…

Answered By: Ayhan Uzumcu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.