0

I would like to iterate over form's fields in a template and display fields with errors like this:

 {{ form.hidden_tag() }}
    {% for field in form if field.widget.input_type != 'hidden' %}
    {%  if form.errors.field %}
  <div class="has-error">  {{ field.label }}  {{ field(size=80, class_='form-control') }}</div>
    <span style="color: red;">{{ form.errors.field.0 }}</span>
    {% else %}
        {{ field.label }}  {{ field(size=80, class_='form-control') }}
        {% endif %}
    {% endfor %}

But that doesn't work for some reason- the form renders but the errors are not displayed.

I've already checked solutions here, and here, and also here and none of those have helped.

Could someone please advise how to fix my form to correctly render the errors?

1 Answer 1

3

The issue is in using form.errors.field. This would only be accurate in jinja if you had a field named field and not for any other names.

Fortunately, you're already iterating fields, and every field has a .errors property so the shortest solution is to simply use that property

Your code should look something like:

 {{ form.hidden_tag() }}
 {% for field in form if field.widget.input_type != 'hidden' %}
   {% if field.errors %}
     <div class="has-error">  {{ field.label }}  {{ field(size=80, class_='form-control') }}</div>
     <span style="color: red;">{% for error in field.errors %}{{ error }}{% if not loop.last %}<br />{% endif %}{% endfor %}</span>
   {% else %}
      {{ field.label }}  {{ field(size=80, class_='form-control') }}
   {% endif %}
 {% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

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.