【问题标题】:django admin 1.11 add an attribute to the options of a selectdjango admin 1.11 为选择的选项添加一个属性
【发布时间】:2018-02-22 01:00:33
【问题描述】:

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

我想添加一个链接属性到:

<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

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

【问题讨论】:

  • 这里没有显示任何相关代码。你的模板、表单、视图是什么样的?
  • 有一个适用于 Django 2.+ 的通用解决方案,并允许在选项中添加标题和其他内容,请参阅stackoverflow.com/a/56097149/1788851

标签: django django-forms django-admin django-widget


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2019-03-21
    • 2018-10-06
    • 2012-07-02
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多