<option>使用Django Forms API </option>选择输入的电平控制

时间:2009-06-08 14:07:54

标签: python django django-forms

我想使用Django Forms API将一个label =属性添加到Select表单输入的option元素,而不会覆盖Select小部件的render_options方法。这是可能的,如果是的话,怎么样?

注意:我想直接在选项中添加标签(此 在XHTML Strict标准中有效)而不是选项组。

2 个答案:

答案 0 :(得分:2)

我刚写了一堂课来做到这一点:

from django.forms.widgets import Select
from django.utils.encoding import force_unicode
from itertools import chain
from django.utils.html import escape, conditional_escape


class ExtendedSelect(Select):
    """
    A subclass of Select that adds the possibility to define additional 
    properties on options.

    It works as Select, except that the ``choices`` parameter takes a list of
    3 elements tuples containing ``(value, label, attrs)``, where ``attrs``
    is a dict containing the additional attributes of the option.
    """

    def render_options(self, choices, selected_choices):
        def render_option(option_value, option_label, attrs):
            option_value = force_unicode(option_value)
            selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
            attrs_html = []
            for k, v in attrs.items():
                attrs_html.append('%s="%s"' % (k, escape(v)))
            if attrs_html:
                attrs_html = " " + " ".join(attrs_html)
            else:
                attrs_html = ""
            return u'<option value="%s"%s%s>%s</option>' % (
                escape(option_value), selected_html, attrs_html,
                conditional_escape(force_unicode(option_label)))
        # Normalize to strings.
        selected_choices = set([force_unicode(v) for v in selected_choices])
        output = []
        for option_value, option_label, option_attrs in chain(self.choices, choices):
            if isinstance(option_label, (list, tuple)):
                output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
                for option in option_label:
                    output.append(render_option(*option))
                output.append(u'</optgroup>')
            else:
                output.append(render_option(option_value, option_label,
                    option_attrs))
        return u'\n'.join(output)

示例:

select = ExtendedSelect(choices=(
        (1, "option 1", {"label": "label 1"}),
        (2, "option 2", {"label": "label 2"}),
    ))

答案 1 :(得分:1)

我担心,如果没有对Select窗口小部件进行子类化以提供自己的渲染,这是不可能的,正如您所猜测的那样。 code for Select不包含每个<option>项的任何属性。它涵盖了期权价值,“选定”状态和标签......这就是全部,我担心:

def render_option(option_value, option_label):
    option_value = force_unicode(option_value)
    selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
    return u'<option value="%s"%s>%s</option>' % (
        escape(option_value), selected_html,
        conditional_escape(force_unicode(option_label)))