I have to make a lot of RadioFields, and I thought it would be good to dynamically generate them, but I can't get the code working. I'm using Flask and flask-wtf.
Form definition:
from flask_wtf import FlaskForm
from wtforms import RadioField, SubmitField
class GenerateForm(FlaskForm):
def binary_generator(self, label_text, yes_text, no_text):
return RadioField(label_text, choices=[(1, yes_text), (0, no_text)])
submit = SubmitField('submit')
Flask app:
import GeneratorForm
form = GeneratorForm
form.radio_one = form.binary_generator('test label', 'yes', 'no')
render_template('file.html', form=form)
Jinja:
{{ form.radio_one.label }}
{{ form.radio_one(style="list-style: none") }}
The Jinja fails with: wtforms.fields.core.UnboundField object has no attribute label
So it looks like the class binary_generator function is working ok, but not constructing the form properly?
Do you need that binary_generator method in GenerateForm ?
Your GenerateForm could look something like this:
from flask_wtf import FlaskForm
from wtforms import RadioField, SubmitField
class GenerateForm(FlaskForm):
radio_fields = RadioField('', choices=[])
submit = SubmitField('submit')
And in your flask application, you need to instantiate your form like this:
import GeneratorForm
form = GeneratorForm() # Instantiate it
form.radio_fields.label = 'Label Example'
form.radio_fields.choices = [('value_1', 'description'), ('value_2', 'description')]
render_template('file.html', form=form)
To render your form in file.html:
<form method="post">
{{ form.hidden_tag() }}
{{ form.radio_fields.label }}
{{ form.radio_fields(style='list-style: none') }}
{{ form.submit }}
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With