按部就班Python3(十三) --3-- django之form表單(爲自動生成的html標籤添加樣式)

views.py
   
   
   
   
from django.shortcuts import render, HttpResponsefrom django import formsimport jsonimport refrom django.core.exceptions import ValidationError# Create your views here.def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手機號碼格式錯誤')class InputForm(forms.Form): # 下面使用的變量名必須和html中input標籤的name值相同 # forms 的字段類型包括:IntegerField,CharField,URLField,EmailField,DateField等,可是沒有手機號 # required=True表示對輸入作驗證 # error_messages 自定製提示信息 username = forms.CharField(required=True, error_messages={'required':'用戶名不能爲空'}) password = forms.CharField(required=True, min_length=8, max_length=20, error_messages={'required':'密碼不能爲空','min_length':'至少6位', 'max_length':'至多10位'} ) num = forms.IntegerField(error_messages={'required':'不能爲空', 'invalid':'必須是數字'}) # 自定製驗證方法關鍵就是參數validators,和本身的函數關聯起來 phone = forms.CharField(validators=[mobile_validate,],) # django給標籤加sytle,關鍵參數widget ,forms.TextInput 表示生成type="text"的input標籤,改爲Textarea則生成<textarea>標籤 test = forms.CharField(widget=forms.TextInput(attrs={'class': 'in_tmp'})) choice = ( (1,'北京'), (2,'上海') ) t_choice = forms.IntegerField(widget=forms.Select(choices=choice))def login(request): if request.POST: objPost = InputForm(request.POST) ret = objPost.is_valid() if ret: print(objPost.clean()) # else: # # from django.forms.utils import ErrorDict # print(type(objPost.errors),objPost.errors.as_json()) return render(request, 'login.html', {'data': objPost}) else: objGet = InputForm() return render(request, 'login.html',{'data': objGet})
login.html
   
   
   
   
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> .error-msg{ color:red; } .in_tmp{ border: 1px solid #6a34ff ; } </style></head><body> <form action="/login/" method="POST"> <div> <div> {{ data.username }} {% if data.errors.username %} <span class="error-msg">{{ data.errors.username.0 }}</span> {% endif %} </div> <div> {{ data.password }} {% if data.errors.password %} <span class="error-msg">{{ data.errors.password.0 }}</span> {% endif %} </div> <div> {{ data.num }} {% if data.errors.num %} <span class="error-msg">{{ data.errors.num.0 }}</span> {% endif %} </div> <div> {{ data.phone }} {% if data.errors.phone %} <span class="error-msg">{{ data.errors.phone.0 }}</span> {% endif %} </div> <div> {{ data.test }} {% if data.errors.test %} <span class="error-msg">{{ data.errors.test.0 }}</span> {% endif %} </div> <div> {{ data.t_choice }} {% if data.errors.t_choice %} <span class="error-msg">{{ data.errors.t_choice.0 }}</span> {% endif %} </div> <input type="submit" value="提交" /> </div> </form></body></html>
效果圖:
 
select 標籤顯示數據庫數據:
  


相關文章
相關標籤/搜索