flask - Make WTForms set field label from database model -
i have 3 tables: components, attributes , attribute_values. each component can have many attribute_values. each attribute_value belongs 1 attribute. yeah, it's dreaded eav pattern...
i have created these 2 forms:
class attributevalueform(form): attribute = hiddenfield() value = stringfield('value') class componentform(form): ... non-related fields left out ... attribute_values = fieldlist(formfield(attributevalueform)) these sqlalchemy models:
class component(db.model): __tablename__ = 'components' id = db.column(db.integer, primary_key=true) ... non-related columns left out ... class attributevalue(db.model): __tablename__ = 'attribute_values' id = db.column(db.integer, primary_key=true) value = db.column(db.string) attribute_id = db.column(db.integer, db.foreignkey('attributes.id')) attribute = db.relationship('attribute', backref='attribute_values')) component_id = db.column(db.integer, db.foreignkey('components.id')) component = db.relationship('component', backref='attribute_values')) def attribute(db.model): __tablename__ = 'attributes' id = db.column(db.integer, primary_key=true) name = db.column(db.string(60)) my problem see name of attribute label of value field (replacing 'value'). i've been trying wrap head around how wtforms work internally, can't see obvious way this.
any hints appreciated. hack renders custom label, if hold of attributevalue object while rendering value field.
ok, came solution, bit similar adarsh's second comment answer, overriding init of form used formfield:
class attributevalueform(form): value = stringfield('unnamed attribute') def __init__(self, *args, **kwargs): super(attributevalueform, self).__init__(*args, **kwargs) if 'obj' in kwargs , kwargs['obj'] not none: self.value.label.text = kwargs['obj'].attribute.name
Comments
Post a Comment