python - Django ModelMultipleChoiceField 对象没有属性 to_field_name

标签 python django model modelform

我正在尝试为 ModelForm 创建自定义字段。我正在从 ModelMultipleChoiceField 扩展,然后覆盖渲染和渲染选项,但是,当我试图导入我的表单时,我一直收到这个异常:

AttributeError: 'ModelMultipleChoiceField' 对象没有属性 '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 时,我都会收到上面的错误。

我应该在类里面添加一些我遗漏的东西吗?

最佳答案

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

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

关于python - Django ModelMultipleChoiceField 对象没有属性 to_field_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8188048/

相关文章:

php - 如何与多个项目共享 Symfony2 模型

node.js - sequelize 未在 index.js 中为 sequelize 模型定义

database - 如何从 CodeIgniter 数据库迁移到 Laravel 数据库

python - 优化for循环的处理?

python - sklearn pca n_components等于特征个数问题

python - django.db.utils.IntegrityError : NOT NULL constraint failed: new__users_personal_detail. husband_adhaarcopy

python - 导入错误: No module named termios with django_mysql on Windows

python - 向字典添加元素会破坏编码

python - Django,如何生成没有模型的管理面板?

django - 在模型中存储外键列表的最佳方法?