python - Flask-WTF : how pass structered object to form

标签 python flask wtforms

我是 python 和 flask 框架的新手。

我的问题是我必须制作一个编辑页面。所以我需要将所有对象的存在信息传递到一个表单中。 详情:

我的对象有这种结构:

class TVChannel(Document):
    __collection__  = 'tvchannels'
    use_dot_notation = True

    structure = {
        '_id'           : basestring,
        'name'          : unicode,
        'streams'       : {
            'city1': { 
                'adapt' : basestring,
                'hds'   : basestring,
                'hls'   : basestring,
                'rtmp'  : basestring,
            },       
            'city2':  {
                'adapt' : basestring,
                'hds'   : basestring,
                'hls'   : basestring,
                'rtmp'  : basestring,
            }
        }
    }

在 View 中:

channel_obj = db.TVChannel().get_id(channel_id) #load a channel's datas into an object from db
channel     = ChannelForm(request.form, obj=channel_obj) #load channel form

return render_template('channel/new.html',form=channel, channel_id=channel_id)

他们理解 channel_object 的“名称”并像往常一样传递它。但是“流”,他们没有识别并将其传递给这样的东西:

class ChannelForm(Form):    
    _id         = HiddenField()
    name        = TextField(_('channel name'))    
    streams = {
        'city1': { 
            'adapt' : TextField(_('stream adapt link')),
            'hds'   : TextField(_('stream hds link')),
            'hls'   : TextField(_('stream hls link')),
            'rtmp'  : TextField(_('stream rtmp link')),
        },       
        'city2':  {
            'adapt' : TextField(_('stream adapt link')),
            'hds'   : TextField(_('stream hds link')),
            'hls'   : TextField(_('stream hls link')),
            'rtmp'  : TextField(_('stream rtmp link')),
        }
    }

    submit      = SubmitField(_('Save'))

我该怎么办? 或者有没有修改对象数据传递到表单参数的方式?

最佳答案

您可以使用 wtforms.fields.FormField 来使用嵌套表单.在您的情况下,它将是这样的:

class CitiForm(Form):
    adapt = TextField(_('stream adapt link'))
    hds = TextField(_('stream hds link'))
    hls = TextField(_('stream hls link'))
    rtmp = TextField(_('stream rtmp link'))

class ChannelForm(Form):
    _id = HiddenField()
    name = TextField(_('channel name'))
    city1 = FormField(CitiForm)
    city2 = FormField(CitiForm)

关于python - Flask-WTF : how pass structered object to form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12744136/

相关文章:

python - 我们如何在frappe中动态添加子表(ERPNEXT)

python - 如何使用 matplotlib 在饼图上显示实际值而不是百分比

python - Numba jit 和延迟类型

python - Flask session 变量是否跨线程维护状态?

python - 如何获取当前登录 Flask-Login 的用户列表?

python - 为什么 session cookie 在从域提供服务时有效,但在使用 IP 时却无效?

python - 使用带有 GAE 和 Jinja2 的 WTForms,当字段无效时如何获得红色边框?

python - Matplotlib:将原点移动到左上角

python - 如何使用 WTForms 和 SQLAlchemy 填充多对多关系?

python - Flask-Admin:如何使用 on_model_change 更改模型?