1、校验字段功能
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)
生成数据表
C:\PycharmProjects\formsdemo>python manage.py makemigrations
C:\PycharmProjects\formsdemo>python manage.py migrate
主url
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^', include(('app01.urls', 'app01')))
]
url
from django.urls import path, re_path, include
from app01 import views
urlpatterns = [
re_path(r'reg/$', views.reg, name='reg'),
]
模板层
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <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="_pwd"></p> <p>邮箱 <input type="text" name="email"></p> <p>手机号 <input type="text" name="tel"></p> <input type="submit" value="注册"> </form> </body> </html>
view
from django.shortcuts import render, HttpResponse def reg(request): if request.method == 'POST': print(request.POST) return HttpResponse('注册成功') return render(request, 'reg.html')
<QueryDict: {'csrfmiddlewaretoken': ['5EwZsUEKRVj836bplmS03PVruttZhG'], 'user': ['alex'], 'pwd': ['123'], '_pwd': ['123'], 'email': ['123@qq.com'], 'tel': ['1234566778']}>
2、定义规则
from django import forms # 导入forms组件 # 定义校验规则 class UserForm(forms.Form): name = forms.CharField(min_length=4, max_length=10) email = forms.EmailField()