Home >>Django Tutorial >Django Forms

Django Forms

Django Forms

Django provide us a Form class that is used to create HTML forms. It describes how a form will work and appear. It is similar to the ModelForm class that creates a form by using the Model, but the difference is that 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 is used to manage the form data and perform validation while submitting the form.

Building a Form in Django

Let’s see an example of creating a form:

from django import forms  
class StudentForm(forms.Form):  
    firstname = forms.CharField(label="Enter first name",max_length=50)  
    lastname  = forms.CharField(label="Enter last name", max_length = 100) 

In the above example, a StudentForm is created that contains two fields. These fields are of type charfield which is used to create an HTML text input component in the form.

We will put this code into the forms.py file.

It will produce the following HTML to the browser:

<label for="id_firstname">Enter first name:</label>  
 <input type="text" name="firstname" required maxlength="50" id="id_firstname" />  
<label for="id_lastname">Enter last name:</label> <input type="text" name="lastname" required maxlength="100" id="id_lastname" />  

Instantiating Form in Django

Now, we need to instantiate the form in views.py file.

// views.py

from django.shortcuts import render  
from myapp.form import StudentForm  
def index(request):  
    student = StudentForm()  
    return render(request,"index.html",{'form':student})

Django Form Validation

Django provides a built-in method to validate the form data automatically. Django forms get submitted only if it contains the CSRF tokens.

is_valid() method is used to perform the validation for each field of the form. It returns True if the data is valid and place all data into a clean data attribute.

Let's see an example for the form validation:

// models.py

from django.db import models  
class Employee(models.Model):  
    eid = models.CharField(max_length=20)  
    ename = models.CharField(max_length=100)  
    econtact = models.CharField(max_length=15)  
    class Meta:  
        db_table = "employee" 

Now, we will create a form which contains the below code.

// forms.py

from django import forms  
from myapp.models import Employee  
class EmployeeForm(forms.ModelForm):  
    class Meta:  
        model = Employee  
        fields = "__all__"  

Instantiate the form

Now we will instantiate the form and check whether the request is get posted or not. It will validate the data by using is_valid() method.


def emp(request):  
    if request.method == "POST":  
        form = EmployeeForm(request.POST)  
        if form.is_valid():  
                return redirect('/')  
        form = EmployeeForm()  
    return render(request,'index.html',{'form':form})