问题描述
我正在尝试为ModelForm创建一个自定义字段.我从ModelMultipleChoiceField进行了扩展,然后覆盖了render和render_options,但是,在尝试导入表单时,我总是收到此异常:
I'm trying to create a custom field for a ModelForm. I'm extending from ModelMultipleChoiceField and then overriding render and render_options, however, I keep getting this exception when just trying to import my form:
AttributeError: 'ModelMultipleChoiceField' object has no attribute 'to_field_name'
我不确定我缺少什么.我什至尝试在我的新类中添加to_field_name属性,但这无济于事.这是我的代码:
I'm not sure what I'm missing. I've tried even adding a to_field_name attribute to my new class, but that doesn't help. Here is my code:
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
时,都会收到上述错误.
Whenever I simply do an from myapp.forms import RoleForm
, I get the error above.
我应该在我的课堂上添加一些我想念的东西吗?
Should I be adding something to my class that I'm missing?
推荐答案
您似乎对字段和小部件感到困惑.您从ModelMultipleChoiceField
继承,该名称(顾名思义)是一个字段,而不是窗口小部件.但是render
和render_options
是窗口小部件(而不是字段)上的方法.您已经在widgets
词典中使用了您的课程.
You seem to have got confused between fields and widgets. You inherit from ModelMultipleChoiceField
, which (as the name implies) is a field, not a widget. But render
and render_options
are methods on widgets, not fields. And you've used your class in the widgets
dictionary.
我怀疑您确实是要创建小部件.您应该从小部件类(可能是forms.CheckboxSelectMultiple
)继承.
I suspect you do mean to create a widget. You should inherit from a widget class, probably forms.CheckboxSelectMultiple
.
这篇关于Django ModelMultipleChoiceField对象没有属性to_field_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!