Introduction to Form
When we previously submitted data to the backend using a form table in an HTML page, we wrote some tags to get user input and wrapped them in form tags.
At the same time, we need to check the user input in many scenarios, such as checking whether the user input, the input length and format is correct or not. If there is an error in the user's input, we need to display the corresponding error message in the corresponding position on the page.
The Django form component implements the functionality described above.
To summarize, the main functions of the form component are actually as follows.
- Generate HTML tags available for the page
- Validation of user-submitted data
- Retaining the last input
First, define a UserForm class in my_forms.py in the application directory.
from django import forms from import widgets class UserForm(): username = (min_length=4, label='Username', widget=(attrs={"class": "form-control"}), error_messages={ "required": "User name cannot be empty.", }) pwd = (min_length=4, label='Password', error_messages={ "required": "Password cannot be empty.", }, widget=(attrs={"class": "form-control"})) r_pwd = (min_length=4, label='Confirm Password', widget=(attrs={"class": "form-control"}), error_messages={ "required": "Password cannot be empty.", }) email = (label='Mailbox', widget=(attrs={"class": "form-control"}), error_messages={ "required": 'Mailbox cannot be empty', "invalid": "Mailbox format error.", }) tel = (label='Cell phone number', widget=(attrs={"class": "form-control"}), )
Write another view function:
In writing a view function
def reg(request): form = UserForm() if == "POST": print() # Instantiate the form object by passing the data submitted by post directly into it. form = UserForm() # The value of the form form's name attribute should match the field name of the forms component if form.is_valid(): print(form.cleaned_data) return HttpResponse('Registration Successful') return render(request, '', locals())
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>enrollment</title> </head> <body> <h3>legacyformform (document)</h3> <form action="" method="post"> {% csrf_token %} <p>user ID:<input type="text" name="username"></p> <p>cryptographic:<input type="password" name="pwd"></p> <p>确认cryptographic:<input type="password" name="r_pwd"></p> <p>inbox:<input type="email" name="email"></p> <p>cell phone number:<input type="tel" name="tel"></p> <p><input type="submit" value="Submit"></p> </form> <h3>formsComponent Rendering Methods1</h3> <form action="" method="post" novalidate> {% csrf_token %} <p>{{ }}:{{ }} <span>{{ .0 }}</span></p> <p>cryptographic:{{ }} <span>{{ .0 }}</span></p> <p>确认cryptographic:{{ form.r_pwd }} <span>{{ form.r_pwd.errors.0 }}</span></p> <p>inbox:{{ }} <span>{{ .0 }}</span></p> <p>cell phone number:{{ }} <span>{{ .0 }}</span></p> <p><input type="submit" value="Submit"></p> </form> <h3>formsComponent Rendering Labeling Methods2</h3> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group clearfix"> <label for="">{{ }}</label> {{ field }} <span style="color: red" class="pull-right">{{ .0 }}</span> {% if == 'r_pwd' %} <span style="color: red" class="pull-right">{{ errors.0 }}</span> {% endif %} </div> {% endfor %} <input type="submit" value="Register." class="btn btn-default pull-right"> </form> <h3>formsComponent Rendering Labeling Methods3 Not recommended</h3> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Register."> </form> </body> </html>
Looking at the results of the web page, I found that it also verifies the functionality of the form:
- The front-end page is generated by the object of the form class --> generate HTML tags functionality
- When the user name and password are entered as empty or wrong, the page will prompt -->user to submit the verification function.
- When the user makes a mistake and types again, the last entry is still in the input box -->keep the last entry
The Form thing.
Common Fields and Plugins
When creating the Form class, it mainly involves [fields] and [plug-ins], fields are used to validate the data requested by the user, and plug-ins are used to generate HTML automatically.
initial
Initial value, the initial value inside the input box.
class LoginForm(): username = ( min_length=8, label="Username", initial="Zhang San" # Set default values ) pwd = (min_length=6, label="Password.")
error_messages
Rewrite the error message.
class LoginForm(): username = ( min_length=8, label="Username", initial="Zhang San", error_messages={ "required": "Cannot be empty.", "invalid": "Formatting error.", "min_length": "Minimum 8 digits for username" } ) pwd = (min_length=6, label="Password.")
password
class LoginForm(): ... pwd = ( min_length=6, label="Password.", widget=(attrs={'class': 'c1'}, render_value=True) )
radioSelect
Single radio value as a string
class LoginForm(): username = ( min_length=8, label="Username", initial="Zhang San", error_messages={ "required": "Cannot be empty.", "invalid": "Formatting error.", "min_length": "Minimum 8 digits for username" } ) pwd = (min_length=6, label="Password.") gender = ( choices=((1, "Male."), (2, "Female."), (3, "Confidentiality.")), label="Gender", initial=3, widget=() )
Select
class LoginForm(): ... hobby = ( choices=((1, "Basketball."), (2, "Football."), (3, "Two Colors."), ), label="Hobbies.", initial=3, widget=() )
Multi-select Select
class LoginForm(): ... hobby = ( choices=((1, "Basketball."), (2, "Football."), (3, "Two Colors."), ), label="Hobbies.", initial=[1, 3], widget=() )
Radio checkbox
class LoginForm(): ... keep = ( label="Do you remember the password?", initial="checked", widget=() )
Multi-select checkbox
class LoginForm(): ... hobby = ( choices=((1, "Basketball."), (2, "Football."), (3, "Two Colors."),), label="Hobbies.", initial=[1, 3], widget=() )
A note about CHOICE:
When using the choices tab, it is important to note that choices options can be obtained from the database, but because they are static fields *** the values obtained cannot be updated in real time ***, then you need to customize the constructor method so as to achieve this purpose.
Way one:
from import Form from import widgets from import fields class MyForm(Form): user = ( # choices=((1, 'Shanghai'), (2, 'Beijing'),) initial=2, widget= ) def __init__(self, *args, **kwargs): super(MyForm,self).__init__(*args, **kwargs) # ['user'].choices = ((1, 'Shanghai'), (2, 'Beijing'),) # or ['user'].choices = ().values_list('id','caption')
Way two:
from django import forms from import fields from import models as form_model class FInfo(): authors = form_model.ModelMultipleChoiceField(queryset=()) # Multiple choice # authors = form_model.ModelChoiceField(queryset=()) # single election Django FormAll built-in fields Field required=True, Whether to allow null widget=None, HTMLplug-in (software component) label=None, Used to generateLabelLabel or display content initial=None, starting value help_text='', Helpful Information(Displayed next to the label) error_messages=None, error message {'required': 'Cannot be empty', 'invalid': 'Formatting error'} validators=[], Customized validation rules localize=False, Support for localization disabled=False, Whether or not it can be edited label_suffix=None LabelContent Suffix CharField(Field) max_length=None, Maximum length min_length=None, minimum length strip=True Whether to remove user input blanks IntegerField(Field) max_value=None, maximum values min_value=None, minimum value FloatField(IntegerField) ... DecimalField(IntegerField) max_value=None, maximum values min_value=None, minimum value max_digits=None, total length decimal_places=None, decimal place length BaseTemporalField(Field) input_formats=None time formatting DateField(BaseTemporalField) specification:2015-09-01 TimeField(BaseTemporalField) specification:11:12 DateTimeField(BaseTemporalField)specification:2015-09-01 11:12 DurationField(Field) time interval:%d %H:%M:%S.%f ... RegexField(CharField) regex, Customized Regular Expressions max_length=None, Maximum length min_length=None, minimum length error_message=None, neglect,error messageutilization error_messages={'invalid': '...'} EmailField(CharField) ... FileField(Field) allow_empty_file=False Whether to allow empty files ImageField(FileField) ... classifier for sums of money:needPILmodule (in software),pip3 install Pillow When the above two dictionaries are used,needclassifier for sums of money意两点: - formform enctype="multipart/form-data" - viewin a function obj = MyForm(, ) URLField(Field) ... BooleanField(Field) ... NullBooleanField(BooleanField) ... ChoiceField(Field) ... choices=(), options (as in computer software settings),as if:choices = ((0,'Shanghai'),(1,'Beijing'),) required=True, Required or not widget=None, plug-in (software component),default (setting)selectplug-in (software component) label=None, Labelelement initial=None, starting value help_text='', Helpful Hints ModelChoiceField(ChoiceField) ... queryset, # Query data in the database empty_label="---------", # Empty display content by default to_field_name=None, # Field corresponding to the value of value in HTML limit_choices_to=None # Secondary filtering of queryset in ModelForm ModelMultipleChoiceField(ModelChoiceField) ... TypedChoiceField(ChoiceField) coerce = lambda val: val Performs a single conversion on the selected value empty_value= '' 空值的default (setting)值 MultipleChoiceField(ChoiceField) ... TypedMultipleChoiceField(MultipleChoiceField) coerce = lambda val: val One conversion for each value selected empty_value= '' 空值的default (setting)值 ComboField(Field) fields=() Using Multiple Validations,as if下:即验证Maximum length20,又验证邮箱specification (fields=[(max_length=20), (),]) MultiValueField(Field) PS: abstract class,Subclasses can be implemented to aggregate multiple dictionaries to match a single value,in conjunction withMultiWidgetutilization SplitDateTimeField(MultiValueField) input_date_formats=None, specification列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y'] input_time_formats=None specification列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'] FilePathField(ChoiceField) 文件options (as in computer software settings),Directory files are displayed on the page path, Folder Path match=None, regular match recursive=False, Recursively following folders allow_files=True, Allowed documents allow_folders=False, Allowed documents夹 required=True, widget=None, label=None, initial=None, help_text='' GenericIPAddressField protocol='both', both,ipv4,ipv6supportiveIPspecification unpack_ipv4=False analyzeipv4address,as if果是::ffff:192.0.2.1length of time,可analyze为192.0.2.1, PS:protocolmust bebothin order to enable SlugField(CharField) digital (electronics etc),letter (of the alphabet),underscores,minus sign - (math.)(hyphen) ... UUIDField(CharField) uuidtypology
Django Form Built-in Fields
calibration
Way one:
from import Form from import widgets from import fields from import RegexValidator class MyForm(Form): user = ( validators=[RegexValidator(r'^[0-9]+$', 'Please enter a number'), RegexValidator(r'^159[0-9]+$', 'The number must begin with 159')], )
Way two:
import re from import Form from import widgets from import fields from import ValidationError # Customized validation rules def mobile_validate(value): mobile_re = (r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('Wrong format of cell phone number') class PublishForm(Form): title = (max_length=20, min_length=5, error_messages={'required': 'Title cannot be empty', 'min_length': 'Minimum of 5 characters for the title', 'max_length': 'Title up to 20 characters'}, widget=(attrs={'class': "form-control", 'placeholder': 'Title 5-20 characters'})) # Use custom validation rules phone = (validators=[mobile_validate, ], error_messages={'required': 'Cell phone cannot be empty'}, widget=(attrs={'class': "form-control", 'placeholder': u'Cell phone number'})) email = (required=False, error_messages={'required': u'Mailbox cannot be empty','invalid': u'Mailbox format error'}, widget=(attrs={'class': "form-control", 'placeholder': u'Mailbox'}))
Way three:
def clean(self): pwd = self.cleaned_data.get('pwd') r_pwd = self.cleaned_data.get('r_pwd') print(pwd, r_pwd) if pwd and r_pwd: if pwd == r_pwd: return self.cleaned_data raise ValidationError('Two passwords don't match') else: return self.cleaned_data def clean_username(self): val = self.cleaned_data.get('username') user = (name=val) if not user: return val else: raise ValidationError("User name registered") def clean_tel(self): val = self.cleaned_data.get('tel') if len(val) == 11: return val raise ValidationError('Cell phone number format error')
Summary:
''' localized hook: 1、is_valid() 2、 3、self.full_clean() 4、self._clean_fields() Validates each field 5、for Loop through each field name、Validation Rule Objects 6、 Verification passed: value = (value) self.cleaned_data[name] = value add toclean_datacenter Exploiting Reflection、Hooks to customize validation rules hasattr(self, 'clean_%s' % name) Writing custom methods value = getattr(self, 'clean_%s' % name)() Implementing custom methods pass: self.cleaned_data[name] = value add toclean_datacenter no_pass: raise ValidationError(msg) throw an exception fail: raise ValidationError(msg) global hook: 1、is_valid() 2、 3、self.full_clean() 4、self._clean_form() After all the fields have been called call (programming) 5、() rewritecleanmethodologies 6、global hook错误:("__all__") '''
summarize
The above is a small introduction to the Django in the forms component examples in detail, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!