【问题标题】:Properly defining "other" option in django MultipleChoiceField using CheckboxSelectMultiple使用 CheckboxSelectMultiple 在 django MultipleChoiceField 中正确定义“其他”选项
【发布时间】:2012-07-24 01:48:10
【问题描述】:

我是 django 和 python 的新手,目前正在尝试构建一个包含各种选项的表单以及列表中未列出的选项的“其他”选项。我想定义该选项,以便在选中“其他”时,表单仅验证其他文本框是否包含非空值。

是否有适当的方法来扩展 django 表单/字段/小部件来完成此任务? 在搜索 google 和 stackoverflow 后可以找到最接近的东西是 this example,它提供了扩展创建自定义渲染器的代码、小部件和表单字段,但它基于旧版本的 django。

【问题讨论】:

    标签: django model-view-controller checkbox django-forms multiple-choice


    【解决方案1】:

    如果您使用 django.forms.ModelForm 呈现表单,您可以在选项字段 (clean_[your field name]) 的表单验证中执行此操作。

    from django import forms
    
    class YourModelForm(forms.ModelForm):
        def clean_your_options(self):
            your_options = self.cleaned_data.getlist('your_options')
    
            if 'other' in your_options:
                other_text_input = self.cleaned_data.get('other_text_input')
                if len(other_text_input) == 0:
                    raise forms.ValidationError('Other text input must contain value')
    
            return your_options
    

    【讨论】:

    • 我只是使用普通的旧 django.forms.Forms。您的答案是否适用于这种情况?
    • 是的,它应该可以正常工作:docs.djangoproject.com/en/dev/ref/forms/validation/…
    • 感谢您的帖子!这看起来比我尝试的要容易得多。今晚晚些时候我会试一试。
    • 完美地工作了一个警告。我必须将cleaned_data 外部化为一个变量并将其定义为cleaned_data = super(ContactForm, self).clean() 原因是,由于这是在表单验证期间调用的,因此self.cleaned_data 不包含我需要的所有信息。
    • @Dave,我遇到了和你一样的问题,但有另一种解决方法。大概您将other_text_input 放在your_options 之后,这就解释了为什么other_text_input 在您到达那里时在self.cleaned_data 中不可用。所以我的解决方案是将这个逻辑从clean_your_options 移动到clean_other_text_input。但是我是在单选字段上执行此操作的,所以我不确定它是否会适用于多项选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2018-08-02
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多