reading-notes

Django CRUD and Forms

SOURCES

ARTICLES

Django Forms

NOTES

Declaring a Form

The declaration syntax for a Form is very similar to that for declaring a Model, and shares the same field types (and some similar parameters). This makes sense because in both cases we need to ensure that each field handles the right types of data, is constrained to valid data, and has a description for display/documentation.

Form data is stored in an application’s forms.py file, inside the application directory. Create and open the file locallibrary/catalog/forms.py. To create a Form, we import the forms library, derive from the Form class, and declare the form’s fields. A very basic form class for our library book renewal form is shown below — add this to your new file:

Form fields

In this case, we have a single DateField for entering the renewal date that will render in HTML with a blank value, the default label “Renewal date:”, and some helpful usage text: “Enter a date between now and 4 weeks (default 3 weeks).” As none of the other optional arguments are specified the field will accept dates using the input_formats: YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default widget: DateInput.