如何将类,id,占位符属性添加到django模型表单中的字段

Shi*_*dla 35 forms django attributes django-forms form-fields

我有一个像下面的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
Run Code Online (Sandbox Code Playgroud)

forms.py

class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')
Run Code Online (Sandbox Code Playgroud)

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> 
Run Code Online (Sandbox Code Playgroud)

其实我想显示/渲染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">
Run Code Online (Sandbox Code Playgroud)

那么最后如何将属性(id,占位符,类)添加到上面代码中的模型表单字段?

Ale*_*ich 46

您可以执行以下操作:

#forms.py
class ProductForm(ModelForm):
    class Meta:
        model = Product
        exclude = ('updated', 'created')

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget = TextInput(attrs={
            'id': 'myCustomId',
            'class': 'myCustomClass',
            'name': 'myCustomName',
            'placeholder': 'myCustomPlaceholder'})
Run Code Online (Sandbox Code Playgroud)

  • 这对我很有用,除了它从我的Select小部件中删除了所有选项.我发现你可以一起跳过小部件声明并仍然设置它的属性如下:`self.fields ['description'].widget.attrs = {'id':'myCustomId','class':'myCustomClass' ,'name':'myCustomName','placeholder':'myCustomPlaceholder'}`对我来说似乎也有点清洁. (5认同)

mar*_*dev 27

字段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'
            })
Run Code Online (Sandbox Code Playgroud)


小智 23

我真的很喜欢Dmitriy Sintsov的回答,但它不起作用.这是一个有效的版本:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    for field in iter(self.fields):
        self.fields[field].widget.attrs.update({
            'class': 'form-control'
    })
Run Code Online (Sandbox Code Playgroud)


小智 16

您可以更新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'}),
                }  
Run Code Online (Sandbox Code Playgroud)


Dmi*_*sov 6

稍作修改的mariodev最佳答案版本,将bootstrap类添加到所有表单字段,因此我不必手动为每个字段重新创建表单输入窗口小部件(简短的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'
            })
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用由“ self.Meta.fields”插入的“ self.fields”,它也可以工作。 (3认同)