Introduction
Django is one of Python's most popular, trusted, and reliable web development frameworks. With Django, we can quickly create web applications without worrying about installation or dependency problems that we usually find with other frameworks.
A widget is the Django representation of an HTML <input> element. The widget in Django will handle the rendering of the HTML elements and extract data from a POST/GET dictionary that corresponds to the same widget. Whenever we specify a field on a Django form, Django uses some default widget appropriate to the data type to be displayed. This article will learn about Django form field custom widgets with a detailed example.
Default Widget in Form Fields
To use Django form field default widgets, we need to have a project named codingninjas and an app called Coding Ninjas Studio working in it.
Refer to the below articles to check how to create a project and an application in Django.
Whenever we specify a field on a Django form, every field has a pre-defined widget. For example, IntegerField has a default widget of NumberInput. We can find the full list of pre-defined widgets here.
Now let's create a form in "Coding Ninjas Studio/forms.py".
from django.db import forms
# Create our models here.
class AuthorDetailForm(forms.Form):
Name = forms.CharField()
Author_email = forms.CharField()
We have created an AuthorDetailForm with the fields Name and Author_email in the above code.
To render our form, we need to create a Django view and template to display our form. In Coding Ninjas Studio/views.py, create a view with the following code:
from django.shortcuts import render
from .forms import AuthorDetailForm
# Creating a view
def form_view(request):
new_form = AuthorDetailForm(request.POST or None)
context = {}
context['form'] = form
return render(request, "home.html", context)
After creating our form_view let's create a template in the Coding Ninjas Studio/home.html,
<form method="POST">
{% csrf_token %}
// Using form in Template
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
Finally, we can run our application with the following command to see our form.
Python manage.py runserver

Output






