項目
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>