dj forms表单组件

2024-03-22 07:20
文章标签 表单 组件 forms dj

本文主要是介绍dj forms表单组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

手动的一个个去校验前端传过来的字段数据,是很麻烦的,利用django 的forms组件,对需要校验的字段定义好,能够大大提高效率。


校验字段功能


from django.db import modelsclass UserInfo(models.Model):name = models.CharField(max_length=32)pwd = models.CharField(max_length=32)email = models.EmailField()tel = models.CharField(max_length=32)
app01/models.py

定义自己的forms,前端传过来的数据字段,要和forms里面的字段一样

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title></head>
<body><form action="" method="post">{% csrf_token %}<div><label for="user">用户名</label><p><input type="text" name="name" id="name"></p></div><div><label for="pwd">密码</label><p><input type="password" name="pwd" id="pwd"></p></div><div><label for="r_pwd">确认密码</label><p><input type="password" name="r_pwd" id="r_pwd"></p></div><div><label for="email">邮箱</label><p><input type="text" name="email" id="email"></p></div><input type="submit">
</form></body>
</html>
register.html
from django.forms import widgetswid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"})class UserForm(forms.Form):name=forms.CharField(max_length=32,widget=wid_01)pwd=forms.CharField(max_length=32,widget=wid_02)r_pwd=forms.CharField(max_length=32,widget=wid_02)email=forms.EmailField(widget=wid_01)tel=forms.CharField(max_length=32,widget=wid_01)def register(request):if request.method=="POST":form=UserForm(request.POST)if form.is_valid():print(form.cleaned_data)       # 所有干净的字段以及对应的值else:print(form.cleaned_data)       #print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}print(form.errors.get("name")) # ErrorList ["错误信息",]return HttpResponse("OK")form=UserForm()return render(request,"register.html",locals())
forms组件与处理视图


渲染标签功能


<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><!-- 最新版本的 Bootstrap 核心 CSS 文件 --><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container"><div class="row"><div class="col-md-6 col-lg-offset-3"><form action="" method="post">{% csrf_token %}<div><label for="">用户名</label>{{ form.name }}</div><div><label for="">密码</label>{{ form.pwd }}</div><div><label for="">确认密码</label>{{ form.r_pwd }}</div><div><label for=""> 邮箱</label>{{ form.email }}</div><input type="submit" class="btn btn-default pull-right"></form></div></div>
</div></body>
</html>
渲染方式1
<form action="" method="post">{% csrf_token %}{% for field in form %}<div><label for="">{{ field.label }}</label>{{ field }}</div>{% endfor %}<input type="submit" class="btn btn-default pull-right">
</form>
渲染方式2
<form action="" method="post">{% csrf_token %}{{ form.as_p }}<input type="submit" class="btn btn-default pull-right"></form>
渲染方式3


显示错误与重置输入信息功能

视图

def register(request):if request.method=="POST":form=UserForm(request.POST)if form.is_valid():print(form.cleaned_data)       # 所有干净的字段以及对应的值else:print(form.cleaned_data)       #print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}print(form.errors.get("name")) # ErrorList ["错误信息",]return render(request,"register.html",locals())form=UserForm()return render(request,"register.html",locals())

模板

