在django 1.11 admin中,我有一个列表字段,我会在<option>
的每个<select>
中添加一个属性
目前我有
<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,但函数render_option(self,selected_choices,option_value,option_label)不在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
您是否知道如何正确添加属性?
答案 0 :(得分:3)
我受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())