在Django中实现多重选择(复选框)和“其他”小部件

3 投票
2 回答
1430 浏览
提问于 2025-04-16 21:49

我需要把一个字符字段填充为一组复选框的结果,并加上一个“其他”选项(在下面的表单状态中,值会是'option-a,other')。这个表单大致可以是这样的:

[x] option a
[ ] option b
[x] other

If you selected "other", please specify. [__________]

我通过实现一个MultipleChoiceField的子类,已经完成了大部分工作:

class CommaStringMultipleChoiceField(MultipleChoiceField):
    def to_python(self, value):
        return [val.rstrip().lstrip() for val in value.split(',')]

    def clean(self, value):
        return ",".join([val.rstrip().lstrip() for val in value])

在我的表单类中,我把这个字段分配给我的表单字段:

TYPE_CHOICES = [
    (u'option-a',u"Option A"),
    (u'option-b',u"Option B"),
    (u'other', u"Other"),
]

type = CommaStringMultipleChoiceField(
    choices=TYPE_CHOICES,
    widget=CheckboxSelectMultiple
)

这样表单就能正确显示了,我自定义的clean()方法也被调用了,但当我保存表单时却出现了验证错误:

Value u'education,other' is not a valid choice.

我尝试添加一个自定义验证器,但到目前为止没有什么效果。我漏掉了什么呢?

2 个回答

0

你可能需要在你的类里重写(也就是修改)Validate方法。在这个代码链接 https://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L682 中,你可以看到是在哪里抛出错误信息的。

1

这个错误只在你从表单保存模型实例时出现,所以要检查一下“Value u'education,other' is not a valid choice”这个错误是不是来自于模型的验证,而不是表单的验证。如果你在模型字段上设置了choices,但其实你想存储的是一个自由格式的字符串,这种情况就会发生。

撰写回答