I'm using Flask to create a web app. I'm trying to create a form using Flask-WTForms by iterating through a list passed in the render_template() method. However, I can't reference the variable in the for-loop inside the template.
View
class FormExample(Form):
category1 = StringField("Category 1")
category2 = StringField("Category 2")
categories = ['category1', 'category2']
def form():
form = FormExample(request.form)
return_template("form.html", categories=categories, form=form)
_formhelpers.html (suggested to use under the docs)
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
{% endif %}
</dd>
{% endmacro %}
Template (form.html)
<form method="POST">
{% for category in categories %}
{{render_field(form.category)}}
{% endfor %}
</form>
When trying to reference form.category in form.html I'm given the following error through the Flask debugger:
jinja2.exceptions.UndefinedError: '__main__.EvaluateCaseForm object' has no attribute 'category'
I've already looked at the official documentation here and couldn't find the answer. I've also tried referencing {{render_field({{ form.category }})}}, {{render_field(form.{{category}})}}, and {{render_field({% form.category %})}}
Is there a way to reference the for-loop variable category inside the render_field() method?
{% for field in form %}{{ render_field(field) }}{% endfor %}? Are you trying to handlecategoriesnot matching the fields in your form?form.categoryis being read as though the variableformhas an attribute calledcategory. However, I want the value forcategoryto be the value based on the for-loop. Does that make sense?