Hiding a form-group with Flask Jinja2 and WTForms

2019-06-04 02:35发布

问题:

I'm trying to show or hide a form field based on the state of a checkbox in another part of the form. I thought that I could do this with jQuery .show() or .hide() with relative ease, but I'm not having much luck so far. Any thoughts?

The form class:

class MyForm(Form):
    checked = BooleanField('Check this box:')
    date = DateField('Date:', format='%Y-%m-%d', id="dates")
    submit = SubmitField('Submit')

The template:

{% import "bootstrap/wtf.html" as wtf %}

{% block content %}

{{ form.hidden_tag() }}
{{ wtf.form_field(form.checked) }}
{{ wtf.form_field(form.date) }}
{{ wtf.form_field(form.submit) }}

{% endblock %}

{% block scripts %}

<script type="text/javascript">
jQuery(document).ready(function() {
  $("#checked").change(function() {
    if(this.checked) {
        $('#dates').show();
    } else {
      $('#dates').hide();
    }
  });
});
</script>

{% endblock %}

回答1:

It looks like you are using Flask-Bootstrap.

First, make sure you include {% extends 'bootstrap/base.html' %} in your template. Without that line, you'll lose out on everything Flask-Bootstrap includes in the template, such as jQuery.

Second, you are overriding the scripts block. This is where Flask-Bootstrap includes jQuery. In order to put your own stuff there without losing the base version, you need to use Jinja's super function. It will include the parent template's scripts block along with your own.

After making these changes your template should look something like

{% extends 'bootstrap/base.html' %}

{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
    <form>
        {{ form.hidden_tag() }}
        {{ wtf.form_field(form.checked) }}
        {{ wtf.form_field(form.date) }}
        {{ wtf.form_field(form.submit) }}
    </form>
{% endblock %}

{% block scripts %}
    {{ super() }}

    <script>
        jQuery(document).ready(function() {
            $("#checked").change(function() {
                if (this.checked) {
                    $('#dates').show();
                } else {
                    $('#dates').hide();
                }
            });
        });
    </script>
{% endblock %}