使WTForms从数据库模型设置字段标签 [英] Make WTForms set field label from database model

查看:54
本文介绍了使WTForms从数据库模型设置字段标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have three tables: components, attributes and attribute_values. Each component can have many attribute_values. Each attribute_value belongs to one attribute. Yeah, it's the dreaded EAV pattern...

我创建了这两种形式:

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

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

这些是SQLAlchemy模型:

These are the 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))

我的问题是我想将属性的 name 视为值字段的标签(替换"Value").我一直在努力思考WTForms在内部的工作方式,但是我看不到任何明显的方法可以做到这一点.

My problem is that I would like to see the name of the attribute as the label of the value field (replacing 'Value'). I've been trying to wrap my head around how WTForms work internally, but I can't see any obvious way to do this.

任何提示表示赞赏.如果我只能在渲染value字段时握住AttributeValue对象,那么我什至可以使用只渲染自定义标签的hack.

Any hints appreciated. I could even do with a hack that just renders a custom label, if I could only get hold of the AttributeValue object while rendering the value field.

推荐答案

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

Ok, so I came up with a solution, which is a bit similar to adarsh's second comment to his answer, but overriding init of the Form used by the FormField:

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

这篇关于使WTForms从数据库模型设置字段标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