django表单小部件呈现

时间:2011-04-12 20:49:18

标签: python django django-forms

嘿伙计们,我想创建一个以下列格式呈现手机字段的小部件

box - box2 - box3

我尝试过在同一个网站上提供的不同代码片段,但是他们不会覆盖html渲染,这就是我想做的事情

例如:

class USPhoneNumberMultiWidget(forms.MultiWidget):
"""
A Widget that splits US Phone number input into three <input type='text'> boxes.
"""
def __init__(self,attrs=None):
    widgets = (
        forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
        forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
        forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}),
    )
    super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)

def decompress(self, value):
    if value:
        return value.split('-')
    return (None,None,None)

def value_from_datadict(self, data, files, name):
    value = [u'',u'',u'']
    # look for keys like name_1, get the index from the end
    # and make a new list for the string replacement values
    for d in filter(lambda x: x.startswith(name), data):
        index = int(d[len(name)+1:]) 
        value[index] = data[d]
    if value[0] == value[1] == value[2] == u'':
        return None
    return u'%s-%s-%s' % tuple(value)

呈现html输入:

box|box2|box3

所以如何覆盖渲染以使其呈现:

box - box2 - box3

我还要感谢任何解释如何创建自定义小部件的文档,到目前为止我还没有找到任何

models.py:

class Preference(models.Model):
    phone = models.PositiveIntegerField(blank=True)

class PreferenceForm(ModelForm):

    class Meta:
        model = Preference
        widgets = {
            'phone':USPhoneNumberMultiWidget(attrs={'class':'firstnumberbox', 'id':'firstcellphone', 'name':'firstphone'}),

呈现的HTML:

<dt><label for="firstcellphone"> Cell Phone:</label></dt> 
        <dd class="phones"><input name="firstphone" id="firstcellphone_0" maxlength="3" type="text" class="firstnumberbox" size="3" /> - <input name="firstphone" id="firstcellphone_1" maxlength="3" type="text" class="firstnumberbox" size="3" /> - <input name="firstphone" id="firstcellphone_2" maxlength="4" type="text" class="firstnumberbox" size="4" /></dd>

1 个答案:

答案 0 :(得分:2)

您可以覆盖MultiWidget的format_output方法:

def format_output(self, rendered_widgets):
        return u'%s - %s - %s' % \
            (rendered_widgets[0], rendered_widgets[1], rendered_widgets[2])

自定义表单小部件上没有大量文档。我只做了几个,他们花了很多时间修补。希望有所帮助!