Django Forms components as well as knowledge summary

 

Forms components

A, Form Components Introduction

Form component can do several things:

  1, the user authentication data request

  2, an error message generated automatically    

  3, packing correct information submitted by the user

  4. If there is a mistake, correct it other, to retain the previous entry

  4, input tag is automatically created and can set style

 

Second, the use of Form components

  1, create a rule

from Django import   Forms
 from `` django.forms`` import Widgets
 from   app01.models import *
 from   `` django.forms`` import the ValidationError   # The following import here and the same effect as 
# from the ValidationError django.core.exceptions import class the UserForm (forms.Form): 
    name = Forms .CharField (min_length = 4, label = ' username', error_messages = { 'required' : ' this field can not be empty!'}, 
                           the widget = widgets.TextInput (attrs = { 'class': 'Control-form'} )) 
    pwd = forms.CharField (= min_length. 8, label = 'password', error_messages = { 'required' : ' this field can not be empty!'},
                           = widgets.PasswordInput the widget (attrs = { 'class':' Control-form '})) 
    r_pwd = forms.CharField (= min_length. 8, label =' Confirm Password ', error_messages = {' required ' :' It can not be ! empty '}, 
                           the widget = widgets.PasswordInput (attrs = {' class ':' Control-form '})) 
    Tel = forms.CharField (label =' phone number ', error_messages = {' required ' :' this field can not ! empty '}, 
                           the widget = widgets.TextInput (attrs = {' class ':' Control-form '})) 
    In email = forms.EmailField (label =' mail ', error_messages = {' required ' :' this field can not ! empty '}, 
                           the widget = widgets.TextInput (attrs = {' class': 'Control-form'}))

2. Rules match

error_messages = { 'Error field': 'prompt'}

= widgets.TextInput the widget (attrs = { 'class': 'form-control' }): to type text input box to add a class attribute value of form-control

widgets.PasswordInput: enter a password box.

def clean_ field names: check local hook, check writing rules for a particular field.

def clean (self): global parity hook, can be taken all the field values, checksum check value for the two fields are identical (and confirm a secret passcode).

self.cleaned_data: in global parity, all clean data (data check has passed).

myforms.py file:

# * _ * Coding: UTF-* _ *. 8 
from Django import   Forms
 from `` django.forms`` import Widgets
 from   app01.models import *
 from   `` django.forms`` import the ValidationError   # The following import here and the same effect as 
# from import django.core.exceptions the ValidationError 
class the UserForm (forms.Form):
     # this class attribute name attribute names must form a front end and a form consistent 
    # when verifying, if there is any one of compliance, it is to false 

    '' ' 
    error_messages, = {' error type ':' error '} 
    widgets.TextInput (attrs = {' attribute name ':' attribute '}) 
    ' '' 
    nameForms.CharField = (= min_length. 4, label = ' username ' , error_messages, = { ' required ' : ' ! This field can not be empty ' }, 
                           the widget = widgets.TextInput (attrs = { ' class ' : ' form-Control ' })) 
    pwd = forms.CharField (= min_length. 8, label = ' password ' , error_messages, = { ' required ' : ' ! this field can not be empty ' }, 
                           the widget = widgets.PasswordInput (attrs = { 'class' : ' Form-Control ' })) 
    r_pwd = forms.CharField (= min_length. 8, label = ' Confirm Password ' , error_messages, = { ' required ' : ' ! This field can not be empty ' }, 
                           the widget = widgets.PasswordInput ( = {attrs ' class ' : ' form-Control ' })) 
    Tel = forms.CharField (label = ' phone number ' , error_messages, = { ' required ' : 'This field can not be empty!' }, 
                           The widget = widgets.TextInput (attrs = { ' class ' : ' form-Control ' })) 
    In Email = forms.EmailField (label = ' mail ' , error_messages, = { ' required ' : ' This field can not be empty! ' }, 
                           the widget = widgets.TextInput (attrs = { ' class ' : ' form-Control ' })) 

    # local hook 
    DEF clean_name (Self): 
        Val= self.cleaned_data.get('name')
        is_true = userinfo.objects.filter(name=val)
        if is_true:
            raise  ValidationError('该用户已经存在!')
        else:
            return val

    def clean_tel(self):
        val =self.cleaned_data.get('tel')
        if len(val)==11 and val.startswith('1'):
            return val
        else:
             The raise ValidationError ( " phone number format is wrong, must begin 1 " )
 #      global hook 
    DEF Clean (Self): 
        pwd = self.cleaned_data.get ( ' pwd ' ) 
        r_pwd = self.cleaned_data.get ( ' r_pwd ' )
         # when the password has been verified, or if pwd r_pwd, not by words when validation rules, then it should not be compared to check both by value is not none. 
        IF pwd and   r_pwd:
             IF pwd == r_pwd:
                 return Self. cleaned_data
             the else :
                 The raise  ValidationError ( ' two passwords do not match ' )
         the else :
             return self.cleaned_data
views.py: check logic code

form = UserForm (request.POST): All data in the POST request, the first instance of an object

is.valid (): This is used for validation

from django.shortcuts Import the render, HttpResponse
 from app01.myforms Import *
 # the Create your views here Wallpaper. 
DEF REG (Request):
     IF request.method == " POST " : 

        Print (request.POST) 
        form = the UserForm (request.POST)
         #   form.is_valid () is the result of the check, if the check by returning true, otherwise returns false 
        Print (form.is_valid ())
         IF form.is_valid ():
             # form.cleaned_data: data through a dictionary form . { 'Key': value} 
            Print (form.cleaned_data)
             return  The HttpResponse ( ' verified ' )
         the else :
             # form.cleaned_data: where the logical verification fails, then the check is successful indicates field information. 
            Print (form.cleaned_data)
             # form.erros: returning the check does not pass information, the format: { 'field does not pass': [Cause by not]} 
            # take global error 
            errors = form.errors.get ( ' __all__ is ' )
             Print (errors)
             Print (form.errors)
             for I in form. errors:
                 Print (form.errors.get (I) [0]) # Get error 

            '' ' check fails Back to:
            The return of the page and get the request is not the same, get the request form is no data. Form the returned data, the data will automatically render 
            such a benefit is, fill in the data will not be cleared, but is rendered to the label      
            '' ' 
            return the render (Request, ' reg.html ' , about locals ()) 

    form = the UserForm () 

    return   the render (Request, ' reg.html ' , about locals ())
reg.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>forms表单校验</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


</head>
<body>


<div class="cent" style="width: 30%;margin: 0 auto">
    <h3>forms组件渲染form表单2</h3>
    <form action="" method="post">
        {% csrf_token %}
        {% for foo in form %}
            <div style="margin: 5px "><label for="">{{ foo.label }}</label> {{ foo }}
                <span style="color:red" class="pull-right">Foo.errors.0} {} { </ span > 
                {% IF errors.0 and foo.name == 'r_pwd'%} is used to determine the global error, if the error is confirmed password. 
                    < Span style = " Color: Red " class =" pull-right " > {{}} errors.0 </ span > 
                {% endif%} 

            </ div > 

        {%} endfor% 

        < INPUT type =" Submit " > 
    </ form > 
< / div > 

</ body > 
</ HTML >

 

Guess you like

Origin www.cnblogs.com/lovepy3/p/10959845.html
Recommended