0

I have a form class like

class StudentForm(FlaskForm):
      bool_1= BooleanField('Set bool_1')
      bool_2= BooleanField('Set bool_2')

Now in view, I want to get the value of fields like

@app.route('/student', methods=['POST'])
def student():
    fields = ['bool_1', 'bool_2']
    form = StudentForm()
    if request.method == 'POST':
       for field in fields:
         if form.field.data is True:
           print('OK')
    return render_template('abc.html', form=form)

But it showing 'StudentForm' object has no attribute 'field', I know the field is a string. Is there any way to achieve this.

Omar
  • 901
  • 11
  • 14
  • 1
    Does this answer your question? [How to access object attribute given string corresponding to name of that attribute](https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib) – noslenkwah Jul 29 '20 at 14:03

2 Answers2

1

Have a look at this answer: https://stackoverflow.com/a/16664376/5516057. And maybe read through something like this: https://pythonise.com/series/learning-flask/flask-working-with-forms. It seems strange to me that you instantiate a new StudentForm() when you are handling a post request. You want to see the data that comes out of the request I'm guessing? What I think you want to do looks more like this:

from flask import request

@app.route('/student', methods=['POST'])
def student():
    fields = ['bool_1', 'bool_2']
    form = request.form # request is a flask thing that handles the data from the request

    for field in fields:
       if form.get(field) is True: # use get, if the strings defined in fields are not in the form in the request this returns None like a normal dict I think
           print('OK')
    return render_template('abc.html', form=form)
Marc
  • 1,539
  • 8
  • 14
0

Here is a simple solution:

@app.route('/student', methods=['POST'])
def student():
    form = StudentForm()
    for k, v in form.data.items():
        if v:
            print('OK')
    return render_template('abc.html', form=form)

And there is no need to check the request.method because you have restricted methods to only be POST in the route decorator.

yuxiaoy
  • 224
  • 1
  • 3