The--forms of Django Learning notes

Source: Internet
Author: User


All that was learned was how to display the data, but there was no information about how to respond to user submissions.
Forms are an important way for users to interact with the server in the Web.

Import Django.forms
Form Django Import Forms
What is the difference between them?

The roles that form plays in Django are:
* Show Form
* Verify user-submitted data

Definition of form
~~~~~~~~~~

The definition of a form is very similar to the definition of model:
____________________________________________
From Django Import forms
Class Bookform (forms. Form):
isbn= forms. Charfield (max_length=200)
title = Forms. Charfield (max_length=200)
--------------------------------------------
A bookform form is defined with ISBN and title two items in the form.

Bookform can generate HTML form text, as follows:
____________________________
Book_form = Bookform ()
html = book_form.as_table ()
Print (HTML)
----------------------------
The result of the print execution is:
<tr><th><label for= "ID_ISBN" >isbn:</label></th><td><input id= "ID_ISBN" Maxlength= "Name=" ISBN "type=" text "/></td></tr>
<tr><th><label for= "Id_title" >title:</label></th><td><input id= "Id_title" Maxlength= "Name=" "title" type= "text"/></td></tr>

It can be seen that the printed text does not contain <form> and <input type= "submit";
specified in the template. The form is only responsible for the input of the ISBN and title, not the action of the form and the way of submission.
Therefore, it is best to use the template method to define the good one template first, such as book-form.html:
_______________________________
<form action= "." Method= "get" >
{{Book_form}}
<br>
<input type= "Submit" >
</form>
-------------------------------
Generate HttpResponse in views.py with Render_to_response ():
____________________________________________________
def book_view (Request):
Book_form = Bookform ()
Response = Render_to_response (' book-form.html ',
{' Book_form ': Book_form.as_table ()})
----------------------------------------------------
Back to the source page:
<form action= "." Method= "get" >
<tr><th><label for= "ID_ISBN" >isbn:</label></th><td><input id= "ID_ISBN" Maxlength= "Name=" ISBN "type=" text "/></td></tr>
<tr><th><label for= "Id_title" >title:</label></th><td><input id= "Id_title" Maxlength= "Name=" "title" type= "text"/></td></tr>
<br>
<input type= "Submit" >
</form>

The form, in addition to the as_table () method, has the As_ul () and as_p () methods, and the default is the As_table () method.

The form is defined in django/forms/forms.py.
Open the forms.py file and you can see that the form inherits from the BaseForm.
The definition of BaseForm is broadly as follows:
___________________________________________________________________________
Class BaseForm (object):
def __init__ (self, data=none, Files=none, auto_id= ' id_%s ', Prefix=none,
Initial=none, Label_suffix=none):
...
def as_table (self):
...
def as_ul (self):
...
def as_p (self):
...
def __str__ (self):
Return self.as_table ()

Class Form (BaseForm):
...
---------------------------------------------------------------------------
AUTO_ID is <input id= "id_xxx", the automatic ID format of the control. For ' or none ' means no ID is required.
Label_suffix is the suffix of the lable name, the default is ":", can be changed. For example: label_suffix= "="
prefix is the prefix for name, if prefix= "AAA" is set, then <input name= "Aaa-xxx" >
The initial is the initial value dictionary.

There is only one domain used in the above bookform: Charfield. Besides, there are many other kinds.
fields are defined in the django/forms/fields.py file.

Open the fields.py file and see more field options in addition to Charfield:
Field
|--charfield
| |--regexfield
| |--emailfield
| |--urlfield
| |--ipaddressfield
| |--genericipaddressfield
| '--slugfield
|--integerfield
| |--floatfield
| '--decimalfield
|--basetomporalfield
| |--datefield
| |--timefield
| '--datetimefield
|--filefield #file选择文件
| '--imagefield
|--booleanfield #checkbox
| '--nullbooleanfield #select: Unknow,yes,no
|--choicefield #select
| |--typedchoicefield
| |--filepathfield
| '--multiplechoicefield
| '--typedmultiplechoicefield
|--combofield
'--multivaluefield
'--splitdatetimefield

There is a default widget for each field.
__________________________________
Class Field (object):
Widget = TextInput
...
Class Emailfield (Charfield):
Widget = EmailInput
...
Class Filefield (Field):
Widget = Clearablefileinput
...
----------------------------------
The widget tells the field what kind of Web control to build.

We can also specify Widgets for field.
For example, the login form:
_____________________________________________________________
Class LoginForm (forms. Form):
#email = forms. Emailfield ()
email = forms. Charfield (widget=widgets. EmailInput ())
Password = forms. Charfield (widget=widgets. Passwordinput ())
-------------------------------------------------------------
Password This field cannot be displayed in clear text, so the widget is changed.

