How do I correctly provide a custom widget with attrs? The call print attrs only outputs this:
attrs in LockFlagWidget are:
{'id': u'id_lockedFlag'}
whereas I would expect this:
attrs in LockFlagWidget are:
{'id': u'id_lockedFlag', 'size': u'80}
I wrote a custom widget like this:
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>")
Now I m using the widget in a form like this:
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 looks like this:
class MyModel(models.Model):
lockedFlag = models.BooleanField(default=False)
It looks to my like the attributes that are being passed into your render method are the attributes from the field not the widget, try to change your print statement to
print self.attrs, that will pick up the attributes that you passed into the constructor of your widget. Hope that makes sense?