代码之家  ›  专栏  ›  技术社区  ›  cethegeek

如何在HTML中设置ModelChoiceField选项的标题和类?

  •  1
  • cethegeek  · 技术社区  · 15 年前

    我有一个模型

    class MyModel(models.Model):
        name = models.CharField(max_length=80, unique=True)
        parent = models.ForeignKey('self', null=True, blank=True)
    

    我要为该模型呈现一个ModelChoiceField,其外观如下:

    <select name="mymodel" id="id_mymodel">
        <option value="1" title="Value 1" class="">Value 1</option>
        <option value="2" title="Value 2" class="Value 1">Value 2</option>
    </select>
    

    此输出与默认输出之间的差异 ModelChoiceField 是选项标记中的标题和类元素。它们不存在于 模式选择字段 的默认输出。

    出于我的目的:

    • title元素应该是选项名。
    • 类元素应该是 self.parent.name . ( 这是我的问题 )

    因此,在上面的HTML片段中,值1没有父级,值2有值1的父级。

    最好的改变机制是什么 模式选择字段 的默认HTML输出?


    编辑: 我了解如何创建一个新的小部件来呈现HTML。问题是如何在每个选项中呈现底层模型的值。

    2 回复  |  直到 15 年前
        1
  •  2
  •   cethegeek    15 年前

    您可以制作自己的小工具:

    from django.forms.widgets import Select 
    
    class MySelect(Select):
    
        def __init__(self, attrs=None, choices=(), model):
           self.model = model
           super(Select, self).__init__(attrs)
    
        def render_options(self, choices, selected_choices):
            def render_option(option_value, option_label):
                option_value = force_unicode(option_value)
                option = self.model.objects.get(pk=option_value)
                selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
                return u'<option value="%s"%s class="%s">%s</option>' % (
                    escape(option_value), selected_html,
                    str(obj.parent.name),
                    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 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))
            return u'\n'.join(output)
    

    如果您还希望看到字段的标签:Field类有一个方法 label_from_instance .

        2
  •  1
  •   Community Mohan Dere    8 年前

    查看我的示例,了解如何在 this post