简体   繁体   中英

WTforms IntegerField in fieldlist never validates using manual iteration

I have an InterField , that validates if a number is between the values 0 and 99 . For some reason it never validates. I have a feeling it is related to the FieldList and ther way I iterate over it in the template, but can't seem to get it working.

The form:

class dpiaImpactAnalysisForm(Form):

    severity_score = IntegerField("Severity Score"), 
        validators=[NumberRange(min=0, max=99, message="Please provide a valid number")]))
    identifiability_score = IntegerField("Identifiability Score"),
        validators=[NumberRange(min=0, max=99, message="Please provide a valid number")]))


class dpiaThreatAnalysisForm(Form):

    impact = FieldList(FormField(dpiaImpactAnalysisForm), min_entries=1)

In views I append the entries dynamically as required:

@app.route('/dpia/analysis/<project_id>', methods=["GET", "POST"])
def analysis(project_id):

    form = dpiaThreatAnalysisForm()

    prim = Assets.query.filter_by(selected=True, primary=True).all()
    primary_assets = list(map(vars, prim))

    ev = Events.query.all()
    events = list(map(vars, ev))

    # add fields to the form...
    for z in range(len(prim) * len(ev)):
        form.impact.append_entry()

    supp = Assets.query.filter_by(selected=True, primary=False).all()
    supporting_assets = list(map(vars, supp))

    ths = Threats.query.all()
    threats = list(map(vars, ths))

    # add fields to the form
    for z in range(len(ths) * len(supp)):
        form.likelihood.append_entry()

    if form.is_submitted():
        print "submitted"
    if form.validate():
        print "valid"
    print form.errors

    if form.validate_on_submit():
        # This is never printed:
        app.logger.info("success!!")
        pprint(form.likelihood)

    return redirect(url_for(next_step, project_id=project_id))
return render_template('analysis.html', form=form, threats=threats, supporting_assets=supporting_assets, primary_assets=primary_assets, events=events)

In the template I iterate over a list primary_assets in a list events , and add the fields per iteration:

{% for val in events %}
   {% if not counter or loop.index0 == 0 %}
      {% set counter = [] %}  <!-- loop hack !-->
   {% endif %}
   <strong>Event: {{ val.name }}</strong><br />
   Jeopardizes: {{ val.jeopardizes }}<br />

   {% for pa in primary_assets %}
       <strong>{{ pa['name'] }}</strong><br />
       {{ form.impact[counter|length].identifiability_score(placeholder='') }} <br />
       {{ form.impact[counter|length].severity_score(placeholder='') }} 
       {{ form.impact[counter|length].hidden_tag() }} 
       {% if counter.append('1') %}{% endif %}
   {% endfor %}
{% endfor %}

The hidden_tag() doesn't work either. Normally I iterate of the forms with with something like

 {% for impact in form.impact %}
     {{ impact.form.hidden_tag() }}
     # do cbg
  {% endfor %}

and that works, that's why I believe it's my manual looping that spoils it...

EDIT 2 march, 17:26

After some testing, I found that using

severity_score = IntegerField("Severity Score", validators=[Optional(), NumberRange( min=0, max=9999999999, message="Please provide a valid number")])

works (if I set min=50 I get an error when inserting a number below 50), however, the CSRF is still not getting passed.

{{ form.impact[counter|length].hidden_tag() }} or {{ form.impact[counter|length].form.hidden_tag() }} both don't work :(

I'm getting: {'impact': [{'csrf_token': ['CSRF token missing']}, {'csrf_token': ['CSRF token missing']}]}

EDIT 18:22

It seems that this: Form validation fails due missing CSRF is the solution. Investigating...

This: Form validation fails due missing CSRF is the solution.

In previous versions this wasn't needed, and after an installation of a new extension pip updated flask-wtf as well...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM