Python path [Chapter 2]: Django Form component, pythondjango
Form component
Django's Form mainly has the following functions:
- Generate HTML tags
- Verify user data (displaying error messages)
- HTML Form submission retain data submitted last time
- Content displayed on the initialization page
When creating a Form class, it mainly involves [fields] and [plug-ins]. The fields are used to verify user request data, and the plug-in is used to automatically generate HTML;
1. built-in Fields
Field required = True: whether to allow empty widgets = None, HTML plug-in label = None, used to generate a Label label or display content initial = None, initial value help_text = '', help information (displayed next to the tag) error_messages = None, * error message {'requestred': 'cannot be blank', 'invalid': 'format error'} show_hidden_initial = False, whether to add a hidden plug-in with default values after the current plug-in (can be used to check whether the two inputs have been) validators = [], * The following sections describe the specific usage of custom verification rules: localize = False, whether local disabled = False, and whether label_suffix = None Label content suffix. * Note: the parameters in the field inherited from the field can all be CharField (Field) max_length = None, the maximum length is min_length = None, and the minimum length is strip = True, whether to remove the blank IntegerField (Field) entered by the user) max_value = None, maximum value min_value = None, minimum value FloatField (IntegerField )... decimalField (IntegerField) max_value = None, maximum min_value = None, minimum max_digits = None, total length = None, decimal length BaseTemporalField (Field) input_formats = None time format DateField (BaseTemporalField) format: 2015-09-01TimeField (BaseTemporalField) Format: 11: 12 DateTimeField (BaseTemporalField) Format: 2015-09-01 11: 12 DurationField (Field) Time Interval: % d % H: % M: % S. % f... regexField (CharField) * is equivalent to adding validators regex to CharField, custom Regular Expression max_length = None, maximum length min_length = None, minimum length error_message = None, ignore, error message: Use error_messages = {'invalid ':'... '} EmailField (CharField )... fileField (Field) allow_empty_file = False whether to allow empty files * upload an ImageField (FileField )... note: when using the PIL module and pip3 install Pillow dictionary, pay attention to the following two points: -In the form, enctype = "multipart/form-data"-view function obj = MyForm (request. POST, request. FILES) URLField (Field )... booleanField (Field )... nullBooleanField (BooleanField )... * ChoiceField (Field) * single-choice drop-down box... choices = (), options, such as: choices = (0, 'shanghai'), (1, 'beijing'),) required = True, required widget = None, plug-in, default select plug-in label = None, Label content initial = None, initial value help_text = '', help prompt ModelChoiceField (ChoiceField) * multiple select drop-down box... django. forms. models. modelChoiceField queryset, # query the data in the database empty_label = "-----------", # The default blank display content to_field_name = None, # The Field limit_choices_to = None corresponding to the value in HTML # The queryset in ModelForm filters ModelMultipleChoiceField (ModelChoiceField) twice )... django. forms. models. modelMultipleChoiceField TypedChoiceField (ChoiceField) coerce = lambda val: val converts the selected value once. empty_value = ''the default value of the null value is MultipleChoiceField (ChoiceField )... typedMultipleChoiceField (MultipleChoiceField) coerce = lambda val: val converts each selected value at a time. The default value of empty_value = ''is ComboField (Field) fields = (). Multiple verifications are used, as follows: that is, the maximum length of verification is 20, and the format of the verified mailbox is fields. comboField (fields = [fields. charField (max_length = 20), fields. emailField (),]) MultiValueField (Field) * is inherited. PS: abstract class. In the subclass, multiple Dictionaries can be aggregated to match a value. The SplitDateTimeField (MultiValueField) must be used in combination with multiwidgets) * The following three input boxes are generated: 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 option. The file in the directory is displayed as the file path when submitted on the page, and the folder path is match = None, regular Expression matching recursive = False, recursive 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 supports the IP Format unpack_ipv4 = False to parse ipv4 addresses. If it is: ffff: 192.0.2.1, it can be parsed to 192.0.2.1, PS: protocol must be both to enable SlugField (CharField) numbers, letters, underscores, minus signs (hyphens )... UUIDField (CharField) uuid type... django built-in Fields
Django built-in Fields
2. built-in plug-ins
* The plug-in is used to generate HTML. All plug-ins can use attrs = {'class': 'c1'} to create the default value TextInput (Input) NumberInput (TextInput) EmailInput (TextInput) URLInput (TextInput) PasswordInput (TextInput) HiddenInput (TextInput) Textarea (Widget) DateInput (DateTimeBaseInput) DateTimeInput (DateTimeBaseInput) TimeInput (DateTimeBaseInput) expires
Django built-in plug-in
3. Form Verification
Process files:
From django import formsclass Verification (forms. form): # verify the user = forms according to the name value submitted by the Form. charField (error_messages = {'requestred': 'user name cannot be blank '}) pwd = forms. charField (max_length = 12, min_length = 6, error_messages = {'requestred': 'password cannot be blank ', 'min _ length': 'password length cannot be less than 6 bits ', 'max _ length': 'password length cannot exceed 12'}) email = forms. emailField (error_messages = {'requestred': 'user name cannot be blank ', 'invalid': 'mailbox format incorrect'}) def login (request): if request. method = "GET": obj = Verification () return render(request,'login.html ', {'obj': obj}) elif request. method = "POST": # obtain all user data # verify each data request # successful: Get all correct information # failed: Show error message obj = Verification (request. POST) result = obj. is_valid () # verify True/False if result: print (obj. cleaned_data) # else: print (obj. errors. as_json) # All error messages (obj. errors return render (request, 'login.html ', {'obj': obj}) # input obj return redirect ('/login /')
HTML file:
<! DOCTYPE html> Login.html
Other labels:
<Form method = "POST" enctype = "multipart/form-data"> {% csrf_token %} {form. xxoo. label }}{ {form. xxoo. id_for_label }}{ {form. xxoo. label_tag }{{ form. xxoo. errors }}< p >{{ form. user }}{ {form. user. errors }}</p> <input type = "submit"/> </form> other labels include
Use other labels
4. More verification methods:
Verification file:
From django import formsfrom django. forms import widgetsfrom django. forms import fieldsclass Verification (forms. form): # verify the user = fields according to the name value submitted by the Form. charField (widget = widgets. textarea (attrs = {'class': 'c1'}), # customize the style, enter in the variable growth box, and add the style class = c1 label = "username:" # display information on the left) pwd = fields. charField (max_length = 12, min_length = 6, widget = widgets. passwordInput () # custom password format) f = fields. fileField () # Upload File p = fields. filePathField (path = 'app01') # displays the path submitted data as the path value email = fields. emailField () city1 = fields. choiceField (# single-choice drop-down box choices = [(0, 'shanghai'), (1, 'guangzhou '), (2, 'dongguan')]) city2 = fields. multipleChoiceField (# select multiple drop-down boxes choices = [(0, 'shanghai'), (1, 'guangzhou '), (2, 'dongguan')])
HTML file:
<! DOCTYPE html> Login.html
5. Commonly Used selection plug-ins
# Single radio, value: String user = fields. charField (initial = 2, widget = widgets. radioSelect (choices = (1, 'shanghai'), (2, 'beijing'),) # single radio, value string user = fields. choiceField (choices = (1, 'shanghai'), (2, 'beijing'),), initial = 2, widget = widgets. radioSelect) # single select with the value of user = fields. charField (initial = 2, widget = widgets. select (choices = (1, 'shanghai'), (2, 'beijing'),) # single select, the value is string user = fields. choiceField (choices = (1, 'shanghai'), (2, 'beijing'),), initial = 2, widget = widgets. select) # select multiple, with the value of list user = fields. multipleChoiceField (choices = (1, 'shanghai'), (2, 'beijing'),), initial = [1,], widget = widgets. selectMultiple) # single checkboxuser = fields. charField (widget = widgets. checkboxInput () # select multiple checkboxes and set the value to list user = fields. multipleChoiceField (initial = [2,], choices = (1, 'shanghai'), (2, 'beijing'),), widget = widgets. checkboxSelectMultiple
Django selection plug-in
6. initialize data
When developing and writing functions in Web applications, it is often used to obtain data in the database and initialize the value on the HTML Tag.
Verification file:
From django import formsfrom django. forms import widgetsfrom django. forms import fieldsclass Verification (forms. form): # verify the user = fields according to the name value submitted by the Form. charField (widget = widgets. textarea (attrs = {'class': 'c1'}), # customize the style, enter in the variable growth box, and add the style class = c1 label = "username:" # display information on the left) pwd = fields. charField (max_length = 12, min_length = 6, widget = widgets. passwordInput () # custom password format) # f = fields. fileField () # Upload File p = fields. filePathField (path = 'app01') # displays the path submitted data as the path value email = fields. emailField () city1 = fields. choiceField (# single-choice drop-down box choices = [(0, 'shanghai'), (1, 'guangzhou '), (2, 'dongguan')]) city2 = fields. multipleChoiceField (# select multiple drop-down boxes choices = [(0, 'shanghai'), (1, 'guangzhou '), (2, 'dongguan')])
Create verification class
Process files:
Def login (request): if request. method = "GET": # obtain dic = {"user": 'r1', 'pwd': '123', 'email 'from the database ': 'sdfsd', 'city1 ': 1, 'city2': [1, 2]} obj = Verification (initial = dic) return render (request, 'login.html ', {'obj ': obj}) elif request. method = "POST": obj = Verification (request. POST) result = obj. is_valid () # verify True/False if result: print (obj. cleaned_data) # else: print (obj. errors. as_json) # All error messages (obj. errors return render (request, 'login.html ', {'obj': obj}) # input obj return redirect ('/login /')
Processing functions
HTML file:
<! DOCTYPE html> Login.html