1

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)

1 Answer 1

3

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())
Sign up to request clarification or add additional context in comments.

1 Comment

No problem :) You can mark this answer as the right one, and upvote it if you like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.