Javatpoint Logo
Javatpoint Logo

Django Forms

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.

Name Class HTML Input Empty value
BooleanField class BooleanField(**kwargs) CheckboxInput False
CharField class CharField(**kwargs) TextInput Whatever you've given as empty_value.
ChoiceField class ChoiceField(**kwargs) Select '' (an empty string)
DateField class DateField(**kwargs) DateInput None
DateTimeField class DateTimeField(**kwargs) DateTimeInput None
DecimalField class DecimalField(**kwargs) NumberInput None
EmailField class EmailField(**kwargs) EmailInput '' (an empty string)
FileField class FileField(**kwargs) ClearableFileInput None
ImageField class ImageField(**kwargs) ClearableFileInput None

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.

// views.py

Passing the context of form into index template that looks like this:

// index.html

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.

django forms localhost index output

There are other output options though for the <label>/<input> pairs:

  • {{ form.as_table }} will render them as table cells wrapped in <tr> tags
  • {{ form.as_p }} will render them wrapped in <p> tags
  • {{ form.as_ul }} will render them wrapped in <li> tags

Note: that we'll have to provide the surrounding <table> or <ul> elements yourself.


Next TopicForm Validation





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA