How to get value (not key) data from SelectField in WTForms [duplicate]
Asked Answered
P

1

9

I have a WTF SelectField, and I'm trying to store the name of the user's choice for display on another page.

Given that my form is

choice = SelectField('Choice', choices=[('cho_1', 'Choice One'), ('cho2', 'Choice Two')])

I understand that

self.choice = form.choice.data

will get me the user's choice (say, cho_1), but how do I get the value ("Choice One")? I feel like it's something simple with dicts, but various attempts plus googling/searching SO haven't helped so far.

Prosecute answered 28/3, 2017 at 13:44 Comment(0)
P
18

Thanks to Ashish Nitin Patil for directing me to here.

I needed to transform the 'choices' into a dict, then get the value for key form.data, thus:

 value = dict(form.choice.choices).get(form.choice.data)
Prosecute answered 28/3, 2017 at 13:55 Comment(1)
Good solution! Case your keys are integers, depending on the use, you may need to do something like value = dict(form.choice.choices).get(int(form.choice.data))Praiseworthy

© 2022 - 2024 — McMap. All rights reserved.