django admin 1.11 向 select 的选项添加一个属性

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

在 django 1.11 admin 中,我有一个列表字段,我会在 <select>

的每个 <option> 中添加一个属性

目前我有

<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>

我想添加一个 link 属性到 :

<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>

我测试了以下堆栈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

您知道如何正确添加属性吗?

我的灵感来自 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())