如何为DJANGO FORM MODEL标签元素添加一些额外的标签?我全读尝试更改form.py/class META / widgets内的内容,但一无所获。
class MySelect( forms.Select ):
def __init__( self, attrs = None, choices = (), option_xtra_attr = '' ):
self.option_xtra_attr = option_xtra_attr
super( MySelect, self ).__init__( attrs, choices )
def render_option( self, selected_choices, option_value, option_label, option_xtra_attr = '' ):
if option_value is None:
option_value = ''
option_value = force_text( option_value )
if option_value in selected_choices:
selected_html = mark_safe( ' selected="selected"' )
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove( option_value )
else:
selected_html = ''
return format_html( '<option value="{}"{}{}>{}</option>',
option_value,
selected_html,
option_xtra_attr,
force_text( option_label ) )
class MonitoringSpot_InLine_FORM( forms.ModelForm ):
class Meta:
model = MonitoringSpotClass
fields = [ 'monitoringSpot_NODE_monitoringAreaType', ]
widgets = {
'monitoringSpot_NODE_monitoringAreaType': MySelect( option_xtra_attr = { 'xdata': 'value' } )
}
答案 0 :(得分:0)
效果更好 类OptionAttr(forms.Select):
def __init__( self, *args, **kwargs ):
self.src = kwargs.pop( 'attributes', { } )
super().__init__( *args, **kwargs )
def create_option( self, name, value, label, selected, index, subindex = None, attrs = None ):
splitedLabel = label.split(",")
options = super( OptionAttr, self ).create_option( name, value, label, selected, index, subindex = None, attrs = None )
for k, v in self.src.items():
if v != True:
options[ 'attrs' ][ k ] = v
else:
options[ 'attrs' ][ k ] = splitedLabel[1:]; options[ 'label' ] = str(splitedLabel[0])
return options
class MonitoringSpot_InLine_FORM( forms.ModelForm ):
class Meta:
model = MonitoringSpotClass
fields = [ 'monitoringSpot_NODE_monitoringAreaType', ]
widgets = {
'monitoringSpot_NODE_monitoringAreaType': OptionAttr( attributes = { 'extra': True } )
}
如果将True设置为extra属性,则此代码会将LABEL中的所有数据拆分为一个额外的标签。或者,您可以设置自己的值。