Location>code7788 >text

Django Framework Forms Basics

Popularity:989 ℃/2024-11-15 09:59:49

This section introduces the basics of Django framework form (Form).Django framework provides a series of tools and libraries to help designers build forms , through the form to receive website user input , and then process and respond to these user input.

6.1.1 HTML forms


Django framework form is designed in the HTML template is completed , in fact, similar to the application of traditional HTML Form form . In a traditional HTML page, the form is composed of "<form>... </form>" tag is realized by adding some elements (such as text input boxes, radio boxes, check boxes, text fields, reset buttons and submit buttons, etc.), allowing end-users to enter relevant data information through the form, and then send it to the server side (backend).Django framework form also implements the corresponding functionality, only to follow the Django framework standards to design.

In HTML, there are some form elements (such as text input box) is very simple and built into the HTML, while there are some form elements will be more complex (such as date selection controls, slider controls, etc.), generally through the use of JavaScript, CSS, and <input> and so on to achieve the effect.

The same is true for Django framework forms, which need to meet the following two general criteria when defined:

The URL address (action attribute) responsible for responding to user input data.
The HTTP method used for the data request (method attribute: GET, POST).
For example, the Django framework's built-in Admin (administrator) login form contains some of the following regular <input> element types:

Username: type="text".
Password: type="password".
Login button: type="submit".
The action attribute specifies the URL address: "/admin/".
HTTP method specified by the method attribute: "POST".
When the user clicks on the <input type="submit" value="Log in"> button element, the submit response is triggered and the form data is sent to the "/admin/" address.

6.1.2 HTTP methods: GET and POST


Django framework uses only two HTTP methods, GET and POST, to process forms, and Django's login form needs to use the POST method to transfer data. When using the POST method, the browser encapsulates the form data, encodes it as necessary for secure transmission, and then sends it to the server to receive its response.

In contrast, the GET method binds the submitted data to a string and uses that string to form a URL address. The URL address contains the address to which the data is to be sent and some key-value equivalents. For example, a search in the official Django documentation () generates a URL address like "/search/?q=forms&release=1", which is the GET method.

The two HTTP methods, GET and POST, are typically used for different purposes. The POST method should be used for any request that may be used to change the state of the system, such as a request to change a database; the GET method should only be used for requests that do not affect the state of the system.

Also, the GET method is not suitable for password forms, because the password will appear in the URL address string, and naturally will be recorded in the browser's history and the server's logs, and are in plain text, so the security can not be guaranteed.The GET method is also not suitable for dealing with a large amount of data strings or binary data, such as images and videos.

The use of GET requests in the web application's administrative forms has security risks: it is easy for an attacker to access the system's sensitive data by simulating a request, so the Django Admin module opted to use the POST method. In Django Framework templates, the POST method provides more control over access by working with protections like CSRF protection.

The GET method is not completely useless; it is used in scenarios like web search forms, where the URL address of the GET request can easily be saved as a bookmark, which can be shared or resubmitted by the user. Therefore, a search in the official Django documentation uses the GET method.

6.1.3 Django's Role in Forms


The Django Framework handling of forms is a complex affair. A study of the Django Framework's Admin module reveals that many different types of data may need to be accomplished in a single form, then rendered into an HTML template to be rendered, as well as edited using convenient interfaces, uploaded to the server, validated and cleansed of data, and finally saved or skipped for the next step in the process.

The Django framework's forms functionality can simplify and automate much of the above work, and can also perform a bit safer than most designers writing their own code to implement.

The Django framework handles 3 different parts involving the form:

Prepare and reorganize the data for the next rendering step.
Create HTML forms for the data.
Receive and process forms and data submitted by the client.
While designers can implement the above functionality by writing code manually, the built-in functionality of Django Framework forms is already capable of doing this.

6.1.4 Form class


The core component of the Django Framework's form system is the Form class, which describes the logical structure of the object, its behavior, and the way it renders content in much the same way as the Django model does.The Form class describes the form and determines how it works and how it is rendered.

Similar to the way the fields of the model class are mapped to database fields , ModelForm model class fields will be mapped to the HTML form through the form class fields in the <input> element . Django framework Admin module is based on the design of this implementation .

Form fields are also classes in their own right and are used to manage form data and perform validation when the form is submitted.DateField and FileField deal with very different data types so they must be used to handle different fields.

In the browser, form fields are presented as HTML elements (control classes). Each field type has a control class that matches it, but can be overridden if necessary.

6.1.5 Instantiating, Processing, and Rendering Forms


When rendering an object in a Django framework form, the process is usually as follows:

(1) Getting objects in a view (e.g. from a database).

(2) Pass the object to the template context.

(3) Use template variables to extend objects to HTML tags.

Rendering a form in a template is almost the same as rendering any other type of object, but there are some key differences.

If the model instance doesn't contain data, it's almost useless to do anything with it in the template, but there's every reason to render an empty form, which is usually what we do when we want the user to populate it. Therefore, when working with model instances in the view, you generally get these objects from the database; when working with forms, you generally instantiate these objects in the view.

When instantiating a form, you can choose to leave the form empty or pre-populated with data, which can be sourced:

(1) Used to save data for model instances (e.g., in the case of administrative edit forms).

(2) Data obtained from other sources.

(3) Data submitted from a previous HTML form.

6.1.6 Creating a form


Assuming one wishes to create the simplest form on a website for getting a user's name, one would normally just use code similar to the following in a template:

[Code 6-1]

<form action="/get-name/" method="get">
      <label for="your_name">Your name: </label>
      <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
      <input type="submit" value="OK">
</form>

[code analysis]

In line 01, the action attribute informs the browser to submit the form data to the URL address "/get-name/" and the method attribute defines the use of the GET method.

In line 03 of the code, a <input type="text" /> text input box is defined for the user to enter a name. Also, the value attribute is defined as a context variable current_name, whose value will be pre-populated into the form if it exists.

In line 04 of the code, a <input type="submit" /> submit button is defined.

For the form defined in [Code 6-1], a view is required to render the template containing the HTML form with the appropriate {{ current_name }} field. When the form is submitted, the "GET" request sent to the server will contain the form data.

Then, a view corresponding to that URL address ("/get-name/") is also needed, which will find the appropriate key-value pair in the request and then process it.

At the same time, the browser may also be required to perform some field validation before the form is submitted , or use more complex fields to allow the user to do something like date selection operations and so on. At this point , through the Django framework can easily accomplish most of the above work .