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.
You should define the
format_outputfunction of your Widget - see: https://docs.djangoproject.com/en/dev/ref/forms/widgets/This lets you format the form html any way you like. I think the default is just to concatenate the field elements.