14 django_forms

django_forms

forms component simplifies the preparation of the distal end, the distal end constructed style django forms assembly is achieved by rendering the check.

Renderings:

forms component

from django.forms import widgets
from django import forms
from django.core.exceptions import ValidationError


wdg1 = widgets.TextInput(attrs={'class':'form-control'})  # 可以给input标签加任何属性
wdg2 = widgets.PasswordInput(attrs={'class':'form-control'})
class UserForms(forms.Form):  # 创建forms校验对象
    name = forms.CharField(min_length=4, max_length=8,widget=wdg1, label=' Name ' ) # min_length validation rules 
    pwd = forms.CharField (= min_length. 4, the widget = wdg2, label = ' password ' ) 
    r_pwd = forms.CharField (= min_length. 4, the widget = wdg2, label = ' Confirm Password ' ) 
    In email = forms.EmailField (= wdg1 the widget, label = ' mailbox ' ) 
    Tel = forms.CharField (min_length =. 11, MAX_LENGTH =. 11, the widget = wdg1, label = ' phone number ' ) 

    # local hook 
    DEF clean_name (Self): 
        Val = self.cleaned_data.get ( ' name ')
         IF  not val.isdigit ():
             return Val
         the else :
             The raise ValidationError ( ' user name can not be all digital ' ) 

    # global hook 
    DEF Clean (Self): 
        pwd = self.cleaned_data.get ( ' pwd ' ) 
        r_pwd = Self. cleaned_data.get ( ' r_pwd ' )
         IF pwd == r_pwd:
             return self.cleaned_data
         the else :
             The raise the ValidationError ( 'The two passwords do not match! ' )

 

View function

 1 from django.shortcuts import render
 2 from django.forms import widgets
 3 from django import forms
 4 
 5 # Create your views here.
 6 
 7 
 8 # 简单的forms校验
 9 def simple_forms(request):
10     class UserForms(forms.Form):  # 创建forms校验对象
11         name = forms.CharField(min_length=4, max_length=8) # min_length 校验规则
12         pwd = forms.CharField(min_length=4)
13 is          r_pwd = forms.CharField (= min_length. 4 )
 14          In Email = forms.EmailField ()
 15          Tel = forms.CharField (min_length =. 11, MAX_LENGTH =. 11 )
 16      IF request.method == ' the POST ' :
 . 17          RES = The UserForms ( of request.POST)
 18 is          Print (RES)
 . 19          Print (res.is_valid ())   # rules by checking whether all passed as True 
20 is          iF res.is_valid ():
 21 is              # All fields cleaned_data check passes, such as input 100 field, but here only four checksum field, is obtained after filtration 4 field 
22 is              Print (res.cleaned_data)
23 is          the else :
 24              Print (res.cleaned_data)   # part of the field through, which go out into the field validation herein by adding 
25              Print (res.errors)   # ErrorDict: { "error check field": [ "error message", ]} to add here does not pass, a dictionary 
26 is              Print (res.errors.get ( ' in Email ' ))   # errorlist [ "error"] is a list of 
27              Print (res.errors.get ( ' in Email ' ) [0]) # take the first error message, usually take the first error message is returned to the front end 
28      return the render (Request, ' simple_forms.html ' )
 29  
30  
31 is  #In order to avoid rendering the check front end forms a front end and a rear end inconsistent fields can be rendered directly by the rear end of the front page 
32  DEF multi_forms (Request):
 33 is      wdg1 = widgets.TextInput (attrs = { ' class ' : ' form-Control ' })   # can be applied to any attribute of input tag 
34 is      wdg2 = widgets.PasswordInput (attrs = { ' class ' : ' form-Control ' })
 35      class The UserForms (forms.Form):   # Create forms checkpoint objects 
