2014-10-16 33 views
0

我已經爲Django中的表單字段編寫了一個自定義小部件,而且我看到了我想要的那種HTML輸出,但該字段未被返回到cleaned_data使用自定義小部件時丟失了Django表單字段數據

HTML是頁面中表單的一部分,所以我的小部件有問題嗎?

# forms.py 

class EntrantDetails(forms.Form): 
    TITLE_CHOICES = (
     ('', 'Select:'), 
     ('Mr', 'Mr'), 
     ('Mrs', 'Mrs'), 
     ('Miss', 'Miss'), 
     ('Ms', 'Ms'), 
     ('Dr', 'Dr'), 
    ) 
    GENDER_CHOICES = (
     ('M', 'male'), 
     ('F', 'female'), 
    ) 
    title = forms.CharField(
     max_length=20, 
     widget=forms.widgets.Select(choices=TITLE_CHOICES) 
    ) 
    first_name = forms.CharField(max_length=200) 
    middle_names = forms.CharField(
     label='Middle name(s)', 
     max_length=200, required=False 
    ) 
    last_name = forms.CharField(max_length=200) 
    date_of_birth = forms.DateField(
     widget=SelectDateWidget(years=range(2015, 1900, -1)) 
    ) 
    gender = forms.CharField(
     max_length=1, 
     widget=ButtonSelectWidget(cls='test_class', choices=GENDER_CHOICES) 
    ) 


# widgets.py 

class ButtonSelectWidget(Widget): 
    """ 
    Custom widget to display a choice field more like selectable buttons. 
    """ 

    def __init__(self, attrs=None, cls=None, choices=None): 
     self.attrs = attrs or {} 
     self.cls = cls 
     self.choices = choices 

    def render(self, name, value, attrs=None, choices=()): 
     if not choices: 
      choices = self.choices 
     output = [] 
     output.append(u'<div class="controls">') 

     for choice in choices: 
      label = u'{}'.format(choice[1]) 
      output.append(u''' 
      <div class="radio radio-{label}"> 
       <input id="user_{name}_{label}" name="user[{name}]" type="radio" value="{choice}"> 
       <label for="user_{name}_{label}">{title}</label> 
      </div> 
      '''.format(name=name, choice=choice[0], label=label, title=label.title())) 
     output.append(u'</div>') 


     return mark_safe(u'\n'.join(output)) 

回答

1

標記中的輸入名稱是錯誤的,所以表單不會收集它。取而代之的

<input id="user_{name}_{label}" name="user[{name}]" type="radio" value="{choice}"> 

你需要

<input id="user_{name}_{label}" name="{name}" type="radio" value="{choice}"> 

同時適用於Django表單控件id標準方案是id_<name>[_counter]

現在的Django已經有一個RadioSelect小部件,讓你同樣的功能,所以你會更好地使用它(在模板中使用你自己的特定標記),而不是在小部件中重新創建(平方)輪和硬編碼項目的特定模板。

+0

啊,這是有道理的。我決定採用這種方法,因爲模板已經是一個怪物,因爲它是一個表單嚮導組窗體的單個模板,我想避免進一步的條件塊。 – 2014-10-16 15:04:31

+1

您不需要條件來處理嚮導中的每個表單模板選擇......只需在上下文中傳遞正確的表單模板路徑,並在它上面傳遞「{%include%}」即可。 wrt/fields渲染,你可以1.使用默認標記或2.使用宏(https://pypi.python.org/pypi/django-templates-macros)或者一些更高級的軟件包如軟盤來應用你自己的標記到處。我的2分錢... – 2014-10-16 15:12:04

相關問題