導入相關模塊
from django import forms
from django.forms import fieldshtml
class F1Form(forms.Form): username = fields.CharField(max_length=18,min_length=2,required=True) pwd = fields.CharField(required=True,max_length=16,min_length=6) age = fields.IntegerField(required=True) email = fields.EmailField(required=True)
class F1Form(forms.Form): username = fields.CharField(max_length=18, min_length=6, required=True, error_messages={ 'required':'用戶名不能爲空', 'min_length':'用戶名太短', 'max_length':'用戶名過長' } )
views部分:數據庫
def rege(req): obj = F1Form() return render(req,'rege.html',{'OBJ':obj})
html部分:django
<form action=""> <p>{{ OBJ.username }}</p> <p>{{ OBJ.pwd }}</p> <p>{{ OBJ.age }}</p> <p>{{ OBJ.email }}</p> </form>
obj = F1Form(req.POST) if obj.is_valid(): #判斷傳來的值是否經過驗證 models.UserInfo.objects.create(**obj.cleaned_data) #將值寫入數據庫
~須要注意的是create(**obj.cleaned_data)方法寫入數據庫的方式,是在forms提交的name名跟數據庫的一致才能夠.ui