Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
Flask & MongoDB - For Loop not working

Having this for Flask:

example = mongo.db.example
got_name = example.find({'name':1})
got_lastname = example.find({'lastname':1})

details = {'name' : got_name, 'lastname' : got_lastname}

return render_template('blabla.html', details=details)

Then the for loop using Jinja in my HTML (wanting it to be a table):

{% for x in details}
<tr>
    <td>{{ x.['name'] }}</td>
    <td>{{ x.['lastname'] }}</td>
</tr>
{% endfor %}

But it won't work, it doesn't display anything in my table. I wrote this example above now, but my code is similar.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You may want to use find_one() instead of find() which returns a cursor to the documents which match the criteria. find_one() returns a single document which can then be used in the dictionary, instead of a cursor:

example = mongo.db.example
doc = example.find_one()

details = { 'name' : doc['name'], 'lastname' : doc['lastname'] }

return render_template('blabla.html', details=details)

Or

example = mongo.db.example
details = example.find_one({}, {'name':1, 'lastname':1})

return render_template('blabla.html', details=details)

And your template will be

<tr>
    <td>{{ details['name'] }}</td>
    <td>{{ details['lastname'] }}</td>
</tr>

If you want to iterate the whole collection and return a list if documents with just the name and lastname fields, then you should use the find() method. If you have a relatively small dataset, the following code will convert the entire result set (Cursor) into a list (everything is pulled into memory):

example = mongo.db.example
details = list(example.find({}, {'name': 1, 'lastname': 1}))

return render_template('blabla.html', details=details)

Then iterate the list in your template

{% for doc in details}
<tr>
    <td>{{ doc['name'] }}</td>
    <td>{{ doc['lastname'] }}</td>
</tr>
{% endfor %}
over 4 years ago · Santiago Trujillo Report

0

Your template would actually have to be more like this:

<tr>
    <td>{{ details['name'] }}</td>
    <td>{{ details['lastname'] }}</td>
</tr>

No loops.

If you had an array of dictionaries, then you could use your initial template.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!