How to add attributes to option tags in django ?

后端 未结 6 2040
闹比i
闹比i 2020-12-14 11:01

I have to add title attribute to options of the ModelChoiceField. Here is my admin code for that:

class LocModelForm(forms.ModelForm):
        def __init__(s         


        
6条回答
  •  甜味超标
    2020-12-14 11:28

    Here is a solution if you want to use the instance to set the attribute value.

    class IconSelectWidget(forms.Select):
        def create_option(self, name, value, *args, **kwargs):
            option = super().create_option(name, value, *args, **kwargs)
            if value:
                icon = self.choices.queryset.get(pk=value)  # get icon instance
                option['attrs']['title'] = icon.title  # set option attribute
            return option
    
    class LocModelForm(forms.ModelForm):
        icons = forms.ModelChoiceField(
            queryset=Photo.objects.filter(galleries__title_slug='markers'),
            widget=IconSelectWidget
        )
    

提交回复
热议问题