我需要用一组复选框和一个“其他”[请指定]选项来填充一个CharField(值将是'option-a ,其他'为下面的表单状态)。形式可以基本上是这样的:实现一个复选框(复选框)在Django中选择+“其他”小部件
[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
)
这正确呈现形式,和我的自定义清洁()方法被调用,但是当我保存的形式,我得到验证错误:
Value u'education,other' is not a valid choice.
我已经玩过了添加自定义验证器,但迄今为止没有任何区别。缺少什么?
有一篇文章可能会帮助你修复类似的东西。该文章的主要变化是为另一个小部件创建子类。 [文章。](http://garmoncheg.blogspot.com/2014/05/implementing-multiple-radio-select.html) – garmoncheg