Question

I've got very simple forum. On one page - list of topics with posting form to create topics:

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

The other page - topic page with form for posting message in topic:

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

And I've got form class for all:

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

But on the topic page (there is no input "topic") I can't pass validate_on_submit.

So what is the best way here - create two classes to separate topic and message inputs or somehow block validatation for topic input on the second page?

Was it helpful?

Solution

There are three different ways to do this (all of them acceptable):

  1. Use two different forms:

    class PostMessageForm(Form):
        message = TextAreaField(validators=[DataRequired()])
    
    class CreateTopicForm(PostMessageForm):
        topic = TextField(validators=[DataRequired()])
    
  2. Delete the field:

    # In the controller that handles topic messages
    form = PostingForm()
    del form.topic
    if form.validate_on_submit():
        # etc.
    
  3. Alter the validators:

    # 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 = []
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top