Directory
First, Introduction
Ii. examples
Third, Form class
Iv. common selection of plug-ins
Five, custom validation rules
Vi. Initializing data
First, Introduction
Django's form has the following major functions
Generate HTML tags
Validating user data (displaying error messages)
HTML form submission holds last commit data
Initialize page display content
Ii. examples
url.py
From django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [url (r ' ^admin/'), admin.site.urls), url (r ' ^fm/', views.fm),]
views.py
from django import formsfrom app01 import modelsfrom django.forms IMPORT WIDGETSFROM DJANGO.FORMS IMPORT FIELDSCLASS FM (forms. Form) The: # field itself only does the validation user = fields. Charfield (error_messages={"required": "user name cannot be empty"}, Widget=widgets. Textarea (attrs={"class": "C1"}) pwd = fields. Charfield ( max_length=12, min_length=6, error_messages={"Required": " Password cannot be empty ", " max_length ": " password length cannot be greater than ", " min_length ": " password length cannot be less than 6 ",}, widgets=widgets. Passwordinput () ) email = fields. Emailfield (error_messages={"Required": "Mailbox cannot be empty", "Invalid": "Mailbox Format Error"}) DEF FM (Request): if request.method == "GET":  OBJ = FM () return render (request, " Fm.html ", {" obj ": obj}) elif request.method == " POST ": # get all the data for the user # Validation # success for each data request: Get all the right information # Failure: page display error message         OBJ = FM ( Request. POST) res = obj.is_valid () if res: &nbSp; models. UserInfo.objects.create (**obj.cleaned_data) else: return render (request, "fm.html", { "obj": obj})
Fm.html
<! DOCTYPE html>
Third, Form class
When creating 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
1.Django built-in fields
field required=true, whether to allow Nulls widget=None, html plug-in label=None, Used to generate label labels or display content initial=None, initial value help_text= ', Help information (displayed next to the label) error_messages=none, 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 inputs are always) validators=[], Custom validation rules localize=False, whether to support localization disabled=False, Whether you can edit label_suffix=none label content suffix charfield (Field) max_length=None, Maximum length min_length=None, Minimum Length strip=True whether to remove user input blank 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 Format datefield (Basetemporalfield ) Format: 2015-09-01timefield (Basetemporalfield) format: 11:12datetimefield (Basetemporalfield) Format: 2015-09-01 11:12 durationfield (Field) time interval:%d %h:%m:%s.%f ... regexfield (Charfield) regex, self-customizing regular expressions max_length=None, Maximum length min_length=None, Minimum Length error_message=None, Ignore, error message using error_messages={' invalid ': ' ... '} Emailfield (Charfield) ... filefield (Field) allow_empty_file=false Allow empty files imagefield (Filefield) ... Note: Requires PIL module,pip3 install pillow above two dictionaries to use, you need to note two points: - form form enctype= "multipart/ Form-data " - view function in obj = myform (request. Post, request. FILES) urlfield (field) ... booleanfield (field) ... nullbooleanfield (Booleanfield) ... choicefield (Field) ... choices= (), options such as:choices = ((0, ' Shanghai '), (1, ' Beijing '),) required=True, is required & NBsp; widget=none, Plugins, default select Plugins 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= "---------", # in default empty displayCapacity to_field_name=None, # fields for value in HTML limit_choices_to=None # Modelform in Queryset two filters modelmultiplechoicefield (Modelchoicefield) ... django.forms.models.ModelMultipleChoiceField typedchoicefield (Choicefield) coerce = lambda val: val Convert the selected values once empty_value= ' default value for null value multiplechoicefield (Choicefield) ... typedmultiplechoicefield (Multiplechoicefield) coerce = lambda val: val Convert each selected value one at a time empty_value= ' default value for null value combofield (Field) fields= () use multiple validations as follows: The maximum length of 20 is verified, Also verify the mailbox format fields.combofield (Fields=[fields. Charfield (max_length=20), fields. Emailfield (),]) multivaluefield (Field) PS: abstract class, subclasses can be implemented to aggregate multiple dictionaries to match a value, To cooperate with Multiwidget using splitdatetimefield (Multivaluefield) input_date_formats=none, format list: ['%y--%m--%d ', '%m%d/%y ', '%m/%d/%y '] input_time_ formats=none format list: ['%h:%m:%s ', '%h:%m:%s.%f ', '%h:%m '] filepatHfield (Choicefield) file options, directories under files are displayed in the page path, Folder path match=None, Regular Matching recursive=False, Recursive folders below allow_files=True, Allow files allow_folders=False, Allow folders 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, can be resolved to 192.0.2.1, ps:protocol must be both to enable slugfield (Charfield) numbers, letters, underscores, minus (hyphens) uuidfield (Charfield) uuid type &NBSP;&NBSP, .....
Note: UUID is a non-repeating random string created based on Mac and current time, etc.
>>> import uuid # make a uuid based on the host ID and current time >>> UUID.UUID1 () # doctest: +skip uuid (' A8098C1A-F86E-11DA-BD1A-00112444BE1E ') # make a uuid using an MD5 hash of a namespace UUID and a name >>>&NBSP;UUID.UUID3 (UUID. namespace_dns, ' python.org ') uuid (' 6fa459ea-ee8a-3ca4-894e-db77e160355e ') # make a random uuid >>> uuid.uuid4 () # doctest: +skip uuid (' 16fd2706-8baf-433b-82eb-8c7fada847da ') # make a uuid using a sha-1 hash of a nAMESPACE&NBSP;UUID&NBSP;AND&NBSP;A&NBSP;NAME&NBSP;&NBSP;&NBSP;&NBSP;>>>&NBSP;UUID.UUID5 (UUID. namespace_dns, ' python.org ') uuid (' 886313e1-3b8a-5372-9b90-0c9aee199e5d ') # make a UUID from a string of hex digits (braces and hyphens ignored) >>> x = uuid. UUID (' {00010203-0405-0607-0809-0a0b0c0d0e0f} ') # convert a uuid to a string of hex digits in standard form > >>&NBSP;STR (x) ' 00010203-0405-0607-0809-0a0b0c0d0e0f ' # get the raw 16 bytes of the UUID >>> x.bytes b ' \x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f ' # make a&nbsP Uuid from a 16-byte string >>> uuid. UUID (bytes=x.bytes) uuid (' 00010203-0405-0607-0809-0a0b0c0d0e0f ')
2.Django Internal Plug-in
TextInput (Input) numberinput (TextInput) EmailInput (TextInput) urlinput (TextInput) passwordinput (TextInput) Hiddeninput (TextInput) Textarea (Widget) dateinput (datetimebaseinput) datetimeinput (datetimebaseinput) Timeinput ( Datetimebaseinput) Checkboxinputselectnullbooleanselectselectmultipleradioselectcheckboxselectmultiplefileinputclearablefileinputmultiplehid Deninputsplitdatetimewidgetsplithiddendatetimewidgetselectdatewidget
Iv. common selection of plug-ins
Five, custom validation rules
Vi. Initializing data
This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1930342
Python Road 71-django Form component