具有多个模型对象的 WTForm

WTForm with more than one model object

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

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

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

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

您可以同时使用多个表格。给每个前缀以确保字段名称在 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)