Python Flask – What is the best way to conditionally display WTF fields based on prior responses?

Issue

I have a WTF form with several fields where I only want to display certain fields based on the responses to previous fields without refreshing the page. For example, say I have a field:

URLInd = BooleanField(u'Do you have a website?',validators=[DataRequired())

Which if checked, I want to display:

URL = TextField(u'Please enter your web address',validators=[DataRequired(), URL()])

So “URLInd” can be shown at the initial page load, but I only want “URL” shown if URLInd == True.

HTML:

<form class="form form-horizontal" method="post" role="form"  enctype=multipart/form-data action>
  {{ form.hidden_tag() }}
  {{ wtf.form_errors(form, hiddens="only") }}
  {{ wtf.form_field(form.URLInd) }}
  {{ wtf.form_field(form.URL) }}
  <button type="submit" class="btn btn-primary btn-lg btn-block">Submit</button>
</form>

Based on my research, I suspect I need to use Javascript and AJAX, but I have no experience using either and I haven’t been able to apply any of the examples I’ve found to this problem. Thanks in advance for your help.

Solution

Field have arg message for replace default error message in defaults validators. For replace use kwargs message="u error message for view invalid this field"

Simple example

URLInd = BooleanField(u'Do you have a website?',validators=[URL(message="I want MY MESSAGE ERROR THIS FIELD")])

Answered By – Spouk

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published