【问题标题】:Django ModelMultipleChoiceField object has no attribute to_field_nameDjango ModelMultipleChoiceField 对象没有属性 to_field_name
【发布时间】:2012-01-01 13:10:53
【问题描述】:

我正在尝试为 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 时,都会收到上述错误。

我应该在课堂上添加一些我缺少的东西吗?

【问题讨论】:

    标签: python django model modelform


    【解决方案1】:

    您似乎对字段和小部件感到困惑。你继承自ModelMultipleChoiceField,它(顾名思义)是一个字段,而不是一个小部件。但是renderrender_options 是小部件上的方法,而不是字段。你已经在widgets 字典中使用了你的类。

    我怀疑你的意思是创建一个小部件。你应该从一个小部件类继承,可能是forms.CheckboxSelectMultiple

    【讨论】:

    • 是的,你是对的。我是……而且 CheckboxSelectMultiple 是我一直在寻找的东西!我怎么错过了?!谢谢。现在要弄清楚如何删除那个烦人的 help_text 消息。
    【解决方案2】:

    根据您发布的代码不确定为什么会出现问题,但to_field_nameModelChoiceField 上的一个属性:

    class ModelChoiceField(ChoiceField):
        ...
    
        def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
                     required=True, widget=None, label=None, initial=None,
                     help_text=None, to_field_name=None, *args, **kwargs):
            ...            
    
            self.to_field_name = to_field_name
    

    但是,当ModelMultipleChoiceField 子类化ModelChoiceField 时,__init__ 方法不接受to_field_name 作为关键字参数。它显然依赖于ModelChoiceFieldself.to_field_name 设置为默认None 的默认行为。

    你的子类应该做同样的事情,所以这部分是混乱的。

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 2020-02-11
      • 2015-02-19
      • 2016-03-30
      • 2021-04-05
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多