您可以制作自己的小工具:
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
.