2011-02-16 41 views
2

我想呈现django表单部件radioselect到表而不是ul列表。第一行为标签,第二行为单选按钮。每个按钮一个单元格。例如django radioselect渲染到表

------------------------------- 
| label 1 | label 2 | label 3 | 
------------------------------- 
| O  | O | O | 
------------------------------- 

我看了默认selectradio组件,但是渲染功能似乎很复杂,要求许多不同的类来完成的渲染每一部分。

有没有人有任何如何做到这一点或可以提供一个简单的解决方案的例子?

回答

2

你需要继承django.forms.widgets.RadioFieldRenderer并重写它的渲染方法。 然后在你的表格,声明你字段中指定的自定义渲染用于微

class MyForm(forms.ModelForm): 
    my_field = forms.TypedChoiceField(choices=some_choices, 
             label=u"bla", 
             widget=forms.RadioSelect(renderer=MyCustomRenderer)) 
7

只需填写一份更有点贝雷斯Botond的回答

class MyForm(forms.ModelForm): 
    my_field = forms.TypedChoiceField(choices=some_choices, 
             label=u"bla", 
             widget=forms.RadioSelect(renderer=MyCustomRenderer)) 

定制渲染器看起来像:

from django import forms 
from django.forms.widgets import RadioFieldRenderer 
from django.utils.encoding import force_unicode 
from django.utils.safestring import mark_safe 

class MyCustomRenderer(RadioFieldRenderer): 
    def render(self): 
     """Outputs a series of <td></td> fields for this set of radio fields.""" 
     return(mark_safe(u''.join([ u'<td>%s</td>' % force_unicode(w.tag()) for w in self ]))) 

在这种情况下,我不想让单选框的名称所以我使用的是“force_unicode(w.tag())”如果你想要它旁边的名字,只需像“force_unicode(w)”那样直接渲染对象。

我希望有帮助!

0

如果您需要进一步自定义输入元素,请覆盖自定义渲染器上的choice_input_class属性。

from django.forms.widgets import RadioChoiceInput, RadioFieldRenderer 
from django.utils.safestring import mark_safe 
from django.utils.html import format_html 

class MyCustomRenderer(RadioFieldRenderer): 
    choice_input_class = MyCustomInputClass 

class MyCustomInputClass(RadioChoiceInput): 
    def render(self, name=None, value=None, attrs=None, choices=()): 
     # Generate outer label, insert a custom div 
     output = format_html(''' 
      <div id="{}"></div> 
     ''', self.choice_label) 
     if self.id_for_label: 
      label_for = format_html(' for="{}"', self.id_for_label) 
     else: 
      label_for = '' 
     attrs = dict(self.attrs, **attrs) if attrs else self.attrs 
     return format_html('<label{}>{} {}</label>', 
          label_for, self.tag(attrs), output) 

    def tag(self, attrs=None): 
     # Generate the customized input element. 
     attrs = attrs or self.attrs 
     final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value) 
     if self.is_checked(): 
      final_attrs['checked'] = 'checked' 
     return format_html('<input{} class="my_custom_class" />', flatatt(final_attrs)) 

这些render()tag()方法是从1.9源代码,改性仅略微显示中的每一个简单的定制的应用程序。