All widgets are defined in the django/forms/widgets.py.
The following controls are available:
' Media ', ' mediadefiningclass ', ' Widgets ', ' TextInput ',
' EmailInput ', ' urlinput ', ' numberinput ', ' passwordinput ',
' Hiddeninput ', ' multiplehiddeninput ', ' clearablefileinput ',
' FileInput ', ' dateinput ', ' datetimeinput ', ' timeinput ', ' Textarea ',
' Checkboxinput ', ' splitdatetimewidget ',
' Select ', ' nullbooleanselect ', ' selectmultiple ', ' radioselect ',
' Checkboxselectmultiple ', ' multiwidget ',


Model-based forms
~~~~~~~~~~~~~~
Automatically define the form based on the definition of the model. As follows:
______________________________________
From Django Import forms
From Models Import book
Class Bookmodelform (froms. Modelform):
Class Meta:
Model = Book
--------------------------------------
and book is defined in models.py:
____________________________________________
Class book (Models. Model):
ISBN = models. Charfield (MAX_LENGTH=50)
title = models. Charfield (max_length=200)
Author = models. ForeignKey (' Author ')

def __unicode__ (self):
Return Self.title
--------------------------------------------
In this way, Bookmodelform also has the corresponding isbn,title,author with book.

Save Modelform
~~~~~~~~~~~~~
The important difference between modelform and the general form is that the Modelform has the Save () function. The data in the form can be
Joins the database and returns a model object.
For the sake of demonstration, I will not use the template. The same is quoted above Bookmodelform and book:
_________________________________________________________________
def add_book_view (Request):
Book_form = forms. Bookmodelform (Request. GET)
Try
Book_model = Book_form.save ()
Content = ' <p>add ' + book_model.title + ' success!</p> '
Except
Content = ' <form action= '. "method=" get ">"
Content + = book_form.as_p ()
Content + = ' <input type= ' Submit ></form> '
return HttpResponse (content)
-----------------------------------------------------------------
and specify the URL of the Add_book_view view as R ' ^add-book/'.

The first time you access/add-book/, because there are no parameters in Get, the Book_form.save () will throw a different
Often. Returns a form to the user in except. After the user has completed the submission. When we do this again, we have data in get.
, so Book_form.save () is normal and the last output success message.

Sometimes we just want to verify the user's input at Save () and do not intend to commit to the data.
Here, just save (commit=false).
Thus, the object of the book model is returned at Save (commit=false). We can then make further changes to it
, and then save to the database.
_____________________________________________________
#book_model = Book_form.save ()
Book_model = Book_form.save (commit=false)
Book_model.title = ' Balabala '
Book_model.save ()
-----------------------------------------------------
The first line just verifies that the user's output is not meeting the requirements. The model object is then modified, and the last
Save it to the database. In this way, the title is changed in the middle, and then saved to the database.

Modelform Show Individual domains
~~~~~~~~~~~~~~~~~~~
Modelform By default, it is consistent with the model. But most of the time, not all the fields in the model have to be
Let the user fill in. We have the option of selectively selecting or excluding individual domains.
This is where meta exclude or fields will be used. Exclude indicates which fields are excluded, and field represents the need to explicitly
which domains are shown. Both cannot be used at the same time.
_________________________________________________
Class Bookmodelform (forms. Modelform):
Class Meta:
Model = Book
Exclude = (' author ') #表示不显示author域
-------------------------------------------------
_________________________________________________
Class Bookmodelform (forms. Modelform):
Class Meta:
Model = Book
Fields = (' title ', ' ISBN ')
#表示只显示title与isbn域
-------------------------------------------------

overriding a field in Modelform
~~~~~~~~~~~~~~~~~~~
_________________________________________
Class Bookmodelform (forms. Modelform):
ISBN = forms. Charfield (max_length=13)
Class Meta:
Model = Book
-----------------------------------------
Change the Charfield (MAX_LENGTH=50) specified in book to 13.

Add a domain in Modelform
~~~~~~~~~~~~~~~~~~~
______________________________________
Class Bookmodelform (forms. Modelform):
Review = forms. Charfield ()
Class Meta:
Model = Book
--------------------------------------
In this way, Bookmodelform is not only the domain in book, but also the review.

Validation of forms
~~~~~~~~~~
The form's is_valid () file can be used to verify that the data is legitimate.
If the data is valid, the form object will have the Cleaned_data property. If it is not lawful, it is errors.
__________________________________________________________________
def add_author_view (Request):
Content = None
If request. Get: # Check if get has form data
Author_form = forms. Authormodelform (Request. GET)
If Author_form.is_valid (): # Check if data is legal
Print (Author_form.cleaned_data)
Try
Author_form.save ()
Content = ' <p>Success</p> '
Except
Content = ' <p>something wrong while Saving.</p> '
Else
Content = str (author_form.errors) # returns an error message with errors
Else
Content = ' <form action= '. " > '
Content + = forms. Authormodelform (). as_p ()
Content + = ' <input type= ' Submit ></form> '
return HttpResponse (content)
------------------------------------------------------------------
The above uses the Author_form.is_valid () to verify data legitimacy.
If successful, there will be author_form.cleaned_data, if the failure will have author_form.errors.
These two will only exist and will not exist at the same time.

The--forms of Django Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.