Django custom widget - unzip () arg not populated

As an exercise, I'm trying to create my own django widget for a 24-hour clock. The widget will be a MultiWidget - a selection field for each field.

I'm trying to keep track of documents online (seemingly sparse) and look at the Pro Django book, but I can't figure out what it is. Am I on the right track? I can save my data from the form, but when I pre-fill the form, the form has no previous values.

It seems that the problem is that the argument of the method “value” of the decompression method () is always empty, so I have nothing to interpret.

from django.forms import widgets

import datetime

class MilitaryTimeWidget(widgets.MultiWidget):
    """
    A widget that displays 24 hours time selection.
    """
    def __init__(self, attrs=None):
        hours = [ (i, "%02d" %(i)) for i in range(0, 24) ]
        minutes = [ (i, "%02d" %(i)) for i in range(0, 60) ]
        _widgets = (
            widgets.Select(attrs=attrs, choices=hours), 
            widgets.Select(attrs=attrs, choices=minutes),
            )
        super(MilitaryTimeWidget, self).__init__(_widgets, attrs)

    def decompress(self, value):
        print "******** %s" %value
        if value:
            return [int(value.hour), int(value.minute)]
        return [None, None]

    def value_from_datadict(self, data, files, name):
        hour = data.get("%s_0" %name, None)
        minute = data.get("%s_1" %name, None)
        if hour and minute:
            hour = int(hour)
            minute = int(minute)
            return datetime.time(hour=hour, minute=minute)
        return None

In my form, I call the widget as:

arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())
+3
source share
2

docstring MultiWidget:

, MultiValueField.

. , ( , Pro Django, , , , , ), " t - MultiWidget.

( MultiWidget/MultiValueField):

  • value_from_datadict
  • MultiValueField compress(), , value_from_datadict() ( datetime.time)
  • ( )
  • Field, Field formfield(), ModelForm.

.

+3

:

>>> class MyForm(forms.Form):
...     t = forms.TimeField(widget=MilitaryTimeWidget())
...
>>> print MyForm(data={'t_0': '13', 't_1': '34'})
******** 13:34:00
<tr><th><label for="id_t_0">T:</label></th><td><select name="t_0" id="id_t_0">
<option value="0">00</option>
[...]
<option value="13" selected="selected">13</option>
[...]
<option value="23">23</option>
</select><select name="t_1" id="id_t_1">
<option value="0">00</option>
[...]
<option value="34" selected="selected">34</option>
[...]
<option value="59">59</option>
</select></td></tr>

.POST.

, , ? ...

0

Source: https://habr.com/ru/post/1703068/


All Articles