Get selected text from a form using wtforms SelectField

后端 未结 5 1074
别跟我提以往
别跟我提以往 2020-12-17 21:02

This is a question upon the use of wtforms SelectField.

Once the form submitted, I wish to extract selected text.

I have the following form:

相关标签:
5条回答
  • 2020-12-17 21:16

    It was answered as a comment, so I'm writing here.

    Use form.hour.data to get the value instead of the name.

    0 讨论(0)
  • 2020-12-17 21:19

    Another option is to get the index from form.hour.data and call it like this:

    index = int(form.hour.data)
    form.hour.choices[index][1]
    
    0 讨论(0)
  • 2020-12-17 21:33

    When you set your choices, the list looks like [(index, value),...] so you don't need to import it, and probably shouldn't if setting dynamically

    value = dict(form.hour.choices).get(form.hour.data)
    

    Substitute self for form if inside form class

    In general, I often zip the choices so index and value are the same. However, sometimes I want to present a displayed selection that's shorter than the value of interest. In that case, I think of it like [(value, display),...] and then the data variable is the value of interest. For example, [(abspath, basename), ...]

    0 讨论(0)
  • 2020-12-17 21:38

    Define choices global in forms:

    HOUR_CHOICES = [('1', '8am'), ('2', '10am')]
    
    class TestForm(Form):
         hour = SelectField(u'Hour', choices=HOUR_CHOICES)
    

    import it from forms, convert it to dict:

    from .forms import HOUR_CHOICES
    
    hour_display = dict(HOUR_CHOICES).get(form.hour.data)
    
    0 讨论(0)
  • 2020-12-17 21:40

    If you don't need the choice indexes, is much more simpler:

    class TestForm(Form):
      hour = SelectField(u'Hour', choices=[('8am', '8am'), ('10am', '10am') ])
    
    0 讨论(0)
提交回复
热议问题