Django comes with a form library called Django.forms, which can handle the HTML form display and validation that we mentioned in this chapter. Let's take a closer look at the form library and use her to rewrite the contact form app.
Django's Newforms Library
The term django.newforms is often seen in the Django community. When people talk about django.newforms, it is actually the django.forms that we introduce in this chapter.
There are historical reasons for renaming. When Django is released to the public once, it has a complex and difficult form system: django.forms. Later it was completely rewritten, and the new version was renamed as: Django.newforms, so that people can also use the old version by name. When Django 1.0 was released, the old version of Django.forms was no longer used, and Django.newforms was finally able to rightfully call it: Django.forms.
The main usage of the form framework is that for each HTML that will be processed, the '
"Defines a form class. In this case, we have only one "", so we just need to define a form class. This class can exist anywhere, even directly in the ' views.py ' file, but the community practice is to put the form class in a file: forms.py. In the directory where ' views.py ' is stored, create the file, and then enter:
From Django Import Formsclass contactform (forms. Form): subject = forms. Charfield () email = forms. Emailfield (required=false) message = forms. Charfield ()
This looks easy to understand and is much like the syntax used in the module. Each field (field) in the form is displayed as a field class as a property of the form class. Only the Charfield and Emailfield types are used here. Each field is required by default. To make email an option, we need to specify Required=false.
Let's delve into the Python interpreter and see what this class does. The first thing it does is to display itself as HTML:
>>> from contact.forms import contactform>>> f = contactform () >>> print FSubject:Email:Message:
For easy access, Django uses the ' ' flag to add tags to each field. This approach makes the default behavior as appropriate as possible.
The default output is in HTML < ' table ' > format, in addition to some other formats:
>>> Print F.as_ul ()
Subject:Email:Message:>>> Print f.as_p ()
Subject:
Email:
Message:
Please note that the label
、The open closing tag is not included in the output, so you can add additional rows or custom formats.
These class methods are only the usual way to quickly display a complete form. You can also display individual fields in HTML:
>>> print f[' subject ']>>> print f[' message '
The second thing the form object does is validate the data. To validate the data, we create a new pair of form images and pass in a dictionary type data that matches the definition:
>>> f = contactform ({' Subject ': ' Hello ', ' email ': ' adrian@example.com ', ' message ': ' Nice site! '})
Once you assign a value to a form entity, you get a binding form:
>>> F.is_boundtrue
Call any Is_valid () method that binds the form to know whether its data is legitimate. We have passed in a value for each field, so the entire form is legal:
>>> f.is_valid () True
If we don't pass in the email value, it's still legal. Because we specify the property of this field Required=false:
>>> f = contactform ({' Subject ': ' Hello ', ' message ': ' Nice site! '}) >>> f.is_valid () True
However, if you leave blank subject or message, the entire form is no longer legal:
>>> f = contactform ({' Subject ': ' Hello '}) >>> f.is_valid () false>>> f = contactform ({' Subject ': ' Hello ', ' Message ': '} ' >>> f.is_valid () False
You can view the error messages for each field individually:
>>> f = contactform ({' Subject ': ' Hello ', ' Message ': '} ') >>> f[' message '].errors[u ' This field is Required. '] >>> f[' subject '].errors[]>>> f[' email '].errors[]
Each of the bonding form entities has a errors property that provides you with a dictionary table that maps fields to error messages.
>>> f = contactform ({' Subject ': ' Hello ', ' Message ': '} ') >>> f.errors{' message ': [u ' This field is Requir ed. ']}
Finally, if the data for a form entity is legal, it will have an available Cleaned_data property. This is a dictionary that contains clean submission data. The Django form framework not only validates the data, it also converts them to the corresponding Python type data, which is called cleanup data.
>>> f = contactform ({subject ': Hello, email:adrian@example.com, Message:nice site!}) >>> f.is_valid () true>>> f.cleaned_data{message ': Unice site!, email:uadrian@example.com, Subject: Uhello}
Our contact form only involves string types, which are cleaned up into Unicode objects. If we use an integer or date type, the form framework ensures that the method uses the appropriate Python integer or Datetime.date type object.