ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – Django ModelMultipleChoiceField对象没有属性to_field_name

2019-07-12 16:05:33  阅读:179  来源: 互联网

标签:python django model modelform


我正在尝试为ModelForm创建自定义字段.我从ModelMultipleChoiceField扩展然后覆盖render和render_options,但是,当我只是尝试导入我的表单时,我不断收到此异常:

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())
        }

每当我只是从myapp.forms导入RoleForm时,我得到上面的错误.

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

解决方法:

你好像在字段和小部件之间感到困惑.您继承自ModelMultipleChoiceField,(顾名思义)是一个字段,而不是一个小部件.但是render和render_options是小部件上的方法,而不是字段.你已经在小部件字典中使用了你的类.

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

标签:python,django,model,modelform
来源: https://codeday.me/bug/20190712/1442374.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有