【问题标题】:What's the best practice in WTForms, using one form class or multiple ones?WTForms 中的最佳实践是什么,使用一个或多个表单类?
【发布时间】:2014-01-29 02:25:17
【问题描述】:

我有一个非常简单的论坛。在一页上 - 带有创建主题的发布表单的主题列表:

<form action="" method="post" name="PostForm">
    {{form.hidden_tag()}}
    {{form.topic(placeholder='New topic'}}
    {{form.message(placeholder='Enter your text here'}}
    <input type="submit">
</form>

另一个页面 - 主题页面,带有在主题中发布消息的表单:

<form action="" method="post" name="PostForm">
    {{form.hidden_tag()}}
    {{form.message(placeholder='Enter your text here'}}
    <input type="submit">
</form>

我已经为所有人准备了表单类:

class PostingForm(Form):
    topic = TextField(validators=[DataRequired()])
    message = TextAreaField(validators=[DataRequired()])

但是在主题页面(没有输入“主题”)我无法通过validate_on_submit。

那么这里最好的方法是什么 - 创建两个类来分隔主题和消息输入,或者以某种方式阻止验证第二页上的主题输入?

【问题讨论】:

    标签: python validation flask wtforms


    【解决方案1】:

    有三种不同的方法可以做到这一点(都可以接受):

    1. 使用两种不同的形式:

      class PostMessageForm(Form):
          message = TextAreaField(validators=[DataRequired()])
      
      class CreateTopicForm(PostMessageForm):
          topic = TextField(validators=[DataRequired()])
      
    2. 删除字段:

      # In the controller that handles topic messages
      form = PostingForm()
      del form.topic
      if form.validate_on_submit():
          # etc.
      
    3. 更改验证器:

      # In the controller that handles topic messages
      form = PostingForm()
      
      # Either mark the field as optional
      form.topic.validators.insert(0, Optional())
      
      # or remove the validator entirely
      form.topic.validators = []
      

    【讨论】:

      猜你喜欢
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多