Python Automation Development Learning 22-django (Form)

Source: Internet
Author: User
Tags local time string back valid email address

Form form Validation

This is not to verify the username password is correct, this part of the content has been mentioned before. Here is the data format to verify, which is the validation that is performed first after the request is received. Only data format validation passes to verify that the user name password is correct. If the data format validation does not pass, an error message is returned.
Lecturer's blog Address: http://www.cnblogs.com/wupeiqi/articles/6144178.html

Test environment

Write a form form first, host.html:

<form action="/host/" method="POST">    {% csrf_token %}    <p><input type="text" name="hostname" placeholder="主机名"></p>    <p><input type="text" name="ip" placeholder="IP地址"></p>    <p><input type="text" name="port" placeholder="端口号"></p>    <p><input type="text" name="email" placeholder="E-Mail"></p>    <p><input type="submit" value="登录"></p></form>

Then import the validated module to write a class:

from django import formsclass FM(forms.Form):    # 变量的字段名匹配form表单里的name属性的值,必须一样    hostname = forms.CharField()    ip = forms.GenericIPAddressField(protocol=‘ipv4‘)    port = forms.IntegerField()    email = forms.EmailField()    # 上面只有这么几个,如果提交的数据有很多,那么其他数据都不收(丢弃)

Then, in the processing function, the class is validated:

def host(request):    if request.method == ‘GET‘:        return render(request, ‘host.html‘)    if request.method == ‘POST‘:        obj = FM(request.POST)  # 实例化,把POST的数据传入        res = obj.is_valid()  # 获取结果        print(res)  # 验证通过是True,不通过则是False        if res:            print(obj.cleaned_data)  # 这是一个原生的字典,里面就是提交来的数据            return HttpResponse(‘OK‘)        else:            print(obj.errors)  # 这里是一串html的列表的代码            print(type(str(obj.errors)))  # 这里的str方法居然是django提供的,变成(<class ‘django.utils.safestring.SafeText‘>)            print(obj.errors.as_json())  # 也可以拿到JSON的格式            return HttpResponse(str(obj.errors))  # 通过str方法后,页面上会直接按html代码处理

You can now open the page test effect.
verification through , Obj.cleaned_data is a valid dictionary of data, can be followed by the operation.
validation does not pass , Obj.errors is the error message (HTML format, a UL unordered list), or you can get a JSON-formatted error message via Obj.errors.as_json ():

{"hostname": [{"message": "This field is required.", "code": "required"}], "ip": [{"message": "Enter a valid IPv4 address.", "code": "invalid"}], "port": [{"message": "Enter a whole number.", "code": "invalid"}], "email": [{"message": "Enter a valid email address.", "code": "invalid"}]}

The error message includes, the error type (code) and the error message (message), here the error message can also be customized, I want to Chinese.

Custom error messages

By setting the custom error message with the parameter error_messages, the value of code is key, and the content you want is filled in value:

from django import formsclass FM(forms.Form):    # 变量的字段名匹配form表单里的name属性的值,必须一样    hostname = forms.CharField(        max_length=12,        min_length=6,        error_messages={‘required‘: "设备名不能为空",                        ‘max_length‘: "设备名太长,不能超过12",                        ‘min_length‘: "设备名太短,不能小于6"})    ip = forms.GenericIPAddressField(protocol=‘ipv4‘)    port = forms.IntegerField()    email = forms.EmailField(error_messages={‘required‘: "邮箱不能为空", ‘invalid‘: "邮箱格式错误"})
Return error message to form page

Now use the Render method to return the error message to the page. All content is in obj and the entire obj is returned:

return render(request, ‘host.html‘, {‘obj‘: obj})

Get error information from the template language. Note here that the last thing to get in. 0 is the content of the error message.

<form action="/host/" method="POST">    {% csrf_token %}    <p><input type="text" name="hostname" placeholder="主机名">{{ obj.errors.hostname.0 }}</p>    <p><input type="text" name="ip" placeholder="IP地址">{{ obj.errors.ip.0 }}</p>    <p><input type="text" name="port" placeholder="端口号">{{ obj.errors.port.0 }}</p>    <p><input type="text" name="email" placeholder="E-Mail">{{ obj.errors.email.0 }}</p>    <p><input type="submit" value="登录"></p></form>

Another problem is that the content you have previously filled in input will be emptied. It's not good.

Automatically generate HTML tags (keep last-entered information)

The above is a function of the form component, in fact, the Django form component is mainly to complete the following 2 functions
The 2 main features of the form component are:

    • Verification (Error message displayed)
    • Preserves the information last entered by the user, implemented by automatically generated HTML tags

