如何将类、id、占位符属性添加到 django 模型表单中的字段 [英] How to add class, id, placeholder attributes to a field in django model forms
本文介绍了如何将类、id、占位符属性添加到 django 模型表单中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面这样的 django 模型
models.py
class Product(models.Model):名称 = 模型.CharField(max_length = 300)描述 = 模型.TextField(max_length = 2000)created = models.DateTimeField(auto_now_add = True)更新 = 模型.DateTimeField(auto_now = True)def __unicode__(self):返回 self.name
forms.py
class ProductForm(ModelForm):元类:型号 = 产品exclude = ('更新', '创建')
product_form.py(只是一个例子)
<div id="描述">{{form.description}}
</表单>
实际上我想显示/渲染如下所示的 html 输出
<input id="common_id_for_inputfields" type="text" placeholder="Description" class="input-calss_name" name="description">
那么最后如何在上面的代码中为模型表单字段添加属性(id,占位符,类)?
解决方案
您可以执行以下操作:
#forms.py类 ProductForm(ModelForm):元类:型号 = 产品exclude = ('更新', '创建')def __init__(self, *args, **kwargs):super(ProductForm, self).__init__(*args, **kwargs)self.fields['description'].widget = TextInput(attrs={'id': 'myCustomId','class': 'myCustomClass','name': 'myCustomName','占位符':'myCustomPlaceholder'})
I have a django model like below
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
forms.py
class ProductForm(ModelForm):
class Meta:
model = Product
exclude = ('updated', 'created')
product_form.py(just an example)
<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>
Actually I want to display/render the html output like below
<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">
So finally how to add attributes(id, placeholder, class)to the model form fields in the above code ?
解决方案
You can do the following:
#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'})
这篇关于如何将类、id、占位符属性添加到 django 模型表单中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文