如何正确提供带有属性的自定义小部件?该调用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)