开发者

Custom multivaluefield isn't displayed in empty form

开发者 https://www.devze.com 2023-01-16 15:09 出处:网络
I\'m trying to build a custom multivaluewidget in my django app. Widget class DayInputWidget(MultiWidget):

I'm trying to build a custom multivaluewidget in my django app.

Widget

class DayInputWidget(MultiWidget):
    def __init__(self, attrs=None):
        widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(d开发者_StackOverfloway_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
        super(DayInputWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        print value
        if value:
            return value
        return None

Input

class DayInput(Input):
    input_type = 'text'
    def __init__(self,attrs=None,day_name=None):
        super(DayInput, self).__init__(attrs)
        self.day_name = day_name

    def render(self, name, value, attrs=None):
        if name is None:
            name = 'Bestellmenge_%s' % self.day_name
        # create day inputs
        return mark_safe(u'<label style="padding-left: 5px">%s</label><input type="text" name="%s" size="5px"  value="0"/> ' % (self.day_name,name))

field

class DayInputField(forms.MultiValueField):
    widget = DayInputWidget

    def __init__(self, *args, **kwargs):
        fields = (forms.CharField(),forms.CharField(),forms.CharField(),forms.CharField(), forms.CharField())
        super(DayInputField, self).__init__(fields, *args, **kwargs)

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

form

class OrderForm(forms.Form):
    Produktart = forms.ModelChoiceField(MProductTypes.objects.all())
    Kw = forms.CharField(widget=KwSelect(), required=False)
    Bestellmengen = fields.DayInputField()

Problem: The form is only shown when it is bound to data. If I init the form with empty data, the validation tooks place and it will be displayed. What am doing wrong here?

I initialise my form this way

form = OrderForm()

according documentation the form should be displayed empty.


Try the following: in your widget class, rewrite your decompress method, so that it does not return None, but []:

class DayInputWidget(MultiWidget):
def __init__(self, attrs=None):
    widgets = (DayInput(day_name='Mo'), DayInput(day_name='Di'), DayInput(day_name='Mi'), DayInput(day_name='Do'), DayInput(day_name='Fr'))
    super(DayInputWidget, self).__init__(widgets, attrs)

def decompress(self, value):
    print value
    if value:
        return value
    return []

This was suggested in this SO answer and it helped me with a similar case.

0

精彩评论

暂无评论...
验证码 换一张
取 消