Значение a
будет b
, но значение [1 110] выражение будет c
. Таким образом, в
d = (a = b, c);
быть равным b
, и d
был бы равен c
.
Что вам нужно сделать, так это изменить вывод, которым управляет виджет. По умолчанию это виджет выбора, поэтому вы можете создать его подкласс. Выглядит это так:
class Select(Widget):
def __init__(self, attrs=None, choices=()):
super(Select, self).__init__(attrs)
# choices can be any iterable, but we may need to render this widget
# multiple times. Thus, collapse it into a list so it can be consumed
# more than once.
self.choices = list(choices)
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select%s>' % flatatt(final_attrs)]
options = self.render_options(choices, [value])
if options:
output.append(options)
output.append('</select>')
return mark_safe(u'\n'.join(output))
def render_options(self, choices, selected_choices):
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)))
# 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)
Это много кода. Но что вам нужно сделать, так это создать свой собственный виджет с измененным методом рендеринга. Это метод рендеринга, который определяет создаваемый HTML. В данном случае вам нужно изменить метод render_options
. Здесь вы можете включить некоторую проверку, чтобы определить, когда добавлять класс, который вы могли бы стилизовать.
Еще одна вещь, в вашем коде выше не похоже, что вы добавляете последний выбор группы. Также вы можете добавить order_by ()
в набор запросов, так как вам нужно, чтобы он был упорядочен по типу. Вы можете сделать это в методе инициализации, поэтому не
Вы не должны возиться с полями формы для добавления некоторых настраиваемых атрибутов к отображаемому тегу html. Но вы должны создать подкласс и добавить их к виджету.
Из docs: customizing-widget-instance
Вы можете отправить словарь attrs
в форму Виджеты, которые отображаются как атрибуты на виджетах формы вывода.
class CommentForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(attrs={'class':'special'}))
url = forms.URLField()
comment = forms.CharField(
widget=forms.TextInput(attrs={'size':'40'}))
Django will then include the extra attributes in the rendered output:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special"/></td></tr>
<tr><th>Url:</th><td><input type="text" name="url"/></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40"/></td></tr>