其他分享
首页 > 其他分享> > form组件使用、常用字段、字段参数、自定义校验规则:

form组件使用、常用字段、字段参数、自定义校验规则:

作者:互联网

views:

from django.shortcuts import render,HttpResponse

# Create your views here.
def reg(request):
if request.method == "POST":
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if len(pwd) <= 6:
return render(request,"reg.html",{"pwd_error":"你太短了"})
return render(request,"reg.html")

#从数据库中获取数据之前使用models:
from app01 import models

#继承之前导入forms:
from django import forms

#定义抛出异常功能:
from django.core.exceptions import ValidationError

#定义校验函数:
def check_name(value):
#自定义校验规则 :
#如果校验合格 什么都不做
#校验不合格 抛出异常
if "alex" in value:
raise ValidationError("不能包含alex,非法字符")

#定义django提供内置正则校验器:
from django.core.validators import RegexValidator

#使用form组件之前要定义类:
class RegForm(forms.Form):
#生成input框、默认值用initial:
user = forms.CharField(
#定义必填:
required=True,
#定义是否可以禁用:
# disabled=True,
label="用户名",
initial="alex",
#定义最小长度:
min_length=6,
#定义校验:
validators=[check_name],
#定义错误信息:error_messages
error_messages={
"required":"不能为空",
"min_length":"至少为6位",
}
)
#用密文需要加widget=forms.PasswordInput:
pwd = forms.CharField(label="密码",widget=forms.PasswordInput)
#定义确认密码功能:
re_pwd = forms.CharField(label="确认密码",widget=forms.PasswordInput)
#定义单选字段:
gender = forms.ChoiceField(choices=(("1","男"),("2","女"),),initial="2")
#定义多选字段:
# hobby = forms.MultipleChoiceField(initial=["1","3"],choices=(("1","抽烟"),("2","喝酒"),("3","吐口水"),))
#从数据库中获取:
# hobby = forms.MultipleChoiceField(initial=["1","3"],choices=models.Hobby.objects.values_list("id","name"),widget=forms.CheckboxSelectMultiple)
hobby = forms.MultipleChoiceField(initial=["1","3"],widget=forms.CheckboxSelectMultiple)
#手机号校验:
phone = forms.CharField(
validators=[RegexValidator(r"^1[3-9]\d{9}$","手机号格式不正确")]
)
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
#自定义操作:
print(self.fields)
self.fields["hobby"].choices = models.Hobby.objects.values_list("id","name")

#定义clean方法局部钩子:
def clean_user(self):
#校验成功 返回当前字段的值
#校验不成功 抛出异常
if "alex" in self.cleaned_data.get("user"):
raise ValidationError("不能包含alex,非法字符")
return self.cleaned_data.get("user")

#定义全局钩子:
def clean(self):
#全局钩子
#校验成功 返回所有字段的值 self.cleaned_data
#校验不成功 抛出异常
pwd = self.cleaned_data.get("pwd")
re_pwd = self.cleaned_data.get("re_pwd")
#判断如果相等返回所有字段的值:
if pwd == re_pwd:
return self.cleaned_data
else:
#定义添加错误的方法:
self.add_error("re_pwd","两次密码不一致!!!!")
raise ValidationError("两次密码不一致")

def reg2(request):
#拿到form对象:
form_obj = RegForm()
if request.method == "POST":
form_obj = RegForm(request.POST)
#校验用is_valid:
if form_obj.is_valid():
print(request.POST)
print(form_obj.cleaned_data,type(form_obj.cleaned_data))
return HttpResponse("注册成功")
return render(request,"reg2.html",{"form_obj":form_obj})

reg.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="" method="post">
{# 加% csrf_token %}作用是可以提交post请求:#}
{% csrf_token %}
<p>
用户名:<input type="text" name="user">
</p>
<p>
密码:<input type="password" name="pwd"><span>{{ pwd_error }}</span>
</p>
<button>注册</button>
</form>
</body>
</html>

reg2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="" method="post" novalidate>
{% csrf_token %}
{# {{ form_obj.as_p }}#}
<p>
<label for="{{ form_obj.user.id_for_label }}">{{ form_obj.user.label }}</label>
{# 生成input框用对象点:#}
{{ form_obj.user }}<span> {{ form_obj.user.errors.0 }} </span>
</p>
<p>
<label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label>
{{ form_obj.pwd }}<span>{{ form_obj.pwd.errors.0 }}</span>
</p>
<p>
<label for="{{ form_obj.re_pwd.id_for_label }}">{{ form_obj.re_pwd.label }}</label>
{{ form_obj.re_pwd }}<span>{{ form_obj.re_pwd.errors.0 }}</span>
</p>
<p>
<label for="{{ form_obj.gender.id_for_label }}">{{ form_obj.gender.label }}</label>
{{ form_obj.gender }}
</p>
<p>
<label for="{{ form_obj.hobby.id_for_label }}">{{ form_obj.hobby.label }}</label>
{{ form_obj.hobby }}
</p>
<p>
<label for="{{ form_obj.phone.id_for_label }}">{{ form_obj.phone.label }}</label>
{{ form_obj.phone }}<span>{{ form_obj.phone.errors.0 }}</span>
</p>
{{ form_obj.errors }}
<button>注册</button>
</form>
</body>
</html>

标签:obj,自定义,form,self,校验,forms,pwd,常用字
来源: https://www.cnblogs.com/zhang-da/p/12112476.html