Long sorted dropdown list with WTForms
forms, python, wtforms
Solution
There are a few issues here:
Your list isn't a list its a 50-tuple.
STATE_ABBREV = ('AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IO', 'KS', 'KY', 'LA', 'ME', 'MD',
'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY')
If you wanted a list, it would look something like:
STATE_ABBREV = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IO', 'KS', 'KY', 'LA', 'ME', 'MD',
'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
I don't believe your `state_pairs` are pairs in the sense that you think they are. They are pairs like this
>>> state_pair = 'AK'
>>> abbr, state = state_pair
>>> print abbr
A
>>> print state
K
>>>
I believe `state_pair` you want would look something like this:
>>> state_pair = ('AK', 'Alaska')
>>> abbr, state = state_pair
>>> print abbr
AK
>>> print state
Alaska
>>>
The solution to the problem you are seeing is to get rid of the method `list_to_ordere_pair` and just create a list of of `state_pairs`
STATE_CHOICES = [('AL', 'Alabama'),('AK','Alaska')...]
class MyForm(wtforms.Form):
state = wtforms.SelectField(label='State', choices=STATE_CHOICES)
Problem
I'd like to create a drop-down list of the U.S. states in alphabetical order. I've converted a tuple of states into an OrderedDict and I'm feeding this into my WTForms SelectField. ``` import collections import wtforms STATE_ABBREV = ('AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IO', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY') def list_to_ordered_pairs(input_list): ordered_pairs = collections.OrderedDict() for item in input_list: ordered_pairs[item] = item return ordered_pairs state_pairs = list_to_ordered_pairs(STATE_ABBREV) class MyForm(wtforms.Form): state = wtforms.SelectField(label='State', choices=state_pairs) ``` My problem is that the resulting dropdown menu shows only the second letter of each state... How do I fix this up to show the proper two-letter designation? And is there a better approach to pulling in various geographic regions?