【问题标题】:Make WTForms set field label from database model使 WTForms 从数据库模型中设置字段标签
【发布时间】:2015-03-31 20:46:26
【问题描述】:

我有三个表:componentsattributesattribute_values。每个组件可以有许多 attribute_values。每个 attribute_value 都属于一个 attribute。是的,这是可怕的 EAV 模式……

我创建了这两种形式:

class AttributeValueForm(Form):
    attribute = HiddenField()
    value = StringField('Value')

class ComponentForm(Form):
    ... non-related fields left out ...
    attribute_values = FieldList(FormField(AttributeValueForm))

这些是 SQLAlchemy 模型:

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))

我的问题是我希望将属性的 name 视为值字段的标签(替换“值”)。我一直在尝试了解 WTForms 如何在内部工作,但我看不到任何明显的方法。

任何提示表示赞赏。如果我只能在呈现值字段时获取 AttributeValue 对象,我什至可以使用仅呈现自定义标签的 hack。

【问题讨论】:

    标签: flask wtforms entity-attribute-value


    【解决方案1】:

    好的,所以我想出了一个解决方案,这有点类似于 adarsh 对他的回答的第二条评论,但覆盖了 FormField 使用的表单的 init

    class AttributeValueForm(Form):
        value = StringField('Unnamed attribute')
    
        def __init__(self, *args, **kwargs):
            super(AttributeValueForm, self).__init__(*args, **kwargs)
            if 'obj' in kwargs and kwargs['obj'] is not None:
                self.value.label.text = kwargs['obj'].attribute.name
    

    【讨论】:

      【解决方案2】:

      您可以考虑使用wtforms-alchemy 中的ModelForm

      你可以很容易地用模型定义表格。

      类似:

      class AttributeValueForm(ModelForm):
          class Meta:
              model = Attribute
              only = (... columns that you want to include ...)
      

      【讨论】:

      • 谢谢,但我不想编辑更改属性类型/名称:我只想更改标签字段的。我已经在 Attribute.name 上使用了 QuerySelectField,它按预期工作。
      • 我对您的问题仍然有些困惑,但如果我理解正确,您可以在构造表单时传递AttributeValue 对象并像这样更改标签吗? form.value.label = attribute_value_object.whatever
      • 每个组件可能有许多 AttributeValues,它们由 WTForms 使用 FieldList 自动填充(参见上面的 ComponentForm)。因此,我无权访问在构造表单后创建每个 AttributeValueForm 实例的 AttributeValue 实例(除非有办法在构造表单后找到用于填充表单的对象?)。当然,我可以访问所有 AttributeValues,但我不知道其中的 哪个 用于填充每个 AttributeValueForm
      猜你喜欢
      • 2015-03-02
      • 2022-10-13
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2016-07-02
      • 2015-09-01
      • 2016-08-11
      • 1970-01-01
      相关资源
      最近更新 更多