我正在尝试为 ModelForm 创建一个自定义字段。我从 ModelMultipleChoiceField 扩展,然后覆盖 render 和 render_options,但是,在尝试导入表单时,我不断收到此异常:
AttributeError: 'ModelMultipleChoiceField' object has no attribute 'to_field_name'
我不确定我错过了什么。我什至尝试在我的新类中添加一个 to_field_name 属性,但这没有帮助。这是我的代码:
class MultiSelect(ModelMultipleChoiceField):
def __init__(self, queryset, cache_choices=False, required=True,
widget=None, label=None, initial=None, help_text=None, *args, **kwargs):
super(MultiSelect, self).__init__(queryset, cache_choices, required, widget,
label, initial, help_text, *args, **kwargs)
def render_options(self, name, choices, selected_choices):
output = []
i = 0
for option_value, option_label in chain(self.choices, choices):
checked_html = (option_value in selected_choices) and u' checked="checked"' or ''
class_html = (i % 2 == 0) and u'even' or u'odd'
output.append('<li class="{0}"><input type="checkbox" name="{1}" value="{2}"{3}/>{4}</li>'
.format(class_html, name, escape(option_value), checked_html, escape(option_label)))
i += 1
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul class="multiSelect">']
options = self.render_options(name, choices, value)
if options:
output.append(options)
output.append('</ul>')
return mark_safe(u'\n'.join(output))
class RoleForm(ModelForm):
class Meta:
model = Role
exclude = ('user_id',)
widgets = {
'permissions': MultiSelect(queryset=Permission.objects.all())
}
每当我简单地做一个from myapp.forms import RoleForm
时,我都会收到上面的错误。
我应该在课堂上添加一些我缺少的东西吗?