【问题标题】:Modify HTML output of Django ModelForm修改 Django ModelForm 的 HTML 输出
【发布时间】:2012-10-29 20:45:21
【问题描述】:

默认情况下,我的 django ModelForm 会生成一个 HTML 表单。我想通过在 select 元素中包含一个额外的属性来修改表单的 HTML 输出:

# models.py
class FoodForm(ModelForm):
    class Meta:
        model = Food
        fields = ('name', 'ingredients')

# default HTML output
<form action="/" method="post">
    <p>
        <label for="id_name">Name:</label>
        <input id="id_name" type="text" name="name" maxlength="30" />
    </p>
    <p>
        <label for="id_ingredients">Ingredients:</label> 
        <select multiple="multiple" name="ingredients" id="id_ingredients">
        <option value="1">Mozzarella</option>
        <option value="2">Cottage cheese</option>
        <option value="3">Onion</option>

我想添加一个新属性到选择字段并保持当前属性不变

# desired HTML output
<select multiple="multiple" name="ingredients" id="id_ingredients" data-placeholder="Choose ingredients...">

我尝试使用小部件(见下文)但它给了我一个错误:

class FoodForm(ModelForm):
    class Meta:
        model = Food
        fields = ('name', 'ingredients')
        widgets = {
            'ingredients': Select(attrs={'data-placeholder': "Choose ingredients..."}),
        }

# NameError: name 'Select' is not defined

任何想法如何修改 HTML 输出?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    需要导入小部件from django.forms

    from django import forms
    class FoodForm(forms.ModelForm):
        class Meta:
            model = Food
            fields = ('name', 'ingredients')
            widgets = {
                'ingredients': forms.Select(attrs={'data-placeholder': "Choose ingredients..."}),
            }
    

    【讨论】:

    • 谢谢,这行得通。是否有一些简单的方法来添加新属性?当前解决方案将所有属性替换为小部件中指定的属性。我当然可以明确定义每个属性,但有更好的方法吗?
    【解决方案2】:

    你只是忘了from django.forms.widgets import Select

    【讨论】:

      猜你喜欢
      • 2010-12-15
      • 2015-08-11
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多