E
E
egregors2014-09-30 06:22:15
Flask
egregors, 2014-09-30 06:22:15

How to dynamically assign one of several values ​​to a WTForms descendant field when initializing a class instance?

Good time.
# Project on Flask + WTForms

I have several custom SelectFields and a form in which one and the same field, depending on the conditions, must be assigned one or another SelectField.

# in view
@app.route('/some/<int:a>/', methods=['POST', 'GET'])
def f(a):
    form = MyForm(a=a)
    return render_template('t.html', form=form)

# in forms
class MyForm(Form):
    next = HiddenField()
    static_field1 = StringField()
    static_field2 = StringField()
    static_field3 = StringField()

    # здесь проблема
    # если a == 1 то необходимо сделать specific_field = CustomSelect1(),
    # но если a == 2, то specific_field = CustomSelect()2

    specific_field = ?


As far as I understand, it is necessary to overload __init__() MyForm in such a way that, depending on the value accepted as a parameter, one or another SelectField can be assigned to the field. Can

you please tell me how to implement this correctly?

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bromzh, 2014-09-30
@bromzh

This is usually done by metaclasses.

S
snoopt, 2014-11-21
@snoopt

You can add the necessary fields to the form in the view:

if a == 1:
    MyForm.static_field1 = CustomSelect1()

Link to WTF documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question