django radioselect 渲染到表

发布于 2024-10-17 11:06:38 字数 370 浏览 2 评论 0原文

我想将 django 表单小部件 radioselect 渲染到表中而不是 ul 列表中。标签位于第一行,单选按钮位于第二行下方。每个按钮一个单元格。例如,

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

我查看了默认的 selectradio 小部件,但渲染函数似乎很复杂,调用许多不同的类来完成渲染的每个部分。

有谁有如何执行此操作的示例或可以提供简单的解决方案吗?

I want to render the django form widget radioselect into a table rather than a ul list. With labels in the first row and the radio buttons below in the second row. One cell for each button. e.g.

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

I've looked at the default selectradio widget but the render function seems so complicated, calling many different classes to do each part of the render.

Does anyone have any examples of how to do this or could provide a simple solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

说不完的你爱 2024-10-24 11:06:38

只是为了补充一点 Béres 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)”

我希望有帮助!

Just to fill in a bit more of Béres Botond's answer

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

The custom renderer would look like:

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 ] )))

In this case I didn't want the name of the radio box next to it, so I am using "force_unicode(w.tag())" If you wanted the name next to it, just render the object directly like "force_unicode(w)"

I hope that helps!

眉目亦如画i 2024-10-24 11:06:38

您需要子类化django.forms.widgets.RadioFieldRenderer并重写它的render方法。
然后在您的表单中,在声明字段时指定小部件的自定义渲染器

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

You need to subclass django.forms.widgets.RadioFieldRenderer and override it's render method.
Then in your form, when declaring your field specify the custom renderer for the widget

class MyForm(forms.ModelForm):
    my_field = forms.TypedChoiceField(choices=some_choices,
                                      label=u"bla",
                                      widget=forms.RadioSelect(renderer=MyCustomRenderer))
兮子 2024-10-24 11:06:38

您还可以使用 django-uni-form 并使用 div 而不是表格。

You could also use django-uni-form and use divs instead of tables.

信愁 2024-10-24 11:06:38

如果您需要进一步自定义输入元素,请覆盖自定义渲染器上的 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 源代码,仅稍加修改以显示每个方法中简单自定义的应用程序。

If you need to customize the input elements further, overwrite the choice_input_class attribute on the custom renderer.

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))

These render() and tag() methods are from the 1.9 source code, modified only slightly to show the application of a simple customization in each.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文