Flask WTF表单:添加选择框和文本域

7
我正在尝试制作一个Flask表单,生成以下HTML代码:
<input type="text" name="title" class="field">
<textarea class="field"></textarea>
<select name="status">
    <option value="active">Active</option>
    <option value="inactive">Inactive</option>
</select>

到目前为止,由于我刚接触Python,所以只能做到这一步。

  {% from "forms/macros.html" import render_field %}
  <form method="POST" action="." class="form">
  {{ render_field(form.title, class="input text") }}

我的问题是,对于标题字段,我是否已经正确理解了,如果是的话,有人能否请解释一下如何获取文本区域和选择字段?我已经阅读了文档,但几乎无法理解。

1个回答

11

在我看来,最好是在控制器中定义表单而不是模板。
例如表单定义:

class CommentForm(Form):
    language = SelectField(u'What You Want', choices=CAN_BE_FILLED_LATER_ON)
    code     = TextAreaField()

以后您只需要做的就是 -

  1. 通过以下步骤初始化表格:

  2. comment_form = CommentForm()
    
  3. 将其传递给模板:

  4. return render_template('post_show.jinja2.html', comment_form=comment_form)
    
  5. 在模板中渲染表单:

  6. <div class="form-group" id='cg-{{comment_form.email.id}}'>
       {{comment_form.email.label(class='col-lg-2 control-label',for=comment_form.email.id)}} 
       <div class="col-lg-9"> 
         {{comment_form.email(class='form-control')}} 
         <span class="help-block" id='hl-{{comment_form.email.id}}'></span> 
       </div> 
    </div
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接