如何在django中的选项标签中添加属性? [英] How to add attributes to option tags in django ?
问题描述
我必须向ModelChoiceField的选项添加title属性。这是我的管理员代码:
class LocModelForm(forms.ModelForm):
pre>
def __init __(self,* args,** kwargs):
super(LocModelForm,self).__ init __(* args,** kwargs)
self.fields ['icons'] = forms.ModelChoiceField(queryset = Photo.objects。过滤器(galleries__title_slug =markers))
self.fields ['icons']。widget.attrs ['class'] ='mydds'
class Meta:
model = Loc
widgets = {
'icons':forms.Select(attrs = {'id':'mydds'}),
}
class Media:
css = {
all:(/ media / css / dd.css,)
}
js =(
'媒体/ js / dd.js',
)
class LocAdmin(admin.ModelAdmin):
form = LocModelForm
我可以添加任何属性来选择小部件,但我不知道如何添加属性到选项标签。任何想法 ?
解决方案首先,不要修改
__ init __
如果要覆盖小部件,请使用Meta
内部类,如果要覆盖表单字段,请以普通(非模型)形式声明它们。
如果
选择
小部件不会做你想要的,那么只需自己做。原始小部件使用render_option
方法来获取单个选项的HTML表示 - 创建一个子类,覆盖它,并添加任何你想要的。class MySelect(forms.Select):
def render_option(self,selected_choices,option_value,option_label):
#看原始的东西以
开头返回u' < option whatever> ...< / option>'
class LocModelForm(forms.ModelForm):
icons = forms.ModelChoiceField(
queryset = Photo.objects。过滤器(galleries__title_slug =markers),
widget = MySelect(attrs = {'id':'mydds'})
)
class Meta:
# ...
#注意,如果你覆盖整个字段,你不必重写
#这个小部件
class Media:
#...
I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that:
class LocModelForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(LocModelForm,self).__init__(*args,**kwargs) self.fields['icons'] = forms.ModelChoiceField(queryset = Photo.objects.filter(galleries__title_slug = "markers")) self.fields['icons'].widget.attrs['class'] = 'mydds' class Meta: model = Loc widgets = { 'icons' : forms.Select(attrs={'id':'mydds'}), } class Media: css = { "all":("/media/css/dd.css",) } js=( '/media/js/dd.js', ) class LocAdmin(admin.ModelAdmin): form = LocModelForm
I can add any attribute to select widget, but i don't know how to add attributes to option tags. Any idea ?
解决方案First of all, don't modify fields in
__init__
, if you want to override widgets useMeta
inner class, if you want to override form fields, declare them like in a normal (non-model) form.If the
Select
widget does not do what you want, then simply make your own. Original widget usesrender_option
method to get HTML representation for a single option — make a subclass, override it, and add whatever you want.class MySelect(forms.Select): def render_option(self, selected_choices, option_value, option_label): # look at the original for something to start with return u'<option whatever>...</option>' class LocModelForm(forms.ModelForm): icons = forms.ModelChoiceField( queryset = Photo.objects.filter(galleries__title_slug = "markers"), widget = MySelect(attrs = {'id': 'mydds'}) ) class Meta: # ... # note that if you override the entire field, you don't have to override # the widget here class Media: # ...
这篇关于如何在django中的选项标签中添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!