简体   繁体   English

Django localflavor USStateSelect()初始值

[英]django localflavor USStateSelect() inital value

I'm trying to use the django localflavor widget USStateSelect() in a form, but I want the widget to have Nebraska selected by default. 我正在尝试在表单中使用django localflavor小部件USStateSelect(),但我希望该小部件默认情况下已选择内布拉斯加州。 The Widget only accepts an attrs arg, so I'm trying to understand what attributes I have to set to get the desired result. 窗口小部件仅接受attrs arg,因此我试图了解必须设置哪些属性才能获得所需的结果。 Here's what I've got in my forms.py: 这是forms.py中包含的内容:

state = forms.CharField(widget=USStateSelect(attrs={'value':'NE'}))

This is the docs for the HTML select element: http://www.w3.org/html/wg/drafts/html/CR/forms.html#the-select-element 这是HTML select元素的文档: http : //www.w3.org/html/wg/drafts/html/CR/forms.html#the-select-element

This is the docs for localflavor: https://django-localflavor.readthedocs.org/en/latest/_modules/localflavor/us/forms/ 这是localflavor的文档: https ://django-localflavor.readthedocs.org/en/latest/_modules/localflavor/us/forms/

<option value="NE" selected>Nebraska</option>

This is what I need to have in my html, but I can't figure out what the attrs dict needs to contain to achieve this result. 这是我在html中需要的内容,但是我无法弄清楚为实现此结果需要包含的attrs dict。 I've tried adding 'selected':'selected' and 'class':'selected' to the dict, but that's not doing it. 我试过在字典中添加'selected':'selected'和'class':'selected',但这不是这样做的。

I've seen a number of people asking how to add an empty option, but no one seems to want to make it default to a specific state. 我见过很多人问如何添加一个空选项,但是似乎没人希望将其默认设置为特定状态。 Any ideas are welcome. 任何想法都欢迎。

Thanks, 谢谢,

Anthony 安东尼

You can set the initial value like so: 您可以这样设置初始值:

state = forms.CharField(widget=USStateSelect(), initial='NE')

or you can set it when you instantiate the form: 或者您可以在实例化表单时进行设置:

form = ExampleForm(initial={'state': 'NE'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM