A, forms Introduction
When submitting data to the back end before we use a form in an HTML page form, will write the label to obtain user input and label them with a form wrap.
At the same time we all need to do in a lot of scenes of user input validation, such as checking whether the user input, the input length and format is not correct. If the user input has an error requires appropriate error message corresponding to the location on the page ..
Django forms component main functions:
- HTML tags generated pages available
- To verify the data submitted by users
- Preserve the contents of the last input
Second, how to use Django forms
1, registration function:
- Rendering the front label Get User Input "" "Render tag
- Obtaining user input transfer backend verification "" "Test Data
- Check did not show an error message by showing "" "Display information
2, the test data:
Step #: form required class from Django Imort Forms class the MyForm (forms.Form): name = forms.CharField (= MAX_LENGTH. 6) password = forms.CharField (= MAX_LENGTH. 8, min_length =. 3) In Email forms.EmailField = ( = True required) # step two: the object is instantiated form form_obj Myform = () # the third step: check to see if the data is legitimate form_obj.is_valid () # only the current through all of the fields will all return True # fourth step 3: Check inspection error message form_obj.errrors # field to store all of the test did not pass the error message " "" { 'name': ['Ensure this value has at most 6 characters (it has 7).'], 'password': ['Ensure this value has at least 3 characters (it has 2).'], 'email': ['Enter a valid email address.'] } """ # Step five: Check Inspection by data form_obj.cleaned_data # inspection rules in line with the data will be placed in the object # ps: check rules form the component data value is from top to bottom, followed by verification test cleaned_data put through the test failures into errors
note:
- All form fields must pass all default values (required = True)
- Check data when you can both pass (multi-pass data will not do any checking >>> does not affect the form validation rules)
3, rendering the label
html: three rendering mode
The first:
<h1> a first rendering (be poor scalability) </ h1 of> {form_obj.as_p} {} {} {} form_obj.as_ul
The second:
<h1> second rendering </ h1 of> <Action = form ""> <p>{{ form_obj.name.label }}{{ form_obj.name }}</p> <p>{{ form_obj.password.label }}{{ form_obj.password }}</p> <p>{{ form_obj.email.label }}{{ form_obj.email }}</p> <input type="submit"> </form>
Third:
<h1>第三种渲染标签的方式</h1>
<form action="" method="post" novalidate>
{% for foo in form_obj %}
<p>
{{ foo.label }}{{ foo }}
<span>{{ foo.errors.0 }}</span>
</p>
{% endfor %}
<input type="submit">
</form>
important point:
If the data submitted to the form component is not legitimate, it will retain the information entered by the user before the page when using the model table form the component data validation, we only need to ensure consistent field so when you create an object directly ** form_obj .cleaned_data <Action = form "" method="post" novalidate> {% for foo in form_obj %} <p> {{ foo.label }}{{ foo }} <span>{{ foo.errors.0 }}</span> </p> {% endfor %} <input type="submit"> </form>
See page effects are also found in the form of validation functions:
• the front page is the object form generated classes -> Generate HTML tags function
• When the user name and password for the page will be prompted after empty or wrong -> check user submitted function
• after the user inputs the wrong again when the last content also remains in the input box -> Keep last input content
Three, Form commonly used functions:
1, commonly used field and plug-ins
When creating Form class, mainly related to the field of [] and [] plug, field is used to authenticate the user requesting the data, for automatically generating the HTML plug;
# initial
The initial value, the initial value input box inside.
class the LoginForm (forms.Form): username = forms.CharField ( min_length =. 8, label = " User Name ", Initial = " John Doe " # Set Default ) pwd = forms.CharField (min_length =. 6, label = " Password ")
# Error_messages: rewrite error message
class the LoginForm (forms.Form): username = forms.CharField ( min_length =. 8, label = " User Name ", Initial = " Joe Smith ", error_messages, = { " required ": " not empty ", " invalid ": " format error ", " min_length ":" user name shortest 8 " } ) pwd = forms.CharField (min_length =. 6, label =" password ")
# password
class LoginForm(forms.Form): ... pwd = forms.CharField( min_length=6, label="密码", widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) )
# RadioSelect: single-radio
class the LoginForm (forms.Form): username = forms.CharField ( min_length =. 8, label = " User Name ", Initial = " Joe Smith ", error_messages, = { " required ": " not empty ", " invalid ": " format error ", " min_length ":" user name shortest 8 " } ) pwd = forms.CharField (min_length =. 6, label =" password ") Gender = forms.fields.ChoiceField ( choices = ((. 1,"M "), (2" female"), (3," Confidential ")), label =" sex ", Initial = 3, the widget forms.widgets.RadioSelect = () )
# Radio Select
class LoginForm (forms.Form): ... Hobby = forms.ChoiceField ( choices = ((1, " basketball "), (2, " football "), (3 " color ball "),), label = " hobby ", Initial =. 3, the widget = forms.widgets.Select () )
# Multiple choice select
class LoginForm (forms.Form): ... Hobby = forms.MultipleChoiceField ( choices = ((1, " basketball "), (2, " football "), (3 " color ball "),), label = " hobby ", Initial = [. 1,. 3], the widget = forms.widgets.SelectMultiple () )
#
class LoginForm(forms.Form):
...
keep = forms.ChoiceField(
label="是否记住密码",
initial="checked",
widget=forms.widgets.CheckboxInput()
)
Radio checkbox #
class LoginForm(forms.Form): ... keep = forms.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput() )
class LoginForm(forms.Form): ... keep = forms.ChoiceField( label="是否记住密码", initial="checked", widget=forms.widgets.CheckboxInput() )
# Multiple-choice checkbox
class LoginForm (forms.Form): ... Hobby = forms.MultipleChoiceField ( choices = ((1, " basketball "), (2, " football "), (3 " color ball "),), label = " hobby ", Initial = [. 1,. 3], the widget = forms.widgets.CheckboxSelectMultiple () )
# Choice field considerations
When using the select tag, you need to pay attention to choices of configuration options can be obtained from the database, but because it is the value of static fields taken not immediately update, you need to override the constructors choice in order to achieve real-time updates.
method one:
from django.forms import Form from django.forms import widgets from django.forms import fields class MyForm(Form): user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), initial=2, widget=widgets.Select ) def __init__(self, *args, **kwargs): super(MyForm,self).__init__(*args, **kwargs) # self.fields['user'].choices = ((1, '上海'), (2, '北京'),) # 或 self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')
Second way:
from django import forms from django.forms import fields from django.forms import models as form_model class FInfo(forms.Form): authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # 多选 # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all()) # 单选
2, Django Form all of the built-in fields
Field, required = True, whether to allow null widget = None, HTML plug label = None, or for generating a display content Label Label initial = None, initial value help_text = '', help information (shown next to the label) error_messages, = None, error message { 'required': 'not empty', 'invalid': 'malformed'} validators = [], custom validation rules localize = False, localized support disabled = False, whether edit label_suffix = None Label SUMMARY suffix as CharField (Field,) MAX_LENGTH = None, maximum length min_length = None, minimum length Strip = True whether to remove the user input blank IntegerField (Field) max_value = None, maximum min_value = None, minimum FloatField (IntegerField) ... DecimalField (IntegerField) max_value = None, maximum min_value = None, minimum max_digits = None, total length decimal_places = None, fractional bit length BaseTemporalField ( Field,) input_formats = None time format DateField (BaseTemporalField) format: 2015-09-01 TimeField (BaseTemporalField) format:. 11: 12 is DateTimeField (BaseTemporalField) format: 2015-09-01 11:12 DurationField (Field,) interval:% H% D:% M:% F% S. ... RegexField (as CharField) REGEX, custom regex MAX_LENGTH = None, maximum length min_length = None, minimum length error_message = None, ignore the error message used = {error_messages, 'invalid': '...'} EmailField (as CharField) ... the FileField (Field,) allow_empty_file = False whether to allow an empty file the ImageField (the FileField) ... Note: requires PIL module, pip3 install Pillow when two or more dictionaries used, two things should be noted: - form form = the enctype " multipart / form-Data " - View the MyForm = function obj (of request.POST, request.FILES) URLField (Field, ) ... BooleanField (Field,) ... NullBooleanField (BooleanField) ... ChoiceField (Field,) required = True,Required ... choices = (), options such as: choices = ((0, 'Shanghai'), (1, 'Beijing'),) the widget = None, plug-ins, the default select the plug label = None, Label contents initial = None, the initial value help_text = '', help tips ModelChoiceField (ChoiceField) ... django.forms.models.ModelChoiceField QuerySet, data # Polling database empty_label = " --------- ", # default empty display content to_field_name = none, # value corresponding to the value in the HTML field limit_choices_to = none # ModelForm in the secondary screening of queryset ModelMultipleChoiceField (ModelChoiceField) ... django.forms. models.ModelMultipleChoiceField TypedChoiceField (ChoiceField) coerce the lambda = Val: Val for the selected conversion values empty_value = '' default null values MultipleChoiceField (ChoiceField) ... TypedMultipleChoiceField (MultipleChoiceField) coerce the lambda = val: val for each value is selected in a conversion empty_value = '' default null values ComboField (Field,) Fields = () using a plurality of verification, as follows: i.e., the maximum length of 20 validation, verification and mailbox format fields.ComboField ( = Fields [fields.CharField (= 20 is MAX_LENGTH), fields.EmailField (),]) MultiValueField (Field,) the PS: abstract class, subclass, the polymerization can be implemented to match a value of a plurality of dictionaries to use with MultiWidget SplitDateTimeField (MultiValueField ) input_date_formats = None, list format: [ '% the Y -% m -% D', 'D%% m /% the Y', '% m /% D /% Y'] input_time_formats = None list format: [ ' H%:% M:% S ','% H:% M:% S. F% ','% H:% M '] that FilePathField will (ChoiceField) file option, directory file page displayed in the path , the folder path match = None, regular matching recursive = False, recursively following folder allow_files = True, allows files allow_folders = False, allowing the folder required = True, the widget = None, label = None, Initial = None, help_text = '' GenericIPAddressField protocol = 'both', both, ipv4, ipv6 IP format supported unpack_ipv4 = False resolve ipv4 address, if it is :: ffff: 192.0.2.1 when resolves to 192.0.2.1, PS: protocol must be enabled in order to both SlugField (CharField) numbers, letters, underscores, minus (hyphen) . .. UUIDField (as CharField) UUID type Django Form built-in fields
3, field validation
# RegexValidator validator
from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], )
# Custom Functions
import re from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.exceptions import ValidationError # 自定义验证规则 def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手机号码格式错误') class PublishForm(Form): title = fields.CharField(max_length=20, min_length=5, error_messages = { 'required': 'title can not be empty', 'min_length': 'a minimum of five characters of the title', 'MAX_LENGTH': 'title up to 20 characters'}, the widget = widgets.TextInput (attrs = { ' class ': " form-Control ", 'placeholder': 'title 5-20 characters'})) # use custom validation rules Phone = fields.CharField (validators = [mobile_validate,], error_messages, = { 'required' : 'phone can not be empty'}, the widget = widgets.TextInput (attrs = { 'class': "form-control", 'placeholder': u 'phone number'})) In Email = fields.EmailField (required = False, error_messages, = { 'required': U 'can not be empty mailbox', 'invalid': u 'mailbox format error'}, the widget widgets.TextInput = (attrs = { ' class ': " form-Control ", 'placeholder': U 'mailbox'}))
4, Hook method (hook)
In addition to the above two methods, we can also define a hook function in the Form class to implement custom validation.
# Partial hook
We define clean_ field name () method in class Fom, it is possible to achieve a specific field of the checksum.
DEF clean_name (Self): name = self.cleaned_data.get ( ' name ') IF '666' in name : self.add_error ( ' name ', '! shout light 666 is not enough, there must be a real force') return name # return or to add, compatibility considerations
# Global hook
We define clean () method Fom class, it is possible to achieve global parity fields.
def clean(self): password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if not password == confirm_password: self.add_error('confirm_password',"两次密码不一致,你这个dsb!") return self.cleaned_data