Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears.
It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.
Each field of the form class map to the HTML form <input> element and each one is a class itself, it manages form data and performs validation while submitting the form.
Lets see an example, in which we are creating some fields too.
A StudentForm is created that contains two fields of CharField type. Charfield is a class and used to create an HTML text input component in the form.
The label is used to set HTML label of the component and max_length sets length of an input value.
When rendered, it produces the following HTML to the browser.
Note: Django Form does not include <form> tags, or a submit button. We'll have to provide those ourselves in the template.
Commonly used fields and their details are given in the below table.
Let's see a complete example to create an HTML form with the help of Django Form class.
Building a Form in Django
Suppose we want to create a form to get Student information, use the following code.
Put this code into the forms.py file.
Instantiating Form in Django
Now, we need to instantiate the form in views.py file. See, the below code.
Passing the context of form into index template that looks like this:
Provide the URL in urls.py
Run Server and access the form at browser by localhost:8000/index, and it will produce the following output.
There are other output options though for the <label>/<input> pairs:
Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.