带有WTForms的长排序下拉列表 [英] Long sorted dropdown list with WTForms
问题描述
我想创建一个按字母顺序排列的美国各州的下拉列表.我已经将状态元组转换为OrderedDict,并将其输入到WTForms SelectField中.
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?
推荐答案
这里有几个问题:
您的列表不是50元组的列表.
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']
我不认为您的state_pairs
是您认为的配对.他们是这样的对
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
>>>
我相信您想要的state_pair
看起来应该像这样:
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
>>>
解决您遇到的问题的方法是摆脱方法list_to_ordere_pair
并仅创建state_pairs
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)
这篇关于带有WTForms的长排序下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!