Django表单字段选择,添加属性

PLANNING_CHOICES = (

('0',u'Every morning'),

('1',u'Every night'),

('2',u'Never'),

)

planning = forms.ChoiceField(

required=True,

choices = PLANNING_CHOICES,

)

有一个这样的表单字段,名为Planning,我需要将title属性添加到选择中,最后渲染如下:

                <select>

<option value="0" title="bla1">Every morning</option>

<option value="1" title="bla2">Every night</option>

<option value="2" title="bla3">Never</option>

</select>

如何实现?

回答:

你必须对该字段进行子类化,以采取任何方式指定你想要的标题以及显示新属性的小部件。

如果你有这样的事情(请注意:完全未经测试):

from django import forms

from django.utils.html import escape

from django.utils.encoding import force_unicode

class SelectWithTitles(forms.Select):

def __init__(self, *args, **kwargs):

super(SelectWithTitles, self).__init__(*args, **kwargs)

# Ensure the titles dict exists

self.titles = {}

def render_option(self, selected_choices, option_value, option_label):

title_html = (option_label in self.titles) and \

u' title="%s" ' % escape(force_unicode(self.titles[option_label])) or ''

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>%s</option>' % (

escape(option_value), title_html, selected_html,

conditional_escape(force_unicode(option_label)))

class ChoiceFieldWithTitles(forms.ChoiceField):

widget = SelectWithTitles

def __init__(self, choices=(), *args, **kwargs):

choice_pairs = [(c[0], c[1]) for c in choices]

super(ChoiceFieldWithTitles, self).__init__(choices=choice_pairs, *args, **kwargs)

self.widget.titles = dict([(c[1], c[2]) for c in choices])

…你应该能够做到这一点:

PLANNING_CHOICES_WITH_TITLES = (

('0', 'Every morning', 'bla1'),

('1', 'Every night', 'bla2'),

('2', 'Never', 'bla3'),

)

planning = forms.ChoiceFieldWithTitles(

required=True, choices=PLANNING_CHOICES_WITH_TITLES)

以上是 Django表单字段选择,添加属性 的全部内容, 来源链接: utcz.com/qa/411702.html

回到顶部