Form Field Widgets and Labels
Django form widgets will be discussed in this lesson.
How to customize widgets
A widget in Django is the HTML representation of a form field. By default, each Django form field works with a specific type of widget. For example, when we selected the integer field, we render an integer widget.
Widgets should not be confused with fields, as fields represent the input validation logic, whereas widgets represent the HTML rendering of the fields.
We can customize these widgets right inside of the form. In this lesson, we will discuss some of these widgets to get a basic idea of how they work. Let’s discuss them one by one and learn about their syntax.
Textarea
widget
The following will provide us with a textarea
widget:
text = forms.CharField(min_length=7,widget=forms.Textarea)
In the above example, widget
is the keyword used to put any kind of widget we want.
NOTE: The validation is still in there, but we can change the widget that is displayed.
Select
widget
This widget allows us to select an option from different choices. For this to work, we first need to make those different choices. So, we can do the following:
INTS_CHOICES= [tuple([x,x]) for x in range(0,100)]
Now, let’s use this array of tuples for our IntegerField
:
integer = forms.IntegerField(initial=10,widget=forms.Select(choices=INTS_CHOICES))
In the above example, Select
is the name of the widget and choices
is the parameter used to pass in different choices.
RadioSelect
widget
This widget allows us to select options in terms of radio buttons. Let’s make another array of tuples for this one:
RADIO_CHOICES = [
('signin','Sign In'),
('signup','Sign Up'),
('forgotpassword','Forgot Password'),
]
Let’s make a new field and use the RadioSelect
widget in it.
radio_choices = forms.CharField(min_length=7,widget=forms.RadioSelect(choices=RADIO_CHOICES))
As you can see, the syntax is similar to the previous widget.
CheckboxSelectMultiple
widget
This widget is used to check options from different checkboxes. We will use the following tuple:
CHECKBOX_CHOICES = [
('terms','Agree to terms and conditions'),
('privacy','Agree to privacy policy'),
]
Now, we will create the field and add choices.
checkbox_choices = forms.CharField(min_length=7,widget=forms.CheckboxSelectMultiple(choices=CHECKBOX_CHOICES))
SelectDateWidget
widget
This widget allows us to select a particular date. It makes it very easy for us to set a specific date or time for a particular thing. By default, it only comes up with a few years, but we can give the widget our own range of years. Let’s make a list for it:
YEARS= [x for x in range(1980,2031)]
Now we define another field for the widget, and then use it like this:
date_field= forms.DateField(initial="2020-20-5",widget=forms.SelectDateWidget(years=YEARS))
In the above example, we are also setting up an initial value, where years
is the keyword used to put our list of YEARS
into it.
Get hands-on with 1400+ tech skills courses.