Automatically generate input tags
The input tag can be generated automatically using the following method. The form tag is added with a novalidate attribute to disable the client's form validation function and to see directly the validation information returned by the server. In other words, the auto-generated label also helps me add a simple client-side initial validation feature:

<form novalidate action="/host/" method="POST">    {% csrf_token %}    <p>{{ obj.hostname.label_tag }}{{ obj.hostname }}{{ obj.errors.hostname.0 }}</p>    <p>{{ obj.ip.label_tag }}{{ obj.ip }}{{ obj.errors.ip.0 }}</p>    <p>{{ obj.port.label_tag }}{{ obj.port }}{{ obj.errors.port.0 }}</p>    <p>{{ obj.email.label_tag }}{{ obj.email }}{{ obj.errors.email.0 }}</p>    <p><input type="submit" value="登录"></p></form>

The above just generates the input tag, which is not set placeholder, if you need to add a custom attribute later.
There are also these common variables:

    • {{Obj.hostname.label_tag}}: Automatic generation of tags, inside this way &lt;label for="id_hostname"&gt;Hostname:&lt;/label&gt; , a for a value, you can use the following 2 variables to get the 2 values alone.
    • {{Obj.hostname.label}}: The value of the label
    • {{Obj.hostname.id_for_label}}: The ID of the input tag is the value of the for in the label tag, and you can write the label yourself.
    • {{obj.hostname.errors}}: Error message appears to be the same as {{obj.errors.hostname.0}}, except that there are different locations

The function here is to note that because the GET request also needs to return the Obj object (but the get does not have to fill in parameters) to the page, so make the following modifications:

def host(request):    if request.method == ‘GET‘:        obj = FM()  # 这里也需要创建一个对象,因为需要它生成标签,但是不需要传参数        return render(request, ‘host.html‘, {‘obj‘: obj})    if request.method == ‘POST‘:        obj = FM(request.POST)  # 实例化,把POST的数据传入        res = obj.is_valid()  # 获取结果        if res:            print(obj.cleaned_data)            return HttpResponse(‘OK‘)        else:            # return HttpResponse(str(obj.errors))            return render(request, ‘host.html‘, {‘obj‘: obj})

Automatically generate forms
It is recommended to use the above, this customization is too poor.
The form labels write themselves, submit their own writing, the others do not have to write. There are 3 ways:

    • {{obj.as_p}}: P tag.
    • {{Obj.as_ul}}: Generated by the LI tag, so the outside should be covered with a layer of UL label?
    • {{obj.as_table}}: Generates a table's Tbody label, so you have to wrap a table label on your own.
<form novalidate action="/host/" method="POST">    {% csrf_token %}    {{ obj.as_p }}    <p><input type="submit" value="登录"></p></form></form><form novalidate action="/host/" method="POST">    {% csrf_token %}    {{ obj.as_ul }}    <p><input type="submit" value="登录"></p></form></form><form novalidate action="/host/" method="POST">    {% csrf_token %}    <table>    {{ obj.as_table }}    </table>    <p><input type="submit" value="登录"></p></form>
HTML Plugin (widgets)

Continue to see the 2 main features of the form component:

    • Verify (display error message), forms. Charfield, responsible for verifying
    • Keep the information that the user last entered, forms. The Charfield contains a plugin widget that is responsible for generating HTML tags. The public attribute is set, and the default parameter for the member property is none, so no definition is to take the default public property

Plug-ins can define the type of label, default is the text box, you can change to multiple lines of text, a single check, in short, the type of all input tags.
Plug-ins can also define the properties of a tag, which enables custom styles.
Define the module to import the plug-in before, from django.forms import widgets

 from django.forms import Form # This is the class to inherit from the Django.forms import fields # Learn here, field import this Module from django.forms Import Widgets # This module is a plugin class FM (forms. form): # The field name of the variable matches the value of the Name property in the form, and must be the same hostname = fields.                        Charfield (max_length=12, min_length=6, error_messages={' required ': "Device name cannot be empty", ' Max_length ': "Device name is too long to exceed", ' min_length ': "Device name is too short to be less than 6"}) IP = fields. Genericipaddressfield (widget=widgets. Textarea, # This is changed to multiple lines of text, do not define the style after the parentheses protocol= ' IPv4 ') port = fields. Integerfield (widget=widgets. TextInput (attrs={' class ': ' C1 '}) # followed by parentheses, write the property you want to customize) email = fields. Emailfield (error_messages={' Required ': "Mailbox cannot be empty", ' Invalid ': "Mailbox format Error"})  

