首页 文章

如何将数据属性添加到django modelform modelchoicefield

提问于
浏览
2

我有一个带有外键字段的django modelform'Recipe'到模型'Ingredient' .

渲染表单时,我得到一个SELECT列表,其ID与成分ID匹配,文本显示等于字段的字符串表示 .

但是,我想在选择列表中添加一个数据属性,该数据属性与Ingredient查询集中的呈现选项相匹配 .

例如,假设这是当前正在呈现的内容:

<option value="1158">Carrots</option>
<option value="1159">Strawberry</option>
<option value="1160">Onion</option>
<option value="1161">Spinach</option>

但我想为相关对象添加数据属性:

<option value="1158" data-ingredient-type="vegetable">Carrots</option>
<option value="1159" data-ingredient-type="fruit">Strawberry</option>
<option value="1160" data-ingredient-type="vegetable">Onion</option>
<option value="1161" data-ingredient-type="vegetable">Spinach</option>

1 回答

  • 1

    为什么不render the fields manually
    它会是这样的

    <select>
      {% for option in form.ingredient.choices %}
         <option value="{{ option.id }}" data-ingredient-type={{ option.type }}>{{ option.name }}</option>
      {% endfor %}
    </select>
    

    或者也许在你的模型表单类中添加attribute,但这必须是一个字符串(或者可能是一个函数)

    widgets = { ...
         'ingredients' = forms.Select(attrs={'data-ingredient-type': 'fruit'}),
       ...}
    

相关问题