0

如何正确提供带有属性的自定义小部件?该调用print attrs仅输出以下内容:

attrs in LockFlagWidget are:
{'id': u'id_lockedFlag'}

而我希望这样:

attrs in LockFlagWidget are:
{'id': u'id_lockedFlag', 'size': u'80}

我写了一个这样的自定义小部件:

class LockFlagWidget(forms.widgets.Widget):

    def render(self, name, value, attrs=None):
        if value is None:
                value = ''
        print "attrs in LockFlagWidget are:"
        print attrs
        staticURL = getattr(settings, 'STATIC_URL')

        if value != '':
            if value == True:
                return mark_safe(u"<img src=\"" + staticURL +
                                 "lock/img/lock_closed.ico\"/>"
                                 + "<span> - Is locked</span>")
            else:
                return mark_safe(u"<img src=\"" + staticURL +
                                 "lock/img/lock_open.ico\"/>"
                                 + "<span> - Is not locked</span>")

现在我以这样的形式使用小部件:

class LockForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(LockForm, self).__init__(*args, **kwargs)
        self.fields['lockedFlag'].widget = LockFlagWidget(attrs={'size':'80'})

MyModel看起来像这样:

class MyModel(models.Model):
    lockedFlag = models.BooleanField(default=False)
4

1 回答 1

1

在我看来,传递给您的渲染方法的属性是来自字段而不是小部件的属性,尝试将您的 print 语句更改为print self.attrs,这将获取您传递给小部件构造函数的属性。希望这有意义吗?

于 2012-09-12T13:20:08.053 回答