django - 如何在 django 中设置 choicefield 的值

标签 django python-2.7 django-forms django-1.5 choicefield

我有一个地址表,其中有一个国家/地区选择字段。我想在表单加载之前设置一个值。我怎么能这么做呢? 表格如下:

from django import forms
from django.utils.translation import gettext as _

from django_countries import countries
from core.api import NcpAPI


class AddressForm(forms.Form):
    # first_name        = forms.CharField(label=_("First Name"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    # last_name         = forms.CharField(label=_("Last Name"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    # company       = forms.CharField(label=_("Company"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    street          = forms.CharField(label=_("Street/PoBox"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    address1        = forms.CharField(label=_("Address1"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    address2        = forms.CharField(required=False, label=_("Address2"), widget=forms.TextInput(attrs={'class':'form-text'}))
    address3        = forms.CharField(required=False, label=_("Address3"), widget=forms.TextInput(attrs={'class':'form-text'}))
    city            = forms.CharField(label=_("City"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    postal_code     = forms.CharField(label=_("Postal code"), widget=forms.TextInput(attrs={'class':'form-text required'}))
    country         = forms.ChoiceField(label=_("Country"), choices=countries.COUNTRIES, widget=forms.Select())

最佳答案

country = forms.ChoiceField(label=_("Country"), 
          choices=countries.COUNTRIES, widget=forms.Select(), initial= 'us')

或者您可以在调用表单构造函数时启动它

form = AddressForm(initial={'country': 'us'})

关于django - 如何在 django 中设置 choicefield 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18097214/

相关文章:

python - Django:在哪里存储全局静态文件和模板?

python - 使用带有 Mod_Python 和多个 Python 安装的 Apache 在 Virtualenv 中运行 Django

django - 您将如何在 Django 应用程序和 Wordpress 博客之间共享主题?

Python- sum() 恰好需要 2 个参数(给定 1 个)

python - Django 基于类的 CreateView 中的表单集

python - 如何在 Django 中获取 super 用户详细信息?

python - 在 Python (2.7.4) 中使用 range() 时出现内存错误

python - Python 中字符串格式化程序的默认舍入模式是什么?

django - 初始化一个表单集

python - 日期范围的 Django 表单