flask - Iterate through model fields in jinja template -
i have several models in application, , have views doing same thing (form + tables showing existing records in model), implemented dfferently because of model, different in each case, wondering if possible make generic.
i googled bit , not able find relevant case. achieve:
in view, want go through each object model passed template, example:
return render_template('addstatus.html', form=form, statuses=status.query.all(), target_model="status", fields=status.__mapper__.c.keys())
but want have 1 view, whatever model be, not able know in advance fields of model, number of columns , on.
i want have in view:
{% obj in objects %} {% field in obj.fields %} (not existing) <h1> {{ field }} :: {{ obj.fields.field.value }} {% endfor %} {% endfor %}
is possible? how can achieve that?
you can add method db.model
class (either subclassing or monkeypatching):
from sqlalchemy.orm import class_mapper, columnproperty def columns(self): """return actual columns of sqlalchemy-mapped object""" return [prop.key prop in class_mapper(self.__class__).iterate_properties if isinstance(prop, columnproperty)]
then can use {% col in obj.columns() %}
iterate on column names.
Comments
Post a Comment