form component Commonly used field, the field parameters, custom validation rules:

views:

Import the render django.shortcuts from, HttpResponse 

# the Create your views here Wallpaper.
DEF REG (Request):
IF request.method == "POST":
the User = request.POST.get ( "the User")
pwd = request.POST.get ( "pwd")
IF len (pwd) <=. 6:
return the render (Request, "reg.html", { "pwd_error": "you too short"})
return the render (Request, "reg.html")

# from before use the database to obtain data models:
from app01 import models

prior to introduction # Inheritance Forms:
Django import Forms from

# thrown defined function:
from the ValidationError django.core.exceptions import

# checksum function is defined:
DEF check_name (value):
# Custom validation rules:
# check if qualified to do nothing
# check failed to throw an exception
if "alex" in value:
raise ValidationError ( "not contain alex, illegal character")

#define django provide built-in regular checker:
from django.core.validators Import RegexValidator

to define classes using form prior to assembly #:
class regform (forms.Form):
# generates input box, the default value Initial:
the user = forms.CharField (
# define required:
required = True,
# define whether you can disable:
# disabled = True,
label = "username",
Initial = "alex",
# defines the minimum length :
min_length =. 6,
# custom validation:
validators = [check_name],
# defined error message: error_messages,
error_messages, = {
"required": "not empty",
"min_length": "at least 6",
}
)
# Encrypted text = forms.PasswordInput need to add the widget:
pwd = forms.CharField (label = "password", widget = forms.PasswordInput)
# custom confirmation password function:
re_pwd = forms.CharField (label = "Confirm Password", widget forms.PasswordInput =)
# defined radio fields:
Gender = forms.ChoiceField (choices = (( "1", "male"), ( "2", "F"),), Initial = "2")
# define multiple choice field:
# = forms.MultipleChoiceField Hobby (Initial = [ ". 1", "3"], choices = (( ". 1", "smoke"), ( "2", "drink"), ( "3" , "spitting")))
# acquired from the database:
# = forms.MultipleChoiceField Hobby (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} $", " phone number is incorrect format")]
)
DEF the __init __ (Self, args *, ** kwargs):
Super () .__ init__ (* args, ** kwargs)
# custom actions:
Print (self.fields)
. self.fields [ "Hobby"] = models.Hobby.objects.values_list choices ( "ID", "name")

# define clean method local hooks:
DEF clean_user (Self):
# check the successful return of the current value of the field
# check unsuccessful thrown
IF "alex" in self.cleaned_data.get ( "the User"):
the raise ValidationError ( "can not contain alex, illegal character ")
return self.cleaned_data.get (" the User ")

# define a global hook:
DEF Clean (Self):
# Global hook
# check all successful return value of the field self.cleaned_data
# check unsuccessful throw an exception
= self.cleaned_data.get pwd ( "pwd")
re_pwd = self.cleaned_data.get ( "re_pwd")
# determines if the return value is equal to all fields:
IF pwd == re_pwd:
return self.cleaned_data
the else:
# add error defined method:
self.add_error ( "re_pwd", "password twice inconsistent !!!!")
the raise ValidationError ( "password twice inconsistent")

DEF reg2 (Request):
# get the form object:
form_obj regform = ()
IF == request.method "the POST":
form_obj = regform (of request.POST)
# checksum with is_valid:
IF form_obj.is_valid ():
Print (of 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>

Guess you like

Origin www.cnblogs.com/zhang-da/p/12112476.html