36          name = forms.CharField (= min_length. 4, MAX_LENGTH =. 8, the widget = wdg1, label = ' name ' ) #min_length validation rules 
37 [          pwd = forms.CharField (= min_length. 4, the widget = wdg2, label = ' password ' )
 38 is          r_pwd = forms.CharField (= min_length. 4, the widget = wdg2, label = ' Confirm Password ' )
 39          In Email = forms.EmailField (= wdg1 the widget, label = ' mailbox ' )
 40          Tel = forms.CharField (min_length =. 11, MAX_LENGTH =. 11, the widget = wdg1, label = ' phone number ' )
 41 is      MyForm The UserForms = ()   #   instance to rendering the distal end 
42 is      IF request.method == ' the POST ' :
43          # error message will pass this front end, can render the error message myform.tel.errors.0 get the corresponding field rendering 
44          # and the information input by the user to avoid user data to be retransmitted are flushed 
45          MyForm = the UserForms (of request.POST)
 46 is          Print (MyForm)
 47          Print (myform.is_valid ())   # rules by checking whether all passed as True 
48          iF myform.is_valid ():
 49              # All fields cleaned_data check passes, such as input field 100, but the checksum here only four fields, that is obtained after filtration of four fields 
50              Print (myform.cleaned_data)
 51 is          the else :
 52 is              Print (myform.cleaned_data)   # by a part of the field, which field validation by go out here plus 
53              Print(myform.errors)   # ErrorDict: { "error check field": [ "error"]} not go through added here, a dictionary 
54 is              Print (myform.errors.get ( ' In Email ' ))   # errorlist [ "error"] is a list of 
55              Print (myform.errors.get ( ' In Email ' ) [0]) # take the first error message, usually take the first error message is returned to the front end 
56 is              return the render (Request, ' multi_forms.html ' , about locals ())
 57 is      return the render (Request, ' multi_forms.html ' ,
about locals ()) 58  
59  
60  # of local and global hook hooks 
61 DEF gouzi (Request):
 62 is      # through Models, forms may be in a file, import and 
63 is      from forms_app01.myforms Import The UserForms
 64      MyForm = The UserForms ()
 65      IF request.method == ' the POST ' :
 66          MyForm = The UserForms ( of request.POST)
 67          IF myform.is_valid ():
 68              Print (myform.cleaned_data)
 69          the else :
 70              clean_error = myform.errors.get ( " __all__ is " )
 71 is          return render(request, 'gouzi.html', locals())
72     return render(request, 'gouzi.html',locals())

 

simple_forms.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>简单forms校验</title>
 6     <link rel="stylesheet" href="/static/bootstrap.min.css">
 7 </head>
 8 <body>
 9 <div class="container">
10     <div class="row">
11         <div class="col-md-6 col-md-offset-3">
12             <h3>简单forms校验</h3>
13             <form action="" method="post">
14                 {% csrf_token %}
15                 <label for="user">用户名</label>
16                 <p><input type="text" name="name" id="name"></p>
17                 <label for="pwd">密码</label>
18                 <p><input type="password" name="pwd" id="pwd"></p>
19                 <label for="r_pwd">确认密码</label>
20                 <p><input type="password" name="r_pwd" id="r_pwd"></p>
21                 <label for="email">邮箱</label>
22                 <p><input type="text" name="email" id="email"></p>
23                 <label for="phone">手机</label>
24                 <p><input type="text" name="tel" id="phone"></p>
25                 <input type="submit">
26             </form>
27         </div>
28     </div>
29 </div>
30 </body>
31 </html>

 

gouzi.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>钩子</title>
 6     <link rel="stylesheet" href="/static/bootstrap.min.css">
 7 </head>
 8 <body>
 9 <div class="container">
10     <div class="row">
11         <div class="col-md-6 col-md-offset-3">
12             <hr>
13             <h3>钩子</h3>
14             <form action="" method="post">
15                 {% csrf_token %}
16                 {% for field in myform  %}
17                     <label for="">{{ field.label }}</label>
18                     {{ field }}
19                     <span class="pull-right" style="color: red">
20                         {% if field.label == '确认密码' %}
21                             {{ clean_error.0 }}
22                             {% else %}
23                             {{ field.errors.0 }}
24                         {% endif %}
25                     </span>
26                 {% endfor %}
27                 <input type="submit" class="btn btn-success mybtn">
28             </form>
29         </div>
30     </div>
31 </div>
32 </body>
33 </html>

 

Guess you like

Origin www.cnblogs.com/znyyy/p/11355797.html