Fields Types in Forms
Besides the CharField
and IntegerField
classes seen in the previous section, you will probably make use of the following field types.
Boolean
Implemented by the django.forms.BooleanField
class. By default the HTML code generates a checkbox. The value received in form.cleaned_data
is a bool
object.
Example:
class CourseForm(forms.Form):
name = forms.CharField(label="Name", max_length=128)
enrolled_students = forms.IntegerField(label="Students")
companies_only = forms.BooleanField(label="Companies only?", required=False)
Note that required=False
is necessary to allow the field to be empty, in which case the value of the field will be False
. This definition renders the following form:
Options list
Implemented by the django.forms.ChoiceField
class. By default the generated HTML code is a select
tag. Each of the options in this list is represented by a tuple: the first element indicates the value that the form will receive for each selected element, while the second is the text that will be shown to the user.
Example:
class CourseForm(forms.Form):
name = forms.CharField(label="Name", max_length=128)
enrolled_students = forms.IntegerField(label="Students")
TIMES_OF_DAY = (
(1, "Morning"),
(2, "Afternoon"),
(3, "Evening")
)
time = forms.ChoiceField(label="Time", choices=TIMES_OF_DAY)
Renders the following form:
If the user selects "Morning", form.cleaned_data["time"]
will be 1
, since it is the value defined in the tuple passed to the choices
parameter; if "Afternoon" gets selected, it will be 2
; and so on.
Date
Implemented by the django.forms.DateField
class. By default the generated HTML code is the same as for django.forms.CharField
(a text box). The difference is that this field will validate that the date is entered in the correct format, and the data type of the field value in form.cleaned_data
will be datetime.date
.
Example:
class CourseForm(forms.Form):
name = forms.CharField(label="Name", max_length=128)
enrolled_students = forms.IntegerField(label="Students")
start_date = forms.DateField(
label="Start date",
input_formats=["%d/%m/%Y"]
)
We are stating that that the input format must be %d/%m/%Y
, that is, dd/mm/yyyy
. You can find the possible formats in the datetime
standard module documentation.
With the following addition you make browsers that support HTML5 display a calendar to select the date:
start_date = forms.DateField(
label="Start date",
widget=forms.DateInput(attrs={"type": "date"})
)
Note that in this case we removed the input format specification, since the format established by the HTML5 standard will be used. For a full explanation, see Date Field With Calendar Widget in Django Forms.
And this is the result:
You might also want to take a look at the full list of fields provided by Django.