Dynamically modifying a form widget in Django -
my django app uses django suit tool theme admin app of django. 1 of things suit can append , prepend elements form widgets like:
class propertyform(modelform): class meta: model = property widgets = { 'amount': enclosedinput(prepend = "gbp"), }
the effect is:
although nice feature more useful if add dynamically (in pseudo code):
'amount': enclosedinput(prepend = my_model_instance.currency)
i tried override form's init so:
class propertyform(modelform): def __init__(self, *args, **kwargs): inst = kwargs["instance"] self._meta.widgets["amount"] = enclosedinput(prepend = inst.currency) super(propertyform, self).__init__(*args, **kwargs)
strangely works when put breakpoint in init method. looks there's timing issue involved.
so question best way (if 1 @ available) implement this?
the problem with:
self._meta.widgets["amount"] = enclosedinput(prepend = inst.currency)
it turns out _meta
being cached. when change above line (which nicer solution _meta private):
self.fields['amount'].widget = enclosedinput(prepend = inst.currency)
...it works flawlessly
Comments
Post a Comment