首页 > 解决方案 > DJANGO

问题描述

我们如何向 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' } )
        }

标签: djangodjango-modelsdjango-formsdjango-admin

解决方案


类 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 设置为额外属性,则此代码会将 LABEL 中的所有数据拆分为额外标签​​。或者您可以设置自己的值。


推荐阅读