django multivaluefield & multiwidget - compress and/or decompress not working

旧街凉风 提交于 2019-12-21 21:43:18

问题


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.


回答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.



来源:https://stackoverflow.com/questions/10370078/django-multivaluefield-multiwidget-compress-and-or-decompress-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!