【问题标题】:django TypedChoiceField - not allow default value of 0django TypedChoiceField - 不允许默认值 0
【发布时间】:2014-10-11 00:13:08
【问题描述】:

当涉及到 TypedChoiceField 并且不允许用户输入选定的值“0”时,我不太确定我的 forms.py 文件设计是否正确。

我已阅读django docs,但找不到任何关于此的内容。有一些关于 empty_value 的内容,但我找不到关于 TypedChoiceField 的任何示例。

我在选择列表中有一个国家/地区名称列表:

<select data-parsley-required="true" name="address_country_style_type" data-parsley-required-message="This field is required." id="id_address_country_style_type" data-parsley-id="1440" class="input-xxlarge" data-original-title="" title="">
    <option value="0"> Select a country or territory</option>
    <option value="1">Afghanistan</option>
    <option value="2">Aland Islands</option>
    <option value="3">Albania</option>
    ......
</select>

在我的 forms.py 文件中,我有以下内容(包括清理后的数据代码):

@parsleyfy
class AddressDetailsForm(forms.Form):

required_css_class = 'required'

address_country_style_type = forms.TypedChoiceField(
    coerce=int,
    label=_('Address Format'),
    choices=[(x, x) for x in range(0, 256)],
    required=True)
....

def clean(self):

    cd_addf = super(AddressDetailsForm, self).clean()

    if 'address_country_style_type' in cd_addf and cd_addf['address_country_style_type'] == 0:

        self._errors['address_country_style_type'] = self.error_class([_("You must select an Address Format.")])
        del self.cleaned_data['address_country_style_type']

    else:
        ....

我添加了django-parsley 来设置客户端验证。

forms.py 文件中的“address_country_style_type = forms.TypedChoiceField”声明中是否有办法声明 address_country_style_type 不能接受选项值 0,以便通过以下方式自动获取此验证django-parsley 和我可以剔除清理过的数据 if 语句?

【问题讨论】:

    标签: javascript jquery django-forms django-templates parsley.js


    【解决方案1】:

    我没有用过django,所以只能用parsleyjs帮你。

    如果您设法删除 value="0" 并像 value="" 一样放置它,Parsleyjs 会告诉您该字段是必需的:

    <option value=""> Select a country or territory</option>
    

    【讨论】:

      猜你喜欢
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2016-01-28
      • 2014-06-13
      • 2020-12-02
      相关资源
      最近更新 更多