0

How can we add some extra tags to DJANGO FORM MODEL tag element? I all-read tried change something inside form.py/class META/widgets but without nothing.

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' } )
        }
Fernando Cesar
  • 131
  • 2
  • 6
  • There is a general solution which works for Django 2.+ and allows to add a title and other things in options, see https://stackoverflow.com/a/56097149/1788851 – Edouard Thiel May 12 '19 at 12:01

1 Answers1

0

It's works better class 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 } )
        }

If you set True to extra attribute this code will split all data from LABEL into a extra tag. Or you can set your own value.

Fernando Cesar
  • 131
  • 2
  • 6