python
  • validation
  • flask
  • wtforms
  • 2014-01-29 22 views 0 likes 
    0

    我有非常簡單的論壇。在一個頁面上 - 用發帖的形式,以創建主題的主題列表:WTForms中的最佳做法是什麼,使用一個表單類還是多個表單類?

    <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。

    那麼這裏最好的方法是什麼 - 創建兩個類來分隔主題和消息輸入,或者以某種方式阻止第二頁主題輸入的驗證?

    回答

    2

    有三種不同的方法來做到這一點(所有的人都可以接受的):

    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 = [] 
      
    相關問題