Form django10-form component

The main function of 1.form components

  Generates HTML tags and style of the page, will form the front end of the back-end code in the form of generation! !

  The data submitted by the user check (regular)

  Automatically generates an error message

  Keep last Input information

 

2.form common field with plug-in components

  Field attribute is requested by the user authentication

  Plug-ins are on the increase generated HTML tag attributes

# Common attributes common field 

required = True                  # Nullable 
the widget = None                     # the HTML widget 
label = None                      # generated tag label 
Initial = None                     # initial value 
error_messages, = None         # error information defining     
Disabled = False                  # editability 
help_text = '                      # help tip 

# common fields 
as CharField (field,)                # iNPUT tag input box 
    MAX_LENGTH = None          # maximum length 
    min_length = None           # minimum length
    = True Strip                     # whether to remove the front and rear spaces 
   # widget = forms.widgets.TextInput (attrs { ' class': 'bootstrap class'}) # change directly generated attribute tag 
   # widget = forms.widgets.PasswordInput (attrs = { 'class': 'bootstrap class'}) # password based on the ciphertext input box
ChoiceField (Field,)                         # radio field (modified by plug-style) 
    choices = ((0, ' Shanghai ' ), (1, ' Beijing ' ))              # front and rear ends corresponding to the selected data 
    the widget forms.widgets.RadioSelect = ()               # based circular input radio tag 
    # the widget forms.widgets.CheckboxInput = () # input based on my radio tag 
    # the widget forms.widgets.Select = () # select radio tags based on the drop-down 
  
MultipleChoiceField (ChoiceField)             # multiple choice field (modified by plug-in style) 
    choices = ((0, ' Shanghai ' ), (1, ' Beijing ' )) 
    the widgetforms.widgets.SelectMultiple = ()             # on the tab to complete multiple choice select 
    # the widget forms.widgets.ChecknoxSelectMultiple = () # square based multi-select tag inpu

 

3.form components simple to use

  1) form a class definition component, key components:

    widget = form.TextInput (attrs = {} Dictionary) # insert may define the type of label, attrs the dictionary may be defined label properties (increased bootstrap style!)

    error_messages = {#} dictionary custom message field validation, with is_valid () using!

    choices # dynamic access to the database data, do not write to die in the class, override the init method is used, the choices fields out to the field as the value of the database (back-end, front-end display)

  2) define the view function, the object passed form template, key components:

    get the request directly to object to the form template 

    post requests, it is necessary to re-form the object is instantiated, POST data will be returned as a parameter, is_vaild () check, check built therein as required, min_length field, etc., continue to execute code if they meet, it does not satisfy the error added form object information passed to the template (of course, this built-in fields can not meet some of the requirements)

  3) the definition of a template, directly to the target loop form tab to remove the display, key components:

    label label is more important need to target each field set 

  4) Method override init

    Completed the acquisition choices dynamically display content and content from back-end database

    Completed all the input box label field, joined the bootstrap style 

#url
url(r'log/', views.log, name='log'),
#view
the LoginForm class (forms.Form): 
DEF the __init __ (Self, args *, ** kwargs):
Super (the LoginForm, Self) .__ the init __ (* args, ** kwargs)
. self.fields [ 'Book'] = choices Models. . Book.objects.all () values_list ( 'PK', 'name')
# remove dictionary traversal key
for ITER in Field (self.fields):
! IF = Field 'Book':
self.fields [Field]. widget.attrs.update ({ 'class': 'Control-form'})

user forms.CharField = (
label = 'username',
required = True,
help_text = 'Please enter a user name here!',
Strip = true,
the widget = forms.TextInput (),
)
password = forms.CharField (
label = 'password'
required=True,
min_length=6,
error_messages={'required': '必须输入', 'min_length': '最小长度6位'},
widget=forms.PasswordInput()
)
book = forms.MultipleChoiceField(
label='书籍',
# choices=((0, '男'), (1, '女')),
initial=[11],
widget=forms.widgets.CheckboxSelectMultiple(),
)



def log(request):
form_obj = LoginForm()
if request.method == 'POST':
form_obj = LoginForm(request.POST)
if form_obj.is_valid():
name = request.POST.get('user')
password = request.POST.get('password')
print(form_obj.errors)
return render(request, 'formtest.html', {'form_obj': form_obj})
 
#html
{% extends 'base.html' %}
{% block body1 %}
<form class="form-horizontal" method="post" novalidate>
{% csrf_token %}
{% for field in form_obj %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
{{ field.errors.0 }}
</div>
{% endfor %}
<button class="btn" type="submit">提交</button>
</form>
{% endblock %}

 

4.form form authentication data

  1) Built-in simple check

    Min_length required to achieve and so on through the property

  2) built regular verification, the custom regular expression to verify the return value field!

    Import RegexValidator method

    validators = [RegexValidator (regular, error)]

from django.core.validators Import RegexValidator 


.... # of the email fields regular 
    email = forms.CharField ( 
        label = ' mail ' , 
        validators = [RegexValidator (R & lt ' ^ [A-zA-Z0-9 _.-] + @ [A-zA-Z0-9 -] + (. \ [A-zA-Z0-9 -] +). * \ [A-zA-Z0-9] {2,6} $ ' , ' mailbox format error ' )], 
        the widget = forms.TextInput ( ), 

    ) 
....

  3) custom method validation (can be applied to check illegal characters )

    Import ValidationError Exception Handling

    Write a check function, do not write return, does not meet the requirements of an abnormal raise of a validationError

    validators = [Function]

from django.core.exceptions Import ValidationError 

# does not satisfy the check Throws 
DEF Desc_Valid (value):
     IF  ' CNM '  in value:
         The raise ValidationError ( ' illegal characters ' ) 

# field validator designated function 
... 
    desc = Forms. as CharField ( 
        label = ' description ' , 
        the widget = forms.TextInput ( ), 
        validators = [Desc_Valid] 
    ) 
...

 

5. Interpretation source is_valid (), how complete the data valid checksum

   Built-in verification value, custom validation

   By checking the value of local hook, clean_% s in the custom class method

   By checking the value global hook, class override clean () method (multi-field can be combined for a secondary acknowledgment checking, such as a password)

  clean () method to override If the check fails a self fields add a errormessage, raise an exception check the original value by returning self dictionary cleand_data

    DEF Clean (Self): 
        pwd = self.cleaned_data [ ' password ' ] 
        repwd = self.cleaned_data [ ' repassword ' ]
         IF pwd =! repwd:
             # to add some fields error 
            self.add_error ( ' repassword ' , ' password inconsistent O ' )
             # exception processing to the error 
            The raise the ValidationError ( ' Pwd ' )
         return self.cleaned_data

 

Guess you like

Origin www.cnblogs.com/quguanwen/p/11427759.html