reading-notes

Django Forms

Django Forms provides a framework that lets you define forms and their fields programmatically, and then use these objects to both generate the form HTML code and handle much of the validation and user interaction.

Django Form Handling Process

A process flowchart of how Django handles form requests is shown below, starting with a request for a page containing a form (shown in green).

Django Forms Flowchart

Based on the diagram above, the main things that Django’s form handling does are:

  1. Display the default form the first time it is requested by the user.
    • The form may contain blank fields if you’re creating a new record, or it may be pre-populated with initial values (for example, if you are changing a record, or have useful default initial values).
    • The form is referred to as unbound at this point, because it isn’t associated with any user-entered data (though it may have initial values).
  2. Receive data from a submit request and bind it to the form.
    • Binding data to the form means that the user-entered data and any errors are available when we need to redisplay the form.
  3. Clean and validate the data.
    • Cleaning the data performs sanitization of the input fields, such as removing invalid characters that might be used to send malicious content to the server, and converts them into consistent Python types.
    • Validation checks that the values are appropriate for the field (for example, that they are in the right date range, aren’t too short or too long, etc.)
  4. If any data is invalid, re-display the form, this time with any user populated values and error messages for the problem fields.
  5. If all data is valid, perform required actions (such as save the data, send an email, return the result of a search, upload a file, and so on).
  6. Once all actions are complete, redirect the user to another page.

Form

Declaring a Form

Form Fields

Validation

Source: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms

Things I Want To Know More About