【问题标题】:WTForm with more than one model object具有多个模型对象的 WTForm
【发布时间】:2015-12-18 20:58:19
【问题描述】:

我有一个页面应该同时创建两个不同模型的实例,即,当提交相同的表单时。

我使用 wtforms_alchemy 创建了一个表单,但这仅涵盖一个模型,而不是两个模型:

class RoutineForm(ModelForm):
    class Meta:
        model = Routine
        only = [u'name', u'comment']
        field_args = {u'comment': {'widget': TextArea()}, }

我知道我可以创建一个不从模型继承并包含我需要的所有字段的表单,但为了保持干燥,我如何让 ModelForm 的实例使用两个模型?

【问题讨论】:

    标签: flask sqlalchemy wtforms


    【解决方案1】:

    您可以同时使用多个表单。给每个前缀以确保字段名称在 HTML 中不重叠。验证这两种形式。除了有两个表单对象外,视图和模板其他一切正常。

    class RoutineForm(ModelForm):
        ...
    
    class EventForm(ModelForm):
        ...
    
    @app.route('/make_event', methods=['GET', 'POST'])
    def make_event():
        routine_form = RoutineForm(prefix='routine')
        event_form = EventForm(prefix='event')
    
        if request.method == 'POST' and routine_form.validate() and event_form.validate():
            ...
    
         return render_template('make_event.html', routine_form=routine_form, event_form=event_form)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2012-03-09
      • 2011-10-23
      相关资源
      最近更新 更多