Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It uses Model View Template architecture. It is mighty. Django is used by some of the biggest companies in the world as their backend framework. 

It is a high-speed and secure framework with some great libraries that save the user from creating an application from scratch. It can be implemented in various frameworks such as HTML, JSON, XML, etc. Django can be used in ORM, ML integration, API integration, etc. 

While building a website in Django, if we are taking input from the users, we will need to use forms. It is very easy to create forms with Django. Django provides a Form class that is used to create form. Building forms in Django is very similar to creating a model.  Like the model, while creating the form, the most important part is creating the field. Each field has a data type that validates the data inputted by the user.

Form Handling in Django

Form Handling is not an easy task for a programmer to do. When a user inputs the data in a form, Django maps it to the corresponding field. Django does all this form handling on our behalf. Django's form handling can be divided into three distinct parts:

  • Django processes the data to make it ready for rendering.
  • Django creates an HTML form for the data.
  • Django also receives and processes submitted forms by the users.

Django Form Class

Django created the form using the form class. The Form class decides the overall functioning of the form. It describes the forms and the fields that form has. The Form class is similar to the model in mapping the data. The model class maps the data with the database table, and the form class maps it to HTML form elements.

Syntax:

field = forms.FieldType(**options) 

Building Forms

To create a form, we need to instantiate a project first. To start your Django project, activate your virtual environment and run the following command:

django-adminstartprojectmyproject

After creating the project, we need to create an app too successfully.

In this post, we will create a student form in Django. In this form, we will create the fields for first name and roll number. The first name will be Garfield, and the roll number will be the Integer field. Just like the other important applications, we will create a separate file for forms. So add a forms.py file in myproject folder. Write the below code in the file:

fromDjango importforms 
    
# creating a form  
classStudent_Form(forms.Form): 
    
    first_name =forms.CharField(max_length =200) 
    roll_number =forms.IntegerField( ) 

The above code defines the form with two fields. The max_length argument constrains the maximum length of the input field. It also makes Django validates the length of the input. The form uses a method is_valid() to validates the data for all the fields. This method will return True if all the data is validated and place it in its cleaned_dataattribute.

The following HTML will be rendered for the above form:

<label for=" first_name">Enter first name:</label>  
 <input type="text" name=" first_name" required maxlength="200" id=" first_name" />  
<label for = “roll_number”> Enter roll number: </label>
<input type = “integer” name = “roll_number” id = “roll_number”/>

A Django form field can be rendered by 3 built-in methods of forms:

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

Now we need to instantiate the form in the views.py file to render the form. Use this code in your views.py file:

fromDjango.shortcuts import render
from .forms import InputForm


defstudent_view(request):
    context ={}
    context['form']= InputForm()
    return render(request, "index.html", context)

Now we need to pass the context in to the template:

Index.html

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
<input type="submit" value="Submit">
</form>

Now we are done with creating the form. Open your browser and navigate to the localhost to see the form:

Django Forms

Form Fields

NameClassHTML Input
BooleanFieldclass BooleanField(**kwargs)CheckboxInput
CharFieldclass CharField(**kwargs)TextInput
ChoiceFieldclass ChoiceField(**kwargs)Select
DateFieldclass DateField(**kwargs)DateInput
DateTimeFieldclass DateTimeField(**kwargs)DateTimeInput
DecimalFieldclass DecimalField(**kwargs)NumberInput
EmailFieldclass EmailField(**kwargs)EmailInput
FileFieldclass FileField(**kwargs)ClearableFileInput
ImageFieldclass ImageField(**kwargs)ClearableFileInput