Date and Time Django Form Fields

Date and Time Django Form Fields

Hello Techies,

In this blog, we will check different Date and Time Django form fields(DateField, DateTimeField, TimeField, SplitDateTimeField) with examples.

All form fields themselves are classes; They manage form data and perform validation when the form is submitted.

Syntax : FieldType(**kwargs) 

Different types of Date and Time Django Form Fields

DateField

The default widget for this input is the DateInput. The empty value is None. It Normalizes to a Python datetime.date object. This validates that the given value is either a string formatted in a specific date format, datetime.date, or a datetime.datetime.

It takes one optional argument which is input_formats.

Syntax: DateField(**kwargs)

Example:

from django import forms

date_field = forms.DateField(label='Date Field', label_suffix=" : ",
                             required=True, disabled=False, input_formats=["%d-%m-%Y"],
                             widget=forms.DateInput(attrs={'class': 'form-control'}),
                             error_messages={'required': "This field is required."})

Let’s run the server and check the result.

Rendered HTML

Date and Time Django Form Fields (DateField)

Rendered HTML with validation

Date and Time Django Form Fields (DateField)

Explanation:

Field OptionsDescription
labelThis argument allows you to specify a “Field Caption” label for this area.
label_suffixThis argument allows you to insert some text after the field’s label.
input_formatsA list of formats is used to try to convert a string into a valid datetime.date object.
requiredBy default, each field assumes a value as required, so you need to set the required field as a false to make it not necessary.
widgetThis Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or any other CSS class to decorate your form field. Also, you can pass the choice list.
For eg. date_field= forms.DateField(widget=forms.DateInput(attrs={‘class’: ‘form-control’}))
error_messagesThis argument allows you to overwrite the default error message that the field will raise. Pass the error message to overwrite in the dictionary with the matching key.
disabledDisabled Boolean Argument, if set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

DateTimeField

The default widget for this input is the DateTimeInput. The empty value is None. It Normalizes to a Python datetime.datetime object. This validates that the given value is either a string formatted in a particular datetime format, datetime.datetime, or a datetime.date.

It takes one optional argument which is input_formats.

The field is always accept strings in the ISO 8601 formatted dates or similar recognized by the parse_ditatime(). Here are some examples:

* '2020-10-25 14:30:59' 
* '2020-10-25T14:30:59' 
* '2020-10-25 14:30' 
* '2020-10-25T14:30' 
* '2020-10-25T14:30Z' 
* '2020-10-25T14:30+02:00' 
* '2020-10-25'

Syntax: DateTimeField(**kwargs)

Example:

from django import forms

class DateTimeForm(forms.Form):
    date_time_field = forms.DateTimeField(label='Date Time Field',
                                          label_suffix=" : ", required=True, disabled=False,
                                          input_formats=["%d-%m-%Y %H:%M"],
                                          widget=forms.DateTimeInput(attrs={'class': 'form-control'}),
                                          error_messages={'required': "This field is required."})

Let’s run the server and check the result.

Rendered HTML

Date and Time Django Form Fields (DateTimeField)

Rendered HTML with validation

Date and Time Django Form Fields (DateTimeField)

Explanation:

Field OptionsDescription
labelThis argument allows you to specify a “Field Caption” label for this area.
label_suffixThis argument allows you to insert some text after the field’s label.
input_formatsIn addition to the ISO 8601 format, a list of formats used to try to convert a string to a valid datetime.datetime object.
requiredBy default, each field assumes a value as required, so you need to set the required as a false to make it not necessary.
widgetThis Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or any other CSS class to decorate your form field. Also, you can pass the choice list.
For eg. typed_multiple_choice_field= forms.TypedMultipleChoiceField(widget=forms.SelectMultiple(attrs={‘class’: ‘form-control’}))
error_messagesThis argument allows you to overwrite the default error message that the field will raise. Pass the error message to overwrite in the dictionary with the matching key.
disabledDisabled Boolean Argument, if set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

TimeField

The default widget for this input is the TimeInput. The empty value is None. It Normalizes to a Python datetime.time object. This validates that the given value is either a string formatted in a particular time format or a datetime.time.

It takes one optional argument which is input_formats.

Syntax: TimeField(**kwargs)

Example:

from django import forms

time_field = forms.TimeField(label='Time Field', label_suffix=" : ",
                             required=True, disabled=False, input_formats=["%H:%M:%S"],
                             widget=forms.TimeInput(attrs={'class': 'form-control'}),
                             error_messages={'required': "This field is required."})

Let’s run the server and check the result.

Rendered HTML

Date and Time Django Form Fields (TimeField)

Rendered HTML with validation

Date and Time Django Form Fields (TimeField)

Explanation:

Field OptionsDescription
labelThis argument allows you to specify a “Field Caption” label for this area.
label_suffixThis argument allows you to insert some text after the field’s label.
input_formatsA list of formats is used to try to convert a string into a valid datetime.time object.
requiredBy default, each field assumes a value as required, so you need to set the required field as a false to make it not necessary.
widgetThis Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or any other CSS class to decorate your form field. Also, you can pass the choice list.
For eg. time_field= forms.TimeField(widget=forms.TimeInput(attrs={‘class’: ‘form-control’}))
error_messagesThis argument allows you to overwrite the default error message that the field will raise. Pass the error message to overwrite in the dictionary with the matching key.
disabledDisabled Boolean Argument, if set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

SplitDateTimeField

The default widget for this input is the SplitDateTimeWidget. The empty value is None. It Normalizes to a Python datetime.datetime object. This validates that the given value is a string formatted in a particular datetime format or a datetime.datetime.

It takes two optional arguments which are input_date_formats and input_time_formats.

Syntax: SplitDateTimeField(**kwargs)

Example:

from django import forms

split_date_time_field = forms.SplitDateTimeField(label='Split Date Time Field', 
                        label_suffix=" : ", required=True, 
                        disabled=False, input_date_formats=["%d-%m-%Y"],
                        input_time_formats=["%H:%M:%S"],
                        widget=forms.SplitDateTimeWidget(attrs={'class': 'form-control'}), 
                        error_messages={'required': "This field is required."})

Let’s run the server and check the result.

Rendered HTML

Date and Time Django Form Fields (SplitDateTimeField)

Rendered HTML with validation

Date and Time Django Form Fields (SplitDateTimeField)

Explanation:

Field OptionsDescription
labelThis argument allows you to specify a “Field Caption” label for this area.
label_suffixThis argument allows you to insert some text after the field’s label.
input_date_formatsList of formats used to attempt to convert a string to a valid datetime.date object.
input_time_formatsList of formats used to attempt to convert a string to a valid datetime.time object.
requiredBy default, each field assumes a value as required, so you need to set the required field as a false to make it not necessary.
widgetThis Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or any other CSS class to decorate your form field. Also, you can pass the choice list.
For eg. split_date_time_field = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget(attrs={‘class’: ‘form-control’}))
error_messagesThis argument allows you to overwrite the default error message that the field will raise. Pass the error message to overwrite in the dictionary with the matching key.
disabledDisabled Boolean Argument, if set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

See the official site for more information.

I hope you understand what I explained about Date and Time Django Form Fields in this blog. If you still have any doubts about the Date and Time Django Form Fields, leave a comment below.

Find the source code for Date and Time Django Form Fields Github link at:

https://github.com/pranalikambli/django_form_fields

Leave a Comment