Django - forms元件
阿新 • • 發佈:2018-11-19
一、校驗欄位功能
1、reg頁面準備
models
from django.db import models class UserInfo(models.Model): useranme = models.CharField(max_length=32) password = models.CharField(max_length=32) email = models.EmailField() telephone = models.CharField(max_length=32)
生成資料表
python manage.py makemigrations python manage.py migrate
常規的form
路由層urls
from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('reg/', views.reg), ]
檢視層views:
def reg(request): if request.method=='POST': print(request) pwd=request.POST.get('pwd') re_pwd=request.POST.get('re_pwd') if pwd==re_pwd: print(request.POST) return HttpResponse('註冊成功') else: return HttpResponse('密碼錯誤') return render(request,'reg.html')
模板層.html
<body> <form action="" method="post"> {% csrf_token %}<p>使用者名稱<input type="text" name="user"></p> <p>密碼<input type="password" name="pwd"></p> <p>確認密碼<input type="password" name="re_pwd"></p> <p>電話<input type="number" name="tel"></p> <p>郵箱<input type="email" name="email"></p> <input type="submit"> </form> </body>
2、(form元件)定義規則
-----------------------------------------------------
print(request.POST):
{'user': 'yuan', 'pwd': '1234', 're_pwd': '1235', 'email': '[email protected]', 'tel': '123'}
注意
總結校驗欄位功能
1、模板層form表單的name=‘屬性值’必須與 form元件欄位名稱一致
2、定義class UserForm(forms.Form)
3、對前段傳來的資料進行驗證:form=UserForm(request.POST)
4、判斷驗證是否成功,布林值form.is_valid()
5、print(form.cleaned_data)# 存放匹配成功的鍵值對 print(form.errors) # 存放 鍵:失敗的資訊
二、forms元件的渲染標籤功能
方式一
views
from django.shortcuts import render, HttpResponse from django import forms # 匯入forms元件 # 定義校驗規則 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) pwd = forms.CharField(min_length=4) re_pwd = forms.CharField(min_length=4) email = forms.EmailField() tel = forms.CharField() def reg_html(request): form = UserForm() return render(request, 'reg_html.html', locals())
reg.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
<h3>渲染標籤功能1</h3>
<form action="" method="post">
{% csrf_token %}
<p>使用者名稱
{{ form.user }}
</p>
<p>密碼{{ form.pwd }}</p>
<p>確認密碼{{ form.re_pwd}}</p>
<p>電話{{ form.tel }}</p>
<p>郵箱{{ form.email }}</p>
<input type="submit">
</form>
</body> </html>
可實現相同的功能
方式二
reg.html
<h3>渲染方式2</h3> <form action="" method="post"> {% csrf_token %} {% for field in form %} <div> {{ field.label }} {{ field }} </div> {% endfor %} </form>
可以自己設定label屬性
方式3
<h3>渲染方式3</h3> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form>
三、顯示error與重置輸入資訊功能
reg.html
<h3>渲染標籤方式1</h3> <form action="" method="post"> {% csrf_token %} <p> {{ form.user.label }} {{ form.user }}<span>{{ form.user.errors.0 }}</span> </p> <p>{{ form.pwd.label }}{{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> <p>{{ form.re_pwd.label }}{{ form.re_pwd}}<span>{{ form.re_pwd.errors.0 }}</span></p> <p>{{ form.tel.label }}{{ form.tel }}<span>{{ form.tel.errors.0 }}</span></p> <p>{{ form.email.label }}{{ form.email }}<span>{{ form.email.errors.0 }}</span></p> <input type="submit"> </form>
views.py
def reg(request): if request.method=='POST': print(request) print(request.POST) form=UserForm(request.POST) print(form.is_valid()) # 返回布林值 if form.is_valid(): print(form.cleaned_data) return HttpResponse('ok') else: print(form.cleaned_data)# 存放匹配成功的鍵值對 print(form.errors) # 存放 鍵:失敗的資訊 return render(request, 'reg.html', locals()) form=UserForm() return render(request, 'reg.html', locals())
說明:
四、forms元件的引數配置
1、引數提示引數設定
views.py
from django.forms import widgets ## 定義校驗規則 class UserForm(forms.Form): # min_length最低為4位 user=forms.CharField(min_length=4,label='使用者名稱' ,error_messages={'required':'該欄位不為空', 'min_length': '不能少於4個字元'}, widget=widgets.TextInput(attrs={'class':'form-control'}))# 預設lable=User pwd=forms.CharField(min_length=4,label='密碼',widget=widgets.PasswordInput(attrs={'class': 'form-control'}) ) re_pwd=forms.CharField(min_length=4,label='確認密碼',widget=widgets.PasswordInput(attrs={'class': 'form-control'})) email=forms.EmailField(label='郵箱',widget=widgets.EmailInput(attrs={'class': 'form-control'}) , error_messages={'invalid': '格式錯誤'}) tel=forms.CharField(label='電話',widget=widgets.NumberInput(attrs={'class': 'form-control'}))
2、引入bootstrap模組優化介面
reg.html引入
<!-- 最新版本的 Bootstrap 核心 CSS 檔案 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
reg.html
<div class="container"> <div class="row"> <div class="col-md-6 col-lg-offset-3"> <h3>渲染標籤方式1</h3> <form action="" method="post" > {% csrf_token %} <p> {{ form.user.label }} {{ form.user }}<span>{{ form.user.errors.0 }}</span> </p> <p>{{ form.pwd.label }}{{ form.pwd }} <span>{{ form.pwd.errors.0 }}</span></p> <p>{{ form.re_pwd.label }}{{ form.re_pwd}}<span>{{ form.re_pwd.errors.0 }}</span></p> <p>{{ form.tel.label }}{{ form.tel }}<span>{{ form.tel.errors.0 }}</span></p> <p>{{ form.email.label }}{{ form.email }}<span>{{ form.email.errors.0 }}</span></p> <input type="submit"> </form> </div> </div> </div>