Learned here, the way to import the module is not very good, explicitly import the required modules.
Import from django.forms import Form module, this is the class to inherit
import from django.forms import field module to define Fields , this fields is the base class for all field types. Start with forms. The Charfield is changed to fields. Charfield .
Import The from django.forms import Widgets module to define the plug-in. If you define only the type, you do not need parentheses later. If custom attributes are required, then parentheses are appended to the attrs to write the various custom attributes in the form of a dictionary.
the input box type of the password , which can be used with this plugin widget=widgets. Passwordinput, .
all authentication types
View the file django\forms\fields.py, which has so many types of authentication. The first field is a base class, followed by a subclass that inherits the field or is a grandson class:

__all__ = (    ‘Field‘, ‘CharField‘, ‘IntegerField‘,    ‘DateField‘, ‘TimeField‘, ‘DateTimeField‘, ‘DurationField‘,    ‘RegexField‘, ‘EmailField‘, ‘FileField‘, ‘ImageField‘, ‘URLField‘,    ‘BooleanField‘, ‘NullBooleanField‘, ‘ChoiceField‘, ‘MultipleChoiceField‘,    ‘ComboField‘, ‘MultiValueField‘, ‘FloatField‘, ‘DecimalField‘,    ‘SplitDateTimeField‘, ‘GenericIPAddressField‘, ‘FilePathField‘,    ‘SlugField‘, ‘TypedChoiceField‘, ‘TypedMultipleChoiceField‘, ‘UUIDField‘,)
Built-in fields

When you create a form class, it mainly involves "fields" and "plug-ins", which are used to validate user-requested data, and plug-ins are used to automatically generate HTML.
The Django built-in fields are as follows:

  • Field
    • Required=true, whether NULL is allowed, default is required, and non-mandatory is set to False
    • Widget=none,html Plug-in
    • Label=none, which is used to generate label or display content, to customize the contents of the label label's value, excluding the last colon
    • The suffix of the label_suffix=none,label content suffix, the custom label label, should be the value of the label that is stitched to the resulting page after all labels are displayed, and the default is the colon in English
    • Initial=none, initial value, you can set the initial content for the label
    • Help_text= ", Help information (displayed next to the label)
    • Error_messages=none, custom error message {' Required ': ' cannot be empty ', ' invalid ': ' Format error '}
    • Show_hidden_initial=false, whether to add a hidden and default plug-in after the current plug-in (can be used to verify that two times the input has been). is to create a hidden, identical label next to your label, and you can compare whether the user's label has changed relative to the previous state.
    • Validators=[], custom validation rules, where an error exception is imported, such as Regexvalidator. Write custom regular expressions and error messages that can be verified by custom rules. This is a list that can define multiple rules, followed by an example.
    • Localize=false, whether localization is supported. For example, the default time is UTC time, the localization is set, and the local time is displayed directly.
    • Disabled=false, whether you can edit it.
  • Charfield (field), the fields in the base class are, of course, available, plus the following
    • Max_length=none, max length
    • Min_length=none, Min. length
    • Strip=true, whether to remove user input blanks
  • Integerfield (Field)
    • Max_value=none, Maximum value
    • Min_value=none, Minimum value
  • Floatfield (Integerfield)
  • Decimalfield (Integerfield)
    • Max_value=none, Maximum value
    • Min_value=none, Minimum value
    • Max_digits=none, total length
    • Decimal_places=none, decimal length
  • Basetemporalfield (Field)
    • Input_formats=none, time formatting
  • Datefield (Basetemporalfield), format: 2015-09-01
  • Timefield (Basetemporalfield), format: 11:12
  • Datetimefield (Basetemporalfield), format: 2015-09-01 11:12
  • Durationfield (Field), time interval:%d%h:%m:%s.%f
  • Regexfield (Charfield), the custom regular is validated. and in fields. The definition of validators is the same in Charfield.
    • Regex, self-customizing regular expressions
    • Max_length=none, max length
    • Min_length=none, Min. length
    • Error_message=none, ignoring, error message using error_messages={' invalid ': ' ... '}
  • Emailfield (Charfield)
  • Filefield (Field)
    • Allow_empty_file=false, whether empty files are allowed
    • Note enctype= "Multipart/form-data" in 1:form form when using
    • Use note that obj = MyForm (Request) in the 2:view function. POST, request. FILES)
  • ImageField (Filefield)
    • Requires PIL module, PIP3 install Pillow
    • When using the note point with Filefield
  • Urlfield (Field)
  • Booleanfield (Field)
  • Nullbooleanfield (Booleanfield)
  • Choicefield (Field), Radio return value is string, multi-select return value is List
    • Choices= (), options, such as: Choices = ((0, ' Shanghai '), (1, ' Beijing '),)
    • Required=true, if required
    • Widget=none, plugins, default widget=widgets.Select , can also selectmultiple (check Select), Widgets. Radioselect (radio), checkboxselectmultiple (multiple selection)
    • Label=none,label Content
    • Initial=none, initial value
    • Help_text= ', help tips
  • Modelchoicefield (Choicefield)
    • Django.forms.models.ModelChoiceField
    • Queryset, querying data in a database
    • Empty_label= "---------", default empty display content
    • The field of value in to_field_name=none,html
    • Two screening of Queryset in Limit_choices_to=none,modelform
  • Modelmultiplechoicefield (Modelchoicefield)
    • Django.forms.models.ModelMultipleChoiceField
  • Typedchoicefield (Choicefield)
    • coerce = Lambda Val:val, one-time conversion of the selected values
    • Empty_value= "", default value for null value
  • Combofield (Field)
    • Fields= (), using multiple validations. As below, verify the maximum length of 20, and verify the mailbox format
    • fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
  • Multivaluefield (Field)
    • Abstract class, can only be inherited. Subclasses can be implemented to aggregate multiple dictionaries to match a value, to be used in conjunction with Multiwidget
  • Splitdatetimefield (Multivaluefield)
    • Input_date_formats=none, List of formats: ['%y--%m--%d ', '%m%d/%y ', '%m/%d/%y ']
    • Input_time_formats=none, List of formats: ['%h:%m:%s ', '%h:%m:%s.%f ', '%h:%m ']
  • Filepathfield (Choicefield), file options, directory files are displayed in the page. Look at the following example.
    • Path, Folder path
    • Match=none, regular match
    • Recursive=false, recursively the following folder
    • Allow_files=true, allow file
    • Allow_folders=false, allow folder
    • Required=true,
    • Widget=none,
    • Label=none,
    • Initial=none,
    • Help_text= ""
  • Genericipaddressfield
    • Protocol= ' Both ', Both,ipv4,ipv6 supported IP formats
    • Unpack_ipv4=false, parse IPv4 address, if:: ffff:192.0.2.1 time, can parse to 192.0.2.1. Protocol must be both to enable
  • Slugfield (Charfield), number, letter, underscore, minus (hyphen)
  • Uuidfield (Charfield), UUID type
