Django Form常用功能及代碼示例
Django的Form主要具有一下幾大功能:
生成HTML標(biāo)簽 驗證用戶數(shù)據(jù)(顯示錯誤信息) HTML Form提交保留上次提交數(shù)據(jù) 初始化頁面顯示內(nèi)容views.py
from django.shortcuts import render# Create your views here.from django.forms import Formfrom django.forms import widgetsfrom django.forms import fields# 對form表單進行數(shù)據(jù)驗證class LoginForm(Form): user = fields.CharField(required=True) # 不能為空 pwd = fields.CharField(min_length=18)def login(request): if request.method == 'get': return render(request, ’login.html’) else: obj = LoginForm(request.POST)#request.POST拿到的是POST的數(shù)據(jù) ''' is_valid 1. 獲取當(dāng)前類中所有的字段 -LoginForm實例化時候,放入self.fields = { ’user’:正則表達(dá)式, ’pwd’:正則表達(dá)式} 2.循環(huán)self.fields flag = Truefor k,v in self.fields.items(): k是:user,pwd v是:正則表達(dá)式 input_value = requests.POST.get(k) flag = False return flag''' if obj.is_valid(): print(obj.cleaned_data)#字典數(shù)據(jù) else: # print(obj.errors)#返回的是個err對象 print(obj.errors)#返回的是個err對象 return render(request,’login.html’)
login.html
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title></head><body><h1>用戶登錄</h1><form action='/login/' method='POST'> {% csrf_token %} 用戶名 <input type='text' name='user'> 密碼 <input type='password' name='pwd'> <input type='submit' value='提交'></form></body></html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. java——Byte類/包裝類的使用說明2. android studio實現(xiàn)簡單的計算器(無bug)3. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作4. python Selenium 庫的使用技巧5. android 控件同時監(jiān)聽單擊和雙擊實例6. python+pywinauto+lackey實現(xiàn)PC端exe自動化的示例代碼7. vue使用exif獲取圖片經(jīng)緯度的示例代碼8. python logging.info在終端沒輸出的解決9. 詳解android adb常見用法10. Python 忽略文件名編碼的方法
