0

I have a Pandas dataframe and trying to return the column headers into WTForm dynamic list on a Flask application. However when I try to submit the HTML form, I get a validation error. Here is my form class error.

   data = pd.read_excel("sampledata.xlsx")
   col_headers = list(data.columns)

   col_list = list(col_headers)
   dic_list = {i : col_list[i] for i in range(0, len(col_list))}


   class StatementForm(FlaskForm):
   date = SelectField('Date', choices = [(key, dic_list[key]) for key in dic_list])

I have tested the HTML form by manually inputting a tuple in the choices list and it worked. Apparently the problem is in the 'date' parameter and the choices.

Your help in reviwing the code is most apreciated.

5
  • Try str(key) in your choices comprehension. In my experience the SelectField does not like integer keys. Commented May 17, 2019 at 18:30
  • 1
    Also, you can get rid of some steps by doing: choices = [(str(x), y) for (x, y) in list(enumerate(data.columns))] and do it all in one line. Let me know if this works Commented May 17, 2019 at 18:34
  • @snakecharmerb There is nothing much to show on the console, the validation rules stops the code from loading. Here is the screenshot pasteboard.co/IfaeH7r.png Commented May 17, 2019 at 20:17
  • @WoodyPride it kind of worked because my form now displays the column header values and submits. However I noticed whenever the data is called it is the Key or index ID that is outputted. form = StatementForm() date = form.date.data date returns an index number Commented May 18, 2019 at 7:31
  • @WoodyPride Please drop your comment as an answer so I can accept it. I was able to resolve the outputted Index ID - This solution from stackoverflow.com/questions/21217475/… worked. Commented May 18, 2019 at 8:39

1 Answer 1

1

Try using the following to create your choices:

choices = [(str(x), y) for (x, y) in list(enumerate(data.columns))]

The difference is that that value in the above code is a string. As per the WFT-Forms documentation:

Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.

In your version you are trying to pass integers as the value, so that is why it is breaking.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.