Django Form常用功能及代碼示例
更新時間:2020年10月13日 10:00:08 作者:py魚
這篇文章主要介紹了Django Form常用功能及代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
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 Form
from django.forms import widgets
from 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 = True
for 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Keras中的兩種模型:Sequential和Model用法
這篇文章主要介紹了Keras中的兩種模型:Sequential和Model用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python讀取xlsx數(shù)據(jù)生成圖標(biāo)代碼實例
這篇文章主要介紹了Python讀取xlsx數(shù)據(jù)生成圖標(biāo)代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
Python使用multiprocessing實現(xiàn)多進程
當(dāng)我們工作中涉及到處理大量數(shù)據(jù)、并行計算或并發(fā)任務(wù)時,Python的multiprocessing模塊是一個強大而實用的工具,在本文中,我們將探索如何使用multiprocessing模塊實現(xiàn)多進程編程,將介紹進程池的概念和用法,需要的朋友可以參考下2024-10-10
python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式
這篇文章主要介紹了python數(shù)據(jù)分析之DateFrame數(shù)據(jù)排序和排名方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

