David Peck
David Peck

Reputation: 35

SQLAlchemy model data isn't rendered in Jinja loop

I'm trying to display a menu of items (like a lunch menu) but I can't get them to show up. I added the items via a Flask-Admin page and checked the database to verify that the items actually exist so I know that's not my problem. Why doesn't the menu item data render in the loop?

class MenuItems(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), index=True, unique=True)
    price = db.Column(db.Float(6), unique=False)
    description = db.Column(db.String(140))

@app.route('/menu')
def menu():
    menu_items = MenuItems.query.all()
    return render_template('menu.html', title="Dave's Bread - Menu",  menu_items=menu_items, user=current_user)
{% for item in menu_items %}
  <td>
    <p><strong>{{ menu_items.name }}</strong></p>
    <p>{{ menu_items.description }}</p>
    <p>Price: {{ menu_items.price }}</p>
  </td>
{% endfor %}

Upvotes: 2

Views: 582

Answers (2)

davidism
davidism

Reputation: 127180

You're accessing properties on menu_items inside the loop. You meant to use item to access the properties of each item.

Flask's Jinja environment skips rendering undefined values by default. menu_items doesn't have a description attribute, so Jinja treats it as undefined. You can make it more strict by using a different undefined type.

from jinja2 import StrictUndefined
app.jinja_env.undefined = StrictUndefined

Upvotes: 4

kyle
kyle

Reputation: 442

You can't loop when you use first() because it's returning one item, rather than a list.

In the template you posted, you're looping over every item, but always referring to the list instead of the item (item instead of menu_items).

Upvotes: 0

Related Questions