2011-04-12 91 views
1

嗨,我想創建呈現在以下格式Django的表單控件呈現

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> 

回答

2

您可以覆蓋MultiWidget的format_output方法:

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

沒有一噸的自定義表單控件文件。我只做了一對,他們花了很多修補。希望有所幫助!

+0

感謝您的回答,它在呈現表單時非常完美,但不幸的是該小部件沒有向數據庫提交任何內容,生病發布我的models.py conf原始問題 – Paulo 2011-04-13 01:56:24

+0

@paulo它可能有助於查看呈現的html ?也許輸入不是用ID進行渲染的? – 2011-04-13 02:07:41

+0

在一個用於腳和英寸的小部件中,我使用了Django片段:http://djangosnippets.org/snippets/2327/,我不必爲該id或名稱添加任何屬性,並且最終使用該小部件內聯和常規形式,沒有任何問題。我不確定爲什麼這些值不在POST中,但請查看該代碼段。它可能會讓你走向正確的方向。 – Brandon 2011-04-13 02:14:58