Skip to content Skip to sidebar Skip to footer

How Do I Generate Dynamic Fields In WTForms

I am trying to generate a form in WTForms that has dynamic fields according to this documentation http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html#dynamic-form-comp

Solution 1:

I ran into this issue tonight and ended up with this. I hope this helps future people.

RecipeForm.py

class RecipeForm(Form):
    category = SelectField('Category', choices=[], coerce=int)
    ...

views.py

@mod.route('/recipes/create', methods=['POST'])
def validateRecipe():
    categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
    form = RecipeForm(request.form)
    form.category.choices = categories
    ...

@mod.route('/recipes/create', methods=['GET'])
def createRecipe():
    categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
    form = RecipeForm(request.form)
    form.category.choices = categories
    return render_template('recipes/createRecipe.html', form=form)

I found this post helpful as well


Solution 2:

class BaseForm(Form):
    @classmethod
    def append_field(cls, name, field):
        setattr(cls, name, field)
        return cls

from forms import TestForm
form = TestForm.append_field("do_you_want_fries_with_that",BooleanField('fries'))(obj=db_populate_object)

I use the extended class BaseForm for all my forms and have a convenient append_field function on class.

Returns the class with the field appended, since instances (of Form fields) can't append fields.


Solution 3:

Posting without writing full code or testing the code, but maybe it will give you some ideas. Also this could maybe only help with the filling the needed data.

You need to fill choices for SelectField to be able to see the data and be able to select it. Where you fill that? Initial fill should be in the form definition, but if you like dynamic one, I would suggest to modify it in the place where you creating this form for showing to the user. Like the view where you do some form = YourForm() and then passing it to the template.

How to fill form's select field with choices? You must have list of tuples and then something like this:

form.category_select.choices = [(key, categories[key]) for key in categories]
form.category_select.choices.insert(0, ("", "Some default value..."))

categories here must be dictionary containing your categories in format like {1:'One', 2:'Two',...}

So if you will assign something to choices when defining the form it will have that data from the beginning, and where you need to have user's categories, just overwrite it in the view.

Hope that will give you some ideas and you can move forward :)


Solution 4:

have you tried calling append_entry() on the form instance instead of the FieldList definition?

class F(Form)
  fld = FieldList(SelectField(Item))

form = F()
form.fld.append_entry()

Solution 5:

This is how i got it to work.

class MyForm(FlaskForm):
    mylist = SelectField('Select Field', choices=[])

@app.route("/test", methods=['GET', 'POST']
def testview():
    form = MyForm()
    form.mylist.choices = [(str(i), i) for i in range(9)]

Strangely this whole thing stops working for me if i use coerce=int. I am myself a flask beginner, so i am not really sure why coerce=int causes issue.


Post a Comment for "How Do I Generate Dynamic Fields In WTForms"