1、form介绍
我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。
与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入,输入的长度和格式等正不正确。如果用户输入的内容有错误就需要在页面上相应的位置显示对应的错误信息.。
Django form组件就实现了上面所述的功能。
总结一下,其实form组件的主要功能如下:
- 生成页面可用的HTML标签
- 对用户提交的数据进行校验(校验请求参数、也可以做请求参数的数据加工)
- 保留上次输入内容
2、form使用
user_demo这个应用的模型类
from django.db import models
from django.core.paginator import Paginator
# Create your models here.
class NewUser(models.Model):
phone = models.CharField(verbose_name="手机号",max_length=11,unique=True)
email = models.EmailField(verbose_name="邮箱",max_length=50,unique=True)
nick = models.CharField(verbose_name="昵称", max_length=50)
password = models.CharField(verbose_name="密码",max_length=32)
class Meta:
verbose_name = "用户表"
verbose_name_plural = verbose_name
db_table = "new_user" # 映射的用户注册表名称
def __str__(self):
return self.nick
2.1、简写版本
2.1.1、在应用目录下创建forms.py文件,定义一个 自定义类
这个类用来校验注册接口
from django import forms
from . import models
class RegisterForms(forms.Form):
phone = forms.CharField(min_length=11, max_length=11)
email = forms.EmailField()
nick = forms.CharField()
password = forms.CharField(min_length=6,max_length=13)
password2 = forms.CharField(min_length=6,max_length=13)
def clean_phone(self):
phone = self.cleaned_data["phone"]
if not phone.isdigit():
raise forms.ValidationError("手机号格式错误~")
if models.NewUser.objects.filter(phone=phone).exists():
raise forms.ValidationError("手机号已存在!")
return phone
def clean_email(self):
email = self.cleaned_data["email"]
if models.NewUser.objects.filter(email=email).exists():
raise forms.ValidationError("邮箱已存在!")
return email
def clean(self):
cleaned_data = super().clean()
if not self.errors: # 判断前面的 clean_xxx 基本的校验是否有错误
password = cleaned_data["password"]
password2 = cleaned_data["password2"]
if password2 != password:
raise forms.ValidationError("两次输入的密码不一致!")
return cleaned_data
2.1.2、写一个对应的视图函数
这个视图函数就是注册接口,简写(没有操作数据库)
from django.http import JsonResponse, HttpResponse
from . import forms
# Create your views here.
def new_register(request):
form = forms.RegisterForms(request.POST)
# 实例化form对象的时候,把post提交过来的数据直接传进去
# form表单的参数应该与forms组件的字段名称一致
if form.is_valid():
print(form.cleaned_data)
return JsonResponse({"code":0,"msg":"success!"})
# return HttpResponse("ok")
else:
print(form.errors.get_json_data())
return JsonResponse(form.errors.get_json_data())
# return HttpResponse("error")
注意:
在urls.py文件中绑定 路由和这个视图函数
2.2、完善版本
2.2.1、完善后的forms.py
import hashlib
from django import forms
from . import models
class RegisterForms(forms.Form):
phone = forms.CharField(min_length=11, max_length=11)
email = forms.EmailField()
nick = forms.CharField()
password = forms.CharField(min_length=6,max_length=13)
password2 = forms.CharField(min_length=6,max_length=13)
def clean_phone(self):
phone = self.cleaned_data["phone"]
if not phone.isdigit():
raise forms.ValidationError("手机号格式错误~")
if models.NewUser.objects.filter(phone=phone).exists():
raise forms.ValidationError("手机号已存在!")
return phone
def clean_email(self):
email = self.cleaned_data["email"]
if models.NewUser.objects.filter(email=email).exists():
raise forms.ValidationError("邮箱已存在!")
return email
def clean(self):
cleaned_data = super().clean()
if not self.errors: # 判断前面的 clean_xxx 基本的校验是否有错误
password = cleaned_data["password"]
password2 = cleaned_data["password2"]
if password2 != password:
raise forms.ValidationError("两次输入的密码不一致!")
# 数据加工
cleaned_data.pop("password2") # 将请求参数的 password2 删除,和数据库字段一致
cleaned_data["password"]=md5(cleaned_data["password"]) # 将这个明文密码加密
return cleaned_data # 返回处理好的请求参数
def md5(password:str)->str:
"""
用来将明文密码MD5加密
:param password: 密码明文
:return: MD5加密后的密码
"""
md5_password = hashlib.md5(password.encode())
return md5_password.hexdigest()
2.2.2、完善后的注册接口
from django.http import JsonResponse, HttpResponse
from . import forms
# Create your views here.
def new_register(request):
form = forms.RegisterForms(request.POST)
# 实例化form对象的时候,把post提交过来的数据直接传进去
# form表单的参数应该与forms组件的字段名称一致
if form.is_valid():
print(form.cleaned_data)
models.NewUser.objects.create(**form.cleaned_data)
#解包form的字典数据
# 要求form的字典数据 数量、key名称 和数据库要交互的表保持一致
return JsonResponse({"code":0,"msg":"success!"})
# return HttpResponse("ok")
else:
print(form.errors.get_json_data())
return JsonResponse(form.errors.get_json_data())
# return HttpResponse("error")
参考博客
脚本之家:Django中的forms组件实例详解
https://www.jb51.net/article/150420.htm