Django Form
Django的Form主要具有一下几大功能:
- 生成HTML标签
- 验证用户数据(显示错误信息)
- HTML Form提交保留上次提交数据
- 初始化页面显示内容(自定义样式)
一、Form 简单示例:
1、view中创建Form类并进行函数处理
class FM(forms.Form): user = fields.CharField() pwd = fields.CharField() email = fields.EmailField() def fm(request): if request.method == "GET": obj = FM() return render(request, ‘fm.html‘, {‘obj‘: obj}) elif request.method == "POST": # 获取用户所有数据 # 每条数据请求的验证 # 成功:获取所有的正确的信息 # 失败:显示错误信息 obj = FM(request.POST) # 生成from表单验证对象实例 r1 = obj.is_valid() # 获取obj对象是否有效 if r1: # obj.cleaned_data print(r1) print(obj.changed_data) else: print(r1) print(obj.errors.as_json()) # 错误信息字典形式 # {"user": [{"message": "This field is required.", "code": "required"}], # "pwd": [{"message": "This field is required.", "code": "required"}], # "email": [{"message": "This field is required.", "code": "required"}]} print(obj.errors[‘user‘][0]) return redirect("/fm/")
2、生成HTML.
原文地址:https://www.cnblogs.com/Keep-Ambition/p/8973287.html
时间: 2024-09-30 00:14:13