我有一个像下面的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
表格
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,占位符,类)?
您可以执行以下操作:
#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'})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句