I. Overview
Django has a form library called django. forms. Define a form class for each HTML "<Form>" to be processed. It is used to writing in forms. py.
For the first time, I felt that Django was really powerful and powerful to abnormal.
1 from django import forms2 3 class ContactForm(forms.Form):4 subject = forms.CharField()5 email = forms.EmailField(required=False)6 message = forms.CharField()
Its Syntax:
Similar to the module, each field is required by default. To enableEmailTo be optional, We need to specifyRequired = False.
Ii. Workflow
1. display yourself as HTML
The default output is in HTML <''table''> format.
1 >>> from contact.forms import ContactForm2 >>> f = ContactForm()3 >>> print f
Other formats: f. as_ul (), f. as_p ()
Note that the open and closed tags of <table>, <ul>, and <form> are not included in the output, so that you can add additional rows or custom formats.
You can also display a single: f ['subobject']
2. Verify data
>>> f = ContactForm({'subject': 'Hello', 'email': 'adrian@example.com', 'message': 'Nice site!'})
Is_bound attribute: Once you pairFormObject assignment, you get a bound form:
1 >>> f.is_bound2 True
Is_valid ()Method: Verify that its data is valid.
ErrorsAttribute: provides a dictionary table that maps fields to error messages.
Cleaned_data attribute: when the data is valid, it containsDictionary
3. Use in view
1 forms. py 2 # user registration 3 class RegistrationForm (forms. form): 4 username = forms. charField (label = "username", max_length = 30) 5 email = forms. emailField (label = 'email ') 6 password1 = forms. charField (label = 'Password', widget = forms. passwordInput () 7 password2 = forms. charField (label = 'Confirm password', widget = forms. passwordInput () 8 pic = forms. imageField (label = "avatar upload") 9 def clean_username (self): 10''' verify the validity of the username entered by the user ''' 11 username = Self. cleaned_data ['username'] 12 if not re. search (R' ^ \ w + $ ', username): 13 raise forms. validationError ('user name can only contain letters, numbers, and underscores ') 14 try: 15 User. objects. get (username = username) 16 TB t ObjectDoesNotExist: 17 return username18 raise forms. validationError ('user name already exists! ') 19 20 def clean_email (self): 21''' verify that the entered email is valid ''' 22 email = self. cleaned_data ['email '] 23 try: 24 User. objects. get (email = email) 25 minutes t ObjectDoesNotExist: 26 return email27 raise forms. validationError ('this email address is registered! ') 28 29 def clean_password2 (self): 30''' verify that the password entered by the user twice is consistent ''' 31 if 'password1' in self. cleaned_data: 32 password1 = self. cleaned_data ['password1 '] 33 password2 = self. cleaned_data ['password2 '] 34 if password1 = password2: 35 return password236 raise forms. validationError ('password mismatch ')
1 views 2 def register_page (request): 3 context = {} 4 if request. method = "POST": 5 form = RegistrationForm (request. POST) # create a RegistrationForm that contains the user registration information. 6. if form. is_valid (): # Verify validity 7 # create a new user object 8 User = user in the User information table based on the registration information submitted by the user. objects. create (9 username = form. cleaned_data ['username'], 10 password = form. cleaned_data ['password1 '], 11 email = form. cleaned_data ['email '], 12) 13 return HttpResponseRedirect ('/accounts/register/success/') 14 else: 15 # If this function is called directly, then a form object 16 form = RegistrationForm () 17 variables = RequestContext (request, {'form': form}) without any data registration is created }) 18 return render_to_response ('registration/register.html ', variables)
Iv. Field settings
1. widgets, such:
Message = forms. CharField (widget = forms. Textarea) # displayed as <'textea ''>
Password = forms. CharField (label = 'Password', widget = forms. PasswordInput () # display as a password
Forms framework separates the display logic of each field into a group of widgets. Each field type has a default part. We can easily replace the default part or provide a custom part.
Consider FieldClass performance * Verification logic *, while component performance * display logic *.
2. Set max_length to the maximum length.
3. Set the Initial ValueInitial: "initial", "initial" means that FormUse InitialParameters
1 ...... 2 else:3 form=ContactForm()4 initial={'subject':'I love you'}
Note that the * Initial Value * data is different from the * bind * data form. The biggest difference is that if only * Initial Value * data is input, the form isUnboundIt means it has no error message.
V. Custom validation rules
1 from django import forms 2 3 class ContactForm (forms. form): 4 subject = forms. charField (label = "topic", max_length = 100) 5 email = forms. emailField (required = False) 6 message = forms. charField (widget = forms. textarea) 7 8 def clean_message (self): 9 message = self. cleaned_data ['message'] 10 num_words = len (message. split () 11 if num_words <4: 12 raise forms. validationError ("Not enough words! ") 13 return message
1. Django's form system automatically finds matching function methods. The method name isClean _And end with the field name. If such a method is available, it will be called during verification.
2. In particular, Clean_message ()The method is called after the default validation logic of the specified field is executed. (In this example CharFieldAfter this verification logic .) Because the field data has been partially processed Self. cleaned_data. Similarly, we don't have to worry about whether the data is empty because it has been verified.
3. We use the combination of len () and split () to calculate the number of words. If the number of words entered by the user is insufficient, we will throw Forms. ValidationErrorType exception. The description of this exception is displayed as an error in the error list. 4. It is very important to explicitly return the field value at the end of the function. We can modify its value in our custom validation method (or convert it to another Python type ). If we forget this step, the value of None will be returned, and the original data will be lost. Vi. Custom form Design
<form action="" method="post"> <div class="field"> {{ form.subject.errors }} <label for="id_subject">Subject:</label> {{ form.subject }} </div> <div class="field"> {{ form.email.errors }} <label for="id_email">Your e-mail address:</label> {{ form.email }} </div> <div class="field"> {{ form.message.errors }} <label for="id_message">Message:</label> {{ form.message }} </div> <input type="submit" value="Submit"> </form>
Effect display: