我正在尝试在 Django 中创建一个自定义表单字段。
class CustomTypedMultipleChoiceField(MultipleChoiceField):
def __init__(self, *args, **kwargs):
self.coerce = kwargs.pop('coerce', lambda val: val)
self.empty_value = kwargs.pop('empty_value', [])
super(CustomTypedMultipleChoiceField, self).__init__(*args, **kwargs)
def to_python(self, value):
"""
Validates that the values are in self.choices and can be coerced to the
right type.
"""
value = super(CustomTypedMultipleChoiceField, self).to_python(value)
if value == self.empty_value or value in self.empty_values:
return self.empty_value
new_value = []
for choice in value:
try:
new_value.append(self.coerce(choice))
except (ValueError, TypeError, ValidationError):
raise ValidationError(self.error_messages['invalid_choice'] % {'value': choice})
return new_value
def validate(self, value):
if value != self.empty_value:
super(CustomTypedMultipleChoiceField, self).validate(value)
elif self.required:
raise ValidationError(self.error_messages['required'])
我收到错误CustomTypedMultipleChoiceField
没有属性empty_values
。这与内置 Django 的代码完全相同TypedMultipleChoiceField
。所以我不明白为什么我会收到这个错误。我也想过对 进行子类化TypedMultipleChoiceField
,但是我希望它的错误在to_python
方法上有所不同,并且不想返回值的东西,所以选择了这种方法。请帮我。