无法从request.POST访问django MultiWidget的所有值?

时间:2018-08-01 18:29:57

标签: python django

我不确定为什么在发布请求后为什么无法从MutliWidget访问两个字段。我已经尝试了诸如request.POST.get('name')之类的各种方法,它们只是返回了0我也尝试了从value_from_datadict(self, data, files, name)访问值的过程,但是没有运气。

最让我感到困惑的是,当我使用print(request.POST)时,我发现发布请求中的表单确实包含了MultiWidget的两个值,但是我只能访问一个

例如,当我打印request.POST时,它被打印到控制台:

<QueryDict: {'total_travel_time': ['0', '0']}>

无论何时尝试:request.POST.get('total_travel_time')我只会收到0

这是怎么回事??????这让我有些发疯。

这是我的MutliWidget。

class TotalTimeWidget(forms.widgets.MultiWidget):
    CON_STYLE = "margin-left: 0.25in;"
    INPUT_STYLE = "width: .5in; display: inline; " \
                  "vertical-align: top; " \
                  "margin-left: 0.0675in; " \
                  "margin-right: 0.0675in;"
    hour_attrs = dict()
    min_attrs = dict()
    name = ''

    def value_from_datadict(self, data, files, name):
        data = super(TotalTimeWidget, self).value_from_datadict(data, files, name)
        print(data)
        return data

    def decompress(self, value):
        print("decompress_called", value)
        if value:
            return value
        else:
            return ['', '']

    def __init__(self, name, attrs=None, hours=0, minutes=0):
        hour_attrs = {'min': 0, 'max': 12, 'class': "hour", 'value': hours}
        min_attrs = {'min': 0, 'max': 59, 'class': "minute", 'value': minutes}
        self.hour_attrs = hour_attrs
        self.min_attrs = min_attrs
        self.name = name
        _widgets = (
            widgets.NumberInput(attrs=hour_attrs),
            widgets.NumberInput(attrs=min_attrs),
        )
        super(TotalTimeWidget, self).__init__(_widgets, attrs)

    def set_initial(self, **kwargs):
        if 'hours' in kwargs:
            self.hour_attrs['value'] = kwargs['hours']
        if 'minutes' in kwargs:
            self.min_attrs['value'] = kwargs['minutes']

    def render(self, name, value, attrs=None, renderer=None):
        super(TotalTimeWidget, self).render(name, value, attrs, renderer)
        html = '<div style="%(container_style)s"><span>Hours</span>'
        html += '<input type="number" name="%(name)s" min="0" max="99" ' \
                'class="hour" value="%(hour)s" style="%(style)s"' \
                'required id="id_total_hours_%(name)s" />'
        html += '<span>:</span>'
        html += '<input type="number" name="%(name)s" min="0" max="59"' \
                ' class="hour" value="%(min)s" style="%(style)s" ' \
                'required id="id_total_minutes_%(name)s" />'
        html += '<span>Minutes</span></div>'
        html = html % dict(hour=self.hour_attrs['value'],
                           min=self.min_attrs['value'],
                           name=name,
                           container_style=self.CON_STYLE,
                           style=self.INPUT_STYLE)
        return mark_safe(html)

这是我使用MultiWidget的字段

class TotalTimeField(forms.MultiValueField):
    def __init__(self, *args, **kwargs):
        hours = 0
        minutes = 0
        if 'hours' in kwargs:
            hours = kwargs['hours']
            del kwargs['hours']
        if 'minutes' in kwargs:
            minutes = kwargs['minutes']
            del kwargs['minutes']
        self.widget = TotalTimeWidget(name='total_time', hours=hours, minutes=minutes)
        list_fields = [
            forms.IntegerField(),
            forms.IntegerField(),
        ]
        super(TotalTimeField, self).__init__(list_fields, *args, **kwargs)

    def compress(self, data_list):
        print('Compress called', data_list)
        if data_list:
            return " ".join(data_list)

这是视图:

def test_view(request):
    form = ILSTimeAndServiceTrackingForm()
    data = dict()
    data['participant'] = Participant.objects.get_participant_by_id(2)
    if request.POST:
        print(request.POST)
        print(request.POST.get('total_travel_time'))
    data['form'] = form
    return render(request, '../templates/tests/widget_test.html', data)

1 个答案:

答案 0 :(得分:0)

对于多个值,有一种特殊的方法:QueryDict.getlist()

尝试从以下位置更改代码

print(request.POST.get('total_travel_time'))

收件人:

print(request.POST.getlist('total_travel_time'))

让我们知道是否有帮助。


由于QueryDict.__getitem__ or QueryDict.get的文档说:

  

如果键具有多个值,则返回最后一个值。