项目
1、在models中添加属性(type_ini):
2、在forms中修改,便于渲染,增加fields,widgets,labels的属性
3、在views中找到对应渲染的位置:
4、查看html源码即可。
具体演示
1、在model中定义
#models.py
class Contact(models.Model):
title = models.CharField(max_length=30)
content = models.CharField(max_length=20)
2、在form中进行使用
#form.py
class ConotactForm(ModelForm):
class Meta:
model = Contact
field = ('title','content') #只显示model中指定的字段
3、在view中使用form
# view.py
form django.shortcuts import render
form django.http import HttpResponseRedirect
def contact(request):
if request.method=="POST":
form = ContactForm(request.POST)
if form.is_valid(): #所有验证都通过
#do something处理业务
return HttpResponseRedirect('/')
else:
form = ContactForm()
return render(request,'contact.html',{'form':form})
4、在模板中具体使用
# contact.html
<form action='/contact/' method='POST'>
{% for field in form %}
<div class = 'fieldWrapper'>
{{field.label_tag}}:{{field}}
{{field.errors}}
</div>
{% endfor %}
<div class='fieldWrapper'> <p><input type='submit' value='留言'></p></div>
</form>