All,
I have managed to get MultiValueField and MultiValueWidget working. But, apart from "choices", I cannot seem to add attributes (like "label" or "initial") to the sub-fields that make up the MultiValueField.
Here is my (simplified) code:
class MyMultiWidget(django.forms.widgets.MultiWidget):
def __init__(self,*args,**kwargs):
myChoices = kwargs.pop("choices",[])
widgets = (
django.forms.fields.TextInput(),
django.forms.fields.TextInput(),
django.forms.fields.Select(choices=myChoices),
)
super(MyMultiWidget, self).__init__(widgets,*args,**kwargs)
class MyMultiValueField(django.forms.fields.MultiValueField):
widget = MyMultiWidget
def __init__(self,*args,**kwargs):
myLabel = "my label"
myInitial = "my initial value"
myChoices = [("a","a"),("b","b")]
fields = (
django.forms.fields.CharField(label=myLabel),
django.forms.fields.CharField(initial=myInitial),
django.forms.fields.ChoiceField(choices=myChoices),
)
super(MyMultiValueField,self).__init__(fields,*args,**kwargs)
self.widget=MyMultiWidget(choices=myChoices)
class MyField(models.Field):
def formfield(self,*args,**kwargs):
return MyMultiValueField()
class MyModel(django.models.Model):
myField = MyField(blank=True)
MyForm = modelform_factory(MyModel)
The "myField" field of MyModel is almost rendered correctly in MyForm; It shows three widgets: two TextInputs and a Select. The latter is restricted to the appropriate choices. But the former two don't have their label or initial value set.
Any suggestions on what I'm doing wrong?
Thanks.
@george is right that the
value
can be defined statically, but you can also overrideget_context
to figure out the value at run-time.Will render