Select Django Form Fields

Listen as audio
Select Django Form Fields

Hello Techies,

In this blog, we will check different Select Django form fields (ChoiceField, TypedChoiceField, FilePathField) with examples.

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

Syntax : FieldType(**kwargs) 

Different types of Select Django form fields

ChoiceField

The default widget for this input is the Select. It does not validate anything so it never increases the ValidationError. Empty value is an empty string(”). It normalizes to a String.

It is used for the implementation of the city, state, country, color, etc. as the information is already defined and the user has to choose one. It is used to input text from the user.

This takes an additional required argument which is choice.

Syntax: ChoiceField(**kwargs)

Example:

from django import forms

city = (
    ("mumbai", "Mumbai"),
    ("pune", "Pune"),
    ("delhi", "Delhi"),
    ("surat", "Surat"),
    ("chennai", "Chennai"),
)

class SelectInputForm(forms.Form):
    choice_field= forms.ChoiceField(label='City', label_suffix = " : ",
                                  required = True,  disabled = False,
                                  choices = city, widget=forms.Select(attrs={'class': 'form-control'}),
                                  error_messages = {'required':"This field is required."})

Let’s run the server and check the result.

Rendered HTML

Select Django Form Fields(ChoiceField)

Explanation:

Field OptionsDescription
labelThe label argument allows you to specify a “Field Caption” label for this area.
label_suffixThe label_suffix argument allows you to insert some text after the field’s label.
choiceEither an iterable 2-tuples to be used as an option for this field or callable such as an iterable object.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetWidget Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or other CSS class for this field to decorate your field. Also, you can pass the choice list.
For eg. choice_field= forms.ChoiceField(widget=forms.Select(attrs={‘class’: ‘form-control’}))
error_messageserror_messages argument allows you to overwrite the default error message that the field will raise. Pass the error message you want to overwrite in the dictionary with matching keys.
disabledDisabled Boolean Argument, when set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

TypedChoiceField

Similar to ChoiceField, except TypedChoiceField takes two extra arguments, coerce and empty_value.

The default widget for this input is the Select. Empty value is whatever you enter as a blank_value. It Normalizes to a value of the type provided by the coerce argument.

It is used for the implementation of the city, state, country, color, etc. as the information is already defined and the user has to choose one. It is used to input text from the user.

Syntax: TypedChoiceField(**kwargs)

Example:

from django import forms

class SelectInputForm(forms.Form):
    typed_choice_field = forms.TypedChoiceField(label='City', label_suffix=" : ",
                                     required=True, disabled=False,
                                     choices=city, coerce = str, empty_value='',
                                                widget=forms.Select(attrs={'class': 'form-control'}),
                                     error_messages={'required': "This field is required."})

Let’s run the server and check the result.

Rendered HTML

Select Django Form Fields(TypedChoiceField)

Explanation:

Field OptionsDescription
labelThe label argument allows you to specify a “Field Caption” label for this area.
label_suffixThe label_suffix argument allows you to insert some text after the field’s label.
choiceEither an iterable 2-tuples to be used as an option for this field or callable such as an iterable object.
coerceA function that takes an argument and returns a coerced value. Examples include the built-in str, int, float, bool, and other types.
empty_valueEmpty value is whatever you enter as a blank_value. Defaults to the empty string, also None is another common choice here.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetWidget Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or other CSS class for this field to decorate your field. Also, you can pass the choice list.
For eg. typed_choice_field = forms.TypedChoiceField(widget=forms.Select(attrs={‘class’: ‘form-control’}))
error_messageserror_messages argument allows you to overwrite the default error message that the field will raise. Pass the error message you want to overwrite in the dictionary with matching keys.
disabledDisabled Boolean Argument, when set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

FilePathField

The default widget for this input is the Select. It Validates that the selected choice exists in the list of choices or not. Empty value is an empty string(”). It normalizes to a String.

It takes five additional arguments (path, recursive, match, allow_files, allow_folders); the Only path required.

Syntax: FilePathField(**kwargs)

Example:

from django import forms

class SelectInputForm(forms.Form):
    file_path_file = forms.FilePathField(label='File Path', label_suffix = " : ",
                                  required = True,  disabled = False, path = "django_form_fields/",
                                  recursive=True, allow_files=True, allow_folders=True,
                                  widget=forms.Select(attrs={'class': 'form-control'}),
                                  error_messages = {'required':"This field is required."})

Let’s run the server and check the result.

Rendered HTML

Select Django Form Fields(FilePathField)

Adding the match argument.

from django import forms

class SelectInputForm(forms.Form):
    file_path_file = forms.FilePathField(label='File Path', label_suffix = " : ",
                                  required = True,  disabled = False, path = "django_form_fields/",
                                  recursive=True, allow_files=True, allow_folders=True, match="url.*",
                                  widget=forms.Select(attrs={'class': 'form-control'}),
                                  error_messages = {'required':"This field is required."})

Let’s run the server and check the result.

Rendered HTML

Select Django Form Fields(FilePathField)

Explanation:

Field OptionsDescription
labelThe label argument allows you to specify a “Field Caption” label for this area.
label_suffixThe label_suffix argument allows you to insert some text after the field’s label.
pathThe perfect path to the directory you want to list. This directory must exist.
recursive If incorrect (default) will only be given as direct content selection along the way. If true, the directory will be descended as a recursively and all descendants will be listed as selected.
matchRegular expression pattern; Only files with names that match this expression will be allowed as a selection.
allow_filesOptional. Either true or false. The default is true. Specifies whether to include files in the specified location. Either this or the allow_files must be true.
allow_folders Optional. Either true or false. The default is true. Specifies whether to include folders in the specified location. Either this or the allow_folders must be true.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetWidget Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or other CSS class for this field to decorate your field. Also, you can pass the choice list.
For eg. file_path_file = forms.FilePathField(widget=forms.Select(attrs={‘class’: ‘form-control’}))
error_messageserror_messages argument allows you to overwrite the default error message that the field will raise. Pass the error message you want to overwrite in the dictionary with matching keys.
disabledDisabled Boolean Argument, when set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

I hope you understand all the Select Django form fields. For more details, you can check out the official site.

Find the source code for Select Django form fields Github link at:

https://github.com/pranalikambli/django_form_fields

thank you

Leave a Comment