Search code examples
djangodjango-formsdjango-admindjango-widget

django admin 1.11 add an attribute to the options of a select


In django 1.11 admin, I have a list field and I would add an attribute in each <option> of my <select>

Currently I have

<select name = "example" id = "id_example">
   <option value = "" selected> --------- </ option>
   <option value = "480"> data1 </ option>
   <option value = "481"> data2 </ option>
   <option value = "482"> data3 </ option>
</select>

I would like to add a link attribute to :

<select name = "example" id = "id_example">
   <option value = "" selected> --------- </ option>
   <option value = "480" link = "1"> data1 </ option>
   <option value = "481" link = "1"> data2 </ option>
   <option value = "482" link = "2"> data3 </ option>
</select>

I tested the following stack Django form field choices, adding an attribute but the function render_option (self, selected_choices, option_value, option_label) is not in django 1.11 https://code.djangoproject.com/ticket/28308

# model.py

class ModelA(models.Model):
    id = models.AutoField(primary_key=True)
    fielda = models.ForeignKey('ModelB', blank=True, null=True,)


class ModelB(models.Model):
    id = models.AutoField(primary_key=True) # In select option is value
    name = models.CharField(max_length=254) # In select option is data
    link = models.Integer() # I would like a new attribute in select option link

    def __str__(self):
        return self.name


# admin.py

class ModelAInlinesForm(forms.ModelForm):
    fielda = forms.ModelChoiceField(
        queryset=ModelB.objects.all(),
        widget=forms.Select(attrs={'test': 'test1'}))
    class Meta:
        model = ModelA
        fields = "__all__"


class ModelAInlines(admin.TabularInline):
    model = ModelA
    extra = 0
    form = ModelAInlinesForm

Do you have any idea how to add an attribute properly?


Solution

  • I was inspired by https://djangosnippets.org/snippets/2453/

    class ModelAInlinesFormSelect(forms.Select):
    
        def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
    
            option_dict = super(SemisInlinesFormSelect, self).create_option(name, value, label, selected, index,
                                                                        subindex=subindex, attrs=attrs)
            if option_dict['value']:
                option_dict['attrs']['link'] = ModelB.objects.values().get(
                    id=option_dict['value'])['link_id']
            return option_dict
    
    
    class ModelAInlinesForm(forms.ModelForm):
        fielda = forms.ModelChoiceField(
            queryset=ModelB.objects.all(),
            widget=ModelAInlinesFormSelect())