2

All,

I have a form with a MultiValueField that almost works. It uses a choicefield and charfield (with a corresponding Select and TextInput for the widgets)::

custom_choices = [("one","one"),("two","two"),("other","other")]

class MyMultiWidget(forms.MultiWidget):
    def __init__(self,*args,**kwargs):
        widgets = (
            forms.Select(choices=custom_choices),
            forms.TextInput(),
        )
        super(MyMultiWidget, self).__init__(widgets,*args,**kwargs)

    def decompress(self, value):
        if value:
            return value.split("|")
        return ['', '']

class MyMultiValueField(forms.MultiValueField):
    def __init__(self, *args, **kwargs):
        fields = (
            forms.ChoiceField(required=True),
            forms.CharField(max_length=128,required=False),
        )
        super(MyMultiValueField, self).__init__(fields, *args, **kwargs)
        self.widget = TestMultiWidget()

    def compress(self, data_list):
        if data_list:
            return '|'.join(data_list)

class MyTestField(models.Field):
    def formfield(self, **kwargs):
        return super(MyTestField, self).formfield(form_class=MyMultiValueField)

class MyModel(models.Model):
    myField = MyTestField()

The compress function seems to be working; it returns a list of two strings as expected. But the "value" argument in decompress is always None. Sure enough, when I check the database directly, the myField column is consistently set to null. Any ideas what's happening inbetween compress and decompress? Why isn't the value from compress actually being stored?

Thanks.

trubliphone
  • 4,132
  • 3
  • 42
  • 66
  • You should inherit `MyTestField` from some field which actually contain the data. In your case it can be `CharField` or `TextField`. I think it will solve the problem. – ilvar Apr 30 '12 at 04:37
  • Thanks. This did help (and if you make it an answer, I'll mark it as accepted). But is also uncovered another problem with my code which I have posted as [another question](http://stackoverflow.com/questions/10454164/django-multivaluefield-multiwidget-make-one-optional) – trubliphone May 04 '12 at 18:24

1 Answers1

1

You should inherit MyTestField from some field which actually contain the data. In your case it can be CharField or TextField. I think it will solve the problem.

ilvar
  • 5,718
  • 1
  • 20
  • 17