这里有一个很好的解释,就是在django表单字段中为<option>标签添加属性。 但这仅适用于Select 小部件 。 我想对SelectMultiple 小部件做同样的SelectMultiple 。
我尝试了以下(子类Select和SelectMultiple并在创建Model表单字段employees时引用MySelectMultiple ):
class MySelect(forms.Select): def __init__(self, *args, **kwargs): super(MySelect, self).__init__(*args, **kwargs) def render_option(self, selected_choices, option_value, option_label): # original forms.Select code # return u'<option custom_attribute="foo">...</option>' class MySelectMultiple(MySelect): def __init__(self, *args, **kwargs): super(MySelectMultiple, self).__init__(*args, **kwargs) employees = forms.ModelMultipleChoiceField( widget=MySelectMultiple(attrs={}), queryset=Employee.objects.all(), )但渲染的表单仍显示为Select小部件,而不是SelectMultiple小部件。
我可以向MySelectMultiple提供attrs={'multiple':'multiple'}以使表单字段呈现为多选小部件 - 但是当保存表单时,只保存一个值(不是多个值)!
如何将表单呈现为多选字段并保存所有选定的值? 谢谢。
There's a great explanation here on adding attributes to <option> tags within a django form field. But this is only for a Select widget. I want to do the same for a SelectMultiple widget.
I tried the following (subclass Select and SelectMultiple and reference MySelectMultiple when creating the Model form field employees):
class MySelect(forms.Select): def __init__(self, *args, **kwargs): super(MySelect, self).__init__(*args, **kwargs) def render_option(self, selected_choices, option_value, option_label): # original forms.Select code # return u'<option custom_attribute="foo">...</option>' class MySelectMultiple(MySelect): def __init__(self, *args, **kwargs): super(MySelectMultiple, self).__init__(*args, **kwargs) employees = forms.ModelMultipleChoiceField( widget=MySelectMultiple(attrs={}), queryset=Employee.objects.all(), )But the rendered form is still showing as a Select widget, not a SelectMultiple widget.
I can provide attrs={'multiple':'multiple'} to MySelectMultiple to make the form field render as a multiple select widget - but when the form is saved, only a single value is saved (not multiple values)!
How can I have the form render as a multiple choice field AND save all of the selected values? Thank you.
最满意答案
您的选择倍数应该继承自SelectMultiple而不是Select :
class MySelectMultiple(SelectMultiple): def render_option(self, selected_choices, option_value, option_label): # original forms.Select code # return u'<option custom_attribute="foo">...</option>'看起来你的__init__方法不是必需的,因为它只调用super() 。
Your select multiple should inherit from SelectMultiple rather than Select:
class MySelectMultiple(SelectMultiple): def render_option(self, selected_choices, option_value, option_label): # original forms.Select code # return u'<option custom_attribute="foo">...</option>'It looks like your __init__ method isn't necessary, since it just calls super().
更多推荐
发布评论