Django的Form主要具備一下幾大功能:html
from django import forms class FM(forms.Form): # 根據form表單中的name來作 username = fields.CharField( error_messages={'required':'用戶名不能爲空'}, ) pwd = fields.CharField( error_messages={'required':'密碼不能爲空','min_length':'請填寫6位以上密碼','max_length':'請填寫12位如下密碼'}, min_length=6, max_length=12, ) email = fields.EmailField( error_messages={'required':'郵箱不合法','invalid':'郵箱格式不正確'} )
def index(request): if request.method == 'GET': # 解決錯誤提示後內容清空的問題 obj = FM() return render(request,'form_index.html',{'obj': obj}) elif request.method == 'POST': # 獲取用戶全部數據 # 每條數據請求驗證 # 成功:獲取用戶提交的數據 # 失敗:顯示錯誤信息 obj = FM(request.POST) # 驗證是否合法 ret = obj.is_valid() if ret: print('obj.clean****',obj.clean()) print('obj.clead_data*****',obj.cleaned_data) else: print('obj.errors****',obj.errors) print('obj.errors.as_json()*****',obj.errors.as_json()) print('obj****',obj) # from django.forms.utils import ErrorDict # obj.errors爲ErrorDict類型,因此應該按照字典的方法獲取值 print(type(obj.errors)) return render(request,'form_index.html',{'obj': obj,'error_msg': obj.errors})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form驗證組件</title> <style> .usernameTF{ background-color: coral; color: aqua; } </style> </head> <body> <form action="/form_app/index" method="post"> {% csrf_token %} <p><input type='text' name='username'/> {{ error_msg.username.0 }}</p> <p><input type='text' name='pwd'/> {{ error_msg.pwd.0 }}</p> <p><input type='text' name='email'/> {{ error_msg.email.0 }}</p> <p><input type="submit" value="提交"></p> </form> </body> </html>
主要涉及widget的使用、初始化默認值,以及記錄上次填寫的值數據庫
from django import forms from django.forms import widgets from django.forms import fields class FM(forms.Form): # 根據form表單中的name來作 username = fields.CharField( error_messages={'required':'用戶名不能爲空'}, widget=widgets.Textarea(attrs={'class':'usernameTF'}) ) pwd = fields.CharField( error_messages={'required':'密碼不能爲空','min_length':'請填寫6位以上密碼','max_length':'請填寫12位如下密碼'}, min_length=6, max_length=12, widget=widgets.PasswordInput ) email = fields.EmailField(error_messages={'required':'郵箱不合法','invalid':'郵箱格式不正確'})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form驗證組件</title> <style> .usernameTF{ background-color: coral; color: aqua; } </style> </head> <body> <form action="/form_app/index" method="post"> {% csrf_token %} <p>{{ obj.username }} {{ error_msg.username.0 }}</p> <p>{{ obj.pwd }} {{ error_msg.pwd.0 }}</p> <p>{{ obj.email }} {{ error_msg.email.0 }}</p> <p>{{ obj.user }}</p> <p><input type="submit" value="提交"></p> </form> </body> </html>
def index(request): if request.method == 'GET': # 加載默認值 initial_dic = { 'username': 'root', 'pwd': '12345678', 'email': '953995648@qq.com', 'user': True } obj = FM(initial_dic) return render(request,'form_index.html',{'obj': obj}) elif request.method == 'POST': # 獲取用戶全部數據 # 每條數據請求驗證 # 成功:獲取用戶提交的數據 # 失敗:顯示錯誤信息 obj = FM(request.POST) # 驗證是否合法 ret = obj.is_valid() if ret: print('obj.clean****',obj.clean()) print('obj.clead_data*****',obj.cleaned_data) else: print('obj.errors****',obj.errors) print('obj.errors.as_json()*****',obj.errors.as_json()) print('obj****',obj) # from django.forms.utils import ErrorDict # obj.errors爲ErrorDict類型,因此應該按照字典的方法獲取值 print(type(obj.errors)) return render(request,'form_index.html',{'obj': obj,'error_msg': obj.errors})
在使用選擇標籤時,須要注意choices的選項能夠從數據庫中獲取,可是因爲是靜態字段 ***獲取的值沒法實時更新***,那麼須要自定義構造方法從而達到此目的。django
方式一:json
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.Select ) def __init__(self, *args, **kwargs): super(MyForm,self).__init__(*args, **kwargs) # self.fields['user'].widget.choices = ((1, '上海'), (2, '北京'),) # 或 self.fields['user'].widget.choices = models.Classes.objects.all().value_list('id','caption')
方式二:app
使用django提供的ModelChoiceField和ModelMultipleChoiceField字段來實現ide
from django import forms from django.forms import fields from django.forms import widgets from django.forms import models as form_model from django.core.exceptions import ValidationError from django.core.validators import RegexValidator class FInfo(forms.Form): authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())