Question

I have two flask forms to create books and authors on my apps. Both of them work only if all fields are filled, whereas I want only one or two strictly required!

The author class :

class AuthorForm(Form):
familyname = TextField('familyname', validators = [Required()])
firstname = TextField('firstname', validators = [Required()])
biography = TextAreaField('biography')
dateofbirth = DateField('dateofbirth')
placeofbirth = TextField('placeofbirth')
nationality = TextField('nationality')
website = TextField('website')

The template:

<form action="" method="post" name="add_author">
    {{form.hidden_tag()}}
    <p>Veuillez donner son prénom (obligatoire) : {{form.firstname}}</p>
    <p>Nom de famille (obligatoire) : {{form.familyname}}</p>
    <p>Nationalité : {{form.nationality}}</p>
    <p>Lieu de naissance : {{form.placeofbirth}}</p>
    <p>Date de naissance (Y-m-d): {{form.dateofbirth}}</p>
    <p>Site web : {{form.website}}</p>
    <p>Biographie : {{form.biography}}</p>
   <p><input type="submit" value="Envoyer"></p>
</form>
{% endblock %}

And the view :

@app.route('/add_author', methods = ['GET', 'POST'])
def add_author():
form = AuthorForm()
if form.validate_on_submit():
    a = Author(firstname= form.firstname.data,
    familyname= form.familyname.data,
    nationality= form.nationality.data,
    dateofbirth= form.dateofbirth.data,
    placeofbirth = form.placeofbirth.data,
    website = form.website.data,
    biography = form.biography.data)
    db.session.add(a)
    db.session.commit()
    return redirect('/index')
return render_template('add_author.html', title = 'Ajouter un auteur a la base de donnees', form = form)
Was it helpful?

Solution

I use WTForms in the Flask app I'm building, and my forms work fine. However I use slightly different syntax:

deadline = TextField('Deadline',[validators.Required()])

notice the dot notation in validators, maybe this is something that's causing your problem?

I checked it now and it turns out that in this case I follow the WTF documentation way, at least in crash course they are writing things like this.

accept_rules = BooleanField('I accept the site rules', [validators.Required()]) 

If this doesn't work you can try writing simply:

familyname = TextField('familyname', [Required()])

You can also explicitly set validators to be optional:

biography = TextAreaField('biography', [validators.optional())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top