Django form field custom widgets


A widget is the representation of the Html input element using Django. The widget is used to handle the rendering of the HTML page and data extracting from the POST/GET dictionary. Every time whenever we specify the field on a form, Django uses the default widget to display the data in an appropriate manner.

Django is the one of the best Framework used by most of the users, to perform the web development. It provides many advanced features, functions and packages to design the best web pages and connect with the servers using the python programming language.

Now let’s see the default widget, for example if we are using an intergerField in the form then the default widget will be NumberInput.

Creating a Widget Project

Firstly, create a new project with the name widgetproject and in the project directory create the app with the name widgetapp. Following are the commands to be executed in the command prompt for creating the project and the app.

django-admin startproject widgetproject
cd widgetproject
django-admin startapp widgetapp

Next add the created app to the INSTALLED_APPS section available in the settings.py file of our project.

We have to create the forms.py file in the widgetapp directory and add the code which needs to be resembled in the html page.

from django import forms
#creating a django form
class TurtorialspointForm(forms.Form):
	title = forms.CharField()
	description = forms.CharField()
	views = forms.IntegerField()

Now to render the form we created above we need to add a view and template to it, which helps to display, the form to the user. So create the views.py file in the widgetapp and enter the below code.

from django.shortcuts import render
# Create your views here.
from .forms import GeeksForm
def home_view(request):
	context = {}
	form = TurtorialspointForm(request.POST or None)
	context['form'] = form
	return render(request, "home.html", context)	

Next we have to create the html file to incorporate the form data we want to display in the webpage.

<form method="POST">
	{% csrf_token %}
	{{ form.as_p }}
	<input type="submit" value="Submit">
</form>

Finally perform the migrations to apply the changes to the database table and run the server.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now, let’s create custom Django form widget field by specifying the required widget in the forms.py file in app directory.

from django import forms
class TurtorialspointForm(forms.Form):
	title = forms.CharField(widget = forms.Textarea)
	description = forms.CharField(widget = forms.CheckboxInput)
	views = forms.IntegerField(widget = forms.TextInput)

In the output we can observe the differences between the customized widgets and the default widgets that we use for the form fields.

Updated on: 06-Nov-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements