Form widget in Django

In this article, we will see how to use widgets in a Django form. Widgets can be quiet helpful to make the frontend better. Widgets are html elements that are rendered from Django form, textarea, input, password input, etc., all are widgets.

First let's create a Django project and an app. I created the project with the name "tutorial14" and app with the name "djangoFormWidget".

Add app in and include app's URL in project

Make every basic files and folders like Templates, home.html,


In app's

from django.urls import path,include
from . import views
urlpatterns = [

It will create a basic URL for rendering view.


from django.shortcuts import render
from .forms import CommentForm

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

def home(request):
   if request.method=='POST':
      if form.is_valid():
   return render(request,'home.html',{"commentform":commentform})

Here, we imported our form and handled its POST and GET requests.

In POST, we save the data and in GET, we send the form to the frontend.


from django.db import models

# Create your models here.
class CommentModel(models.Model):

Here we created a model which we will use in our form. We need this model to use the form.

In home.html

<!DOCTYPE html>
      {% for fm in commentform %}
      <form method="post">

            <button type="submit">Submit</button>

It is a simple frontend where we render our form.


from django import forms
from .models import CommentModel
class CommentForm(forms.Form):
   comment=forms.CharField(widget=forms.Textarea(attrs={'class':'comment','title':'add comment'})) # this is the line which is used for widget, here I added TextArea widget you can see we also assigned class to widget using attrs attribute.

def save(self):

It is where we make our form. We used the built-in Django form widget to render a textarea in the form.