【发布时间】:2013-06-17 02:18:00
【问题描述】:
我正在尝试在 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 has no attribute empty_values。这与内置 TypedMultipleChoiceField 中的 Django 代码完全相同。所以我不明白为什么我会收到这个错误。
我也想过对TypedMultipleChoiceField 进行子类化,但是我希望它的错误在to_python 方法中有所不同,并且不想返回值的东西,所以选择了这种方法。
请帮帮我。
【问题讨论】:
-
你使用的是哪个 Django 版本?
-
Django 1.5.1 是我正在使用的版本。这有什么关系?
标签: django django-forms django-models