Some examples of built-in fields

Field property validators, custom validation rule

from django.forms import Formfrom django.core.validators import RegexValidatorclass MyForm(Form):    mobile = fields.CharField(        validators=[RegexValidator(r‘^[0-9]+$‘, ‘请输入数字‘), RegexValidator(r‘^159[0-9]+$‘, ‘数字必须以159开头‘)],    )

Filepathfield (Choicefield)
List all the files in a folder and choose a commit:

from django.forms import Formfrom django.forms import fieldsclass FM(Form):    folder = fields.FilePathField(path=‘app01‘)def folder(request):    obj = FM()    return render(request, ‘folder.html‘, {‘obj‘: obj})

The template language automatically generates a drop-down list:

{{ obj.folder }}

A drop-down box is generated on the page that shows the file name, followed by a Submit button. The file path is submitted.

Built-in plugins

The following are the built-in plugins. Custom properties can be added after (attrs={‘key‘: ‘value‘}) the plugin:

    • TextInput (Input)
    • Numberinput (TextInput)
    • EmailInput (TextInput)
    • Urlinput (TextInput)
    • Passwordinput (TextInput)
    • Hiddeninput (TextInput)
    • Textarea (Widget)
    • Dateinput (Datetimebaseinput)
    • Datetimeinput (Datetimebaseinput)
    • Timeinput (Datetimebaseinput)
    • Checkboxinput
    • Select
    • Nullbooleanselect
    • Selectmultiple
    • Radioselect
    • Checkboxselectmultiple
    • FileInput
    • Clearablefileinput
    • Multiplehiddeninput
    • Splitdatetimewidget
    • Splithiddendatetimewidget
    • Selectdatewidget
Initializing data

When developing authoring functionality in a Web application, it is often used to get the data in the database and initialize the values on the tags in the HTML.
Get the data and put the data in a dictionary. In the case of database queries, ORM can directly obtain data in the form of a dictionary.
The previous GET request used the equivalent of passing in a obj = FM() null value, and now you can pass the dictionary as a parameter obj = FM(initial=dict) . In this way, the HTML tag generated on the page using form has a value in the dictionary.

Serialization operations (to be supplemented)

The above is submitted using form forms. I've also learned to commit with Ajax before. There is no problem with the commit, but the request returned by the AJAX submission is a string. Either a dictionary or a list can be serialized as a string in JSON. But what is returned here is the obj = FM() object, how to serialize the string back to Ajax?

Python Automation Development Learning 22-django (Form)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.