41

以下のようなdjangoモデルがあります

models.py

class Product(models.Model):
    name = models.CharField(max_length = 300)
    description = models.TextField(max_length = 2000)
    created = models.DateTimeField(auto_now_add = True)
    updated = models.DateTimeField(auto_now = True)

    def __unicode__(self):
        return self.name

フォーム.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')

product_form.py (ほんの一例)

 <form enctype="multipart/form-data" action="{% url 'add_a_product' %}" method="post">
         <div id="name">
           {{form.name}}
         </div> 
         <div id="description">
           {{form.description}}
         </div> 
   </form> 

実際には、以下のようなhtml出力を表示/レンダリングしたい

<input id="common_id_for_inputfields" type="text" placeholder="Name" class="input-calss_name" name="Name">

<input id="common_id_for_inputfields" type="text" placeholder="Description" class="input-calss_name" name="description">

最後に、上記のコードのモデル フォーム フィールドに属性 (id、プレースホルダー、クラス) を追加する方法は?

4

9 に答える 9

30

フィールド ID は、他のフィールドをオーバーライドするために、django によって自動的に生成される必要があります。

class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs\
            .update({
                'placeholder': 'Name',
                'class': 'input-calss_name'
            })
于 2013-10-21T08:54:14.513 に答える
19

以下のようにforms.pyを更新できます

class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')
        widgets={
                   "name":forms.TextInput(attrs={'placeholder':'Name','name':'Name','id':'common_id_for_imputfields','class':'input-class_name'}),
                   "description":forms.TextInput(attrs={'placeholder':'description','name':'description','id':'common_id_for_imputfields','class':'input-class_name'}),
                }  
于 2014-01-17T04:28:54.880 に答える
7

すべてのフォーム フィールドにブートストラップ クラスを追加する、優れた mariodev の回答のわずかに変更されたバージョンなので、各フィールドのフォーム入力ウィジェットを手動で再作成する必要はありません (短い Python 3.x super()):

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
            })
于 2015-06-23T11:35:49.450 に答える
2

次のことができます。

class ProductForm(ModelForm):
    name = forms.CharField(label='name ', 
            widget=forms.TextInput(attrs={'placeholder': 'name '}))
于 2015-06-03T20:49:26.460 に答える