<form action="" method="post" novalidate>{% csrf_token %}{% for field in form %}<div><label for="">{{ field.label }}</label>{{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span></div>{% endfor %}<input type="submit" class="btn btn-default"></form>


局部钩子与全局钩子


# forms组件
from django.forms import widgetswid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"})from django.core.exceptions import ValidationError
class UserForm(forms.Form):name=forms.CharField(max_length=32,widget=wid_01)pwd=forms.CharField(max_length=32,widget=wid_02)r_pwd=forms.CharField(max_length=32,widget=wid_02)email=forms.EmailField(widget=wid_01)tel=forms.CharField(max_length=32,widget=wid_01)# 局部钩子def clean_name(self):val=self.cleaned_data.get("name")if not val.isdigit():return valelse:raise ValidationError("用户名不能是纯数字!")# 全局钩子def clean(self):pwd=self.cleaned_data.get("pwd")r_pwd=self.cleaned_data.get("r_pwd")if pwd==r_pwd:return self.cleaned_dataelse:raise ValidationError('两次密码不一致!')def register(request):if request.method=="POST":form=UserForm(request.POST)if form.is_valid():print(form.cleaned_data)       # 所有干净的字段以及对应的值else:clean_error=form.errors.get("__all__")return render(request,"register.html",locals())form=UserForm()return render(request,"register.html",locals())
view


---

app01/myforms.py

from django import forms
from django.forms import widgets
from app01.models import UserInfofrom django.core.exceptions import NON_FIELD_ERRORS, ValidationErrorclass UserForm(forms.Form):name = forms.CharField(min_length=4, label="用户名", error_messages={"required": "该字段不能为空"},  # label 用于前端展示widget=widgets.TextInput(attrs={"class": "form-control"}))  # html挂件 pwd = forms.CharField(min_length=4, label="密码",widget=widgets.PasswordInput(attrs={"class": "form-control"}))r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={"required": "该字段不能为空"},widget=widgets.TextInput(attrs={"class": "form-control"}))email = forms.EmailField(label="邮箱", error_messages={"required": "该字段不能为空", "invalid": "格式错误"},widget=widgets.TextInput(attrs={"class": "form-control"}))tel = forms.CharField(label="手机号", widget=widgets.TextInput(attrs={"class": "form-control"}))# 对字段进行校验 clean_xx  , 验证完记得要返回对应字段值def clean_name(self):val = self.cleaned_data.get("name")  # cleaned_data 提交过来的干净的字段数据ret = UserInfo.objects.filter(name=val)if not ret:return valelse:raise ValidationError("该用户已注册!")def clean_tel(self):val = self.cleaned_data.get("tel")if len(val) == 11:return valelse:raise ValidationError("手机号格式错误")def clean(self):pwd = self.cleaned_data.get('pwd')r_pwd = self.cleaned_data.get('r_pwd')if pwd and r_pwd:if pwd == r_pwd:return self.cleaned_dataelse:raise ValidationError('两次密码不一致')else:return self.cleaned_data  # 要返回数据
myforms.py

处理视图

from django.shortcuts import renderfrom app01.myforms import *def reg(request):if request.method == "POST":# print(request.POST)# form=UserForm({"name":"yu","email":"123@qq.com","xxxx":"alex"})form = UserForm(request.POST)  # 前端传过来的form表单的name属性值应该与forms组件字段名称一致# print(form.is_valid())  # 返回布尔值if form.is_valid():print(form.cleaned_data)  # {"name":"yuan","email":"123@qq.com"}else:print(form.cleaned_data)  # {"email":"123@qq.com"}# print(form.errors)        # {"name":[".........."]}# print(type(form.errors))  # ErrorDict# print(form.errors.get("name"))# print(type(form.errors.get("name")))    # ErrorList# print(form.errors.get("name")[0])#   全局钩子错误# print("error",form.errors.get("__all__")[0])errors = form.errors.get("__all__")return render(request, "reg.html", locals())'''form.is_valid()   :返回布尔值form.cleaned_data :{"name":"yuan","email":"123@qq.com"}form.errors       :{"name":[".........."]}'''form = UserForm()return render(request, "reg.html", locals())
app01/views.py

提交模板

模板渲染的3种方式

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><style>.error{color: red;}</style><!-- 最新版本的 Bootstrap 核心 CSS 文件 --><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body><div class="container"><div class="row"><div class="col-md-6 col-lg-offset-3">{#<h3>简单form</h3>#}{##}{##}{#<form action="" method="post" novalidate>#}{#    {% csrf_token %}#}{#    <p>用户名<input type="text" name="name"></p>#}{#    <p>密码 <input type="text" name="pwd"></p>#}{#    <p>确认密码 <input type="text" name="r_pwd"></p>#}{#    <p>邮箱  <input type="text" name="email"></p>#}{#    <p>手机号 <input type="text" name="tel"></p>#}{#    <input type="submit">#}{##}{#</form>#}<hr><h3>forms组件渲染方式1</h3><form action="" method="post" novalidate>  {# 自己校验 #}{% csrf_token %}<p>{{ form.name.label }}{{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span></p><p>{{ form.pwd.label }}{{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span></p><p>确认密码{{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span><span class="pull-right error">{{ errors.0 }}</span></p><p>邮箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p><p>手机号 {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p><input type="submit"></form>{#<h3>forms组件渲染方式2</h3>#}{##}{#<form action="" method="post" novalidate>#}{#     {% csrf_token %}#}{##}{#    {% for field in form %}#}{##}{#        <div>#}{#            <label for="">{{ field.label }}</label>#}{#            {{ field }}#}{#        </div>#}{##}{#    {% endfor %}#}              {# 每行的错误信息不好展示 #}{##}{#     <input type="submit">#}{#</form>#}{##}{#<h3>forms组件渲染方式3 用的比较少</h3>#}{##}{#<form action="" method="post">#}{#     {% csrf_token %}#}{##}{#     {{ form.as_p }}#}{##}{#     <input type="submit">#}{#</form>#}</div></div>
</div></body>
</html>
templates/reg.html

imageimage


错误信息在定义forms的时选择添加与否

转载于:https://www.cnblogs.com/wenyule/p/10519191.html

这篇关于dj forms表单组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/834803

相关文章

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

HTML提交表单给python

python 代码 from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)@app.route('/')def form():# 渲染表单页面return render_template('./index.html')@app.route('/submit_form',

vue2 组件通信

props + emits props:用于接收父组件传递给子组件的数据。可以定义期望从父组件接收的数据结构和类型。‘子组件不可更改该数据’emits:用于定义组件可以向父组件发出的事件。这允许父组件监听子组件的事件并作出响应。(比如数据更新) props检查属性 属性名类型描述默认值typeFunction指定 prop 应该是什么类型,如 String, Number, Boolean,

kubelet组件的启动流程源码分析

概述 摘要: 本文将总结kubelet的作用以及原理,在有一定基础认识的前提下,通过阅读kubelet源码,对kubelet组件的启动流程进行分析。 正文 kubelet的作用 这里对kubelet的作用做一个简单总结。 节点管理 节点的注册 节点状态更新 容器管理(pod生命周期管理) 监听apiserver的容器事件 容器的创建、删除(CRI) 容器的网络的创建与删除

form表单提交编码的问题

浏览器在form提交后,会生成一个HTTP的头部信息"content-type",标准规定其形式为Content-type: application/x-www-form-urlencoded; charset=UTF-8        那么我们如果需要修改编码,不使用默认的,那么可以如下这样操作修改编码,来满足需求: hmtl代码:   <meta http-equiv="Conte

js异步提交form表单的解决方案

1.定义异步提交表单的方法 (通用方法) /*** 异步提交form表单* @param options {form:form表单元素,success:执行成功后处理函数}* <span style="color:#ff0000;"><strong>@注意 后台接收参数要解码否则中文会导致乱码 如:URLDecoder.decode(param,"UTF-8")</strong></span>

前端form表单+ifarme方式实现大文件下载

// main.jsimport Vue from 'vue';import App from './App.vue';import { downloadTokenFile } from '@/path/to/your/function'; // 替换为您的函数路径// 将 downloadTokenFile 添加到 Vue 原型上Vue.prototype.$downloadTokenF

火语言RPA流程组件介绍--浏览网页

🚩【组件功能】:浏览器打开指定网址或本地html文件 配置预览 配置说明 网址URL 支持T或# 默认FLOW输入项 输入需要打开的网址URL 超时时间 支持T或# 打开网页超时时间 执行后后等待时间(ms) 支持T或# 当前组件执行完成后继续等待的时间 UserAgent 支持T或# User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器

vue 父组件调用子组件的方法报错,“TypeError: Cannot read property ‘subDialogRef‘ of undefined“

vue 父组件调用子组件的方法报错,“TypeError: Cannot read property ‘subDialogRef’ of undefined” 最近用vue做的一个界面,引入了一个子组件,在父组件中调用子组件的方法时,报错提示: [Vue warn]: Error in v-on handler: “TypeError: Cannot read property ‘methods