TextInput Django form fields

TextInput Django form fields

Hello Techies,

In this blog, we will check different TextInput Django Form fields (CharField, SlugField, DurationField,GenericIPAddressField, RegexField, UUIDField, ComboField) 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 TextInput Django Form fields

CharField

This is the most used field in forms. The default widget of CharField is TextInput. Let’s check which parameters and validation this field provides on form submission. It Normalizes to a string.

Syntax: CharField(**kwargs)

Example:

from django import forms

class FieldForm(forms.Form):
    name = forms.CharField(label='Enter Name', label_suffix=" : ", min_length=5, max_length=50,
                           required=False,
                           widget=forms.TextInput(attrs={'class': 'form-control'}),
                           help_text="help_text: Please enter the name.",
                           error_messages={'required': "Please Enter your Name"}, disabled=False, strip=True)

Let’s run the server and check the result.

Rendered HTML

django form fields
TextInput Django form fields (CharField)

Rendered HTML With Validation

rendered django form fields TextInput
TextInput Django form fields (CharField)

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.
min_lengthEnsures minimum label length.
max_lengthEnsures maximum label length.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetThe default widget for this field is TextInput. Widget 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.
For eg. name = forms.CharField(widget=forms.TextInput(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.
stripThis field is set to true by default. This field is used to remove leading and trailing white space.

SlugField

For slug inputs like a specific URL or similar, a slug field in the Django form is a slug field. The default widget of SlugField is TextInput.

For validation, it uses validate_slug  or validate_unicode_slug to verify that a given value contains only letters, numbers, underscores, and hyphens.

A SlugField is used to store and generate valid URLs for dynamically generated web pages.

Syntax: SlugField(**kwargs)

Example:

from django import forms


class FieldForm(forms.Form):

    slug = forms.SlugField(label='Enter slug', label_suffix=" : ", required=False,
                           widget=forms.TextInput(attrs={'class': 'form-control'}), help_text="Please enter slug",
                           error_messages={'required': "Please Enter slug"}, disabled=False)

Let’s run the server and check the result.

Rendered HTML

Django form field slugfield
TextInput Django form fields (SlugField)

Rendered HTML With Validation

Django form field slugfield
TextInput Django form fields (SlugField)

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.
allow_unicode Boolean suggests a field to accept Unicode characters in addition to ASCII characters. Defaults to False.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetThe default widget for this field is TextInput. Widget 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.
For eg. name = forms.SlugField(widget=forms.TextInput(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.

DurationField

The default widget of DurationField is TextInput. It normalizes to a Python timedelta. This verifies that the given value is a string that can be converted to a timedelta. Must be a value between datetime.timedelta.min and datetime.timedelta.max.

Syntax: DurationField(**kwargs)

Example:

from django import forms

class FieldForm(forms.Form):
        post_update = forms.DurationField(label='Enter post update duration', label_suffix=" : ",
                                      required=False, widget=forms.TextInput(attrs={'class': 'form-control'}),
                                      help_text="Please enter post update duration format should be(45:15:10)",
                                      error_messages={'required': "Please enter post update duration"}, disabled=False)

Let’s run the server and check the result.

Rendered HTML

Django form field durationfield
TextInput Django form fields (DurationField)

Rendered HTML With Validation

Django form field durationfield
TextInput Django form fields (DurationField)

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.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetThe default widget for this field is TextInput. Widget 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.
For eg. post_update = forms.DurationField (widget= forms.TextInput (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.

GenericIPAddressField

The default widget for this input is the TextInput. This field contains either the IPV4 or IPV6 address. The given value verifies that it is a valid IP address. It normalizes to a string.

This field takes two optional arguments protocol and unpack_ipv4:

Syntax: GenericIPAddressField(**kwargs)

Example:

from django import forms

class FieldForm(forms.Form):
    loopback = forms.GenericIPAddressField(label='Enter Loopback IP Address', label_suffix=" - ",
                                           required=True, widget=forms.TextInput(attrs={'class': 'form-control'}),
                                           help_text="Please enter Loopback IP Address format should be(100.10.0.1)",
                                           protocol='IPv4',  unpack_ipv4=False, disabled=False,
                                           error_messages={'required': "Please enter Loopback IP Address"})

Let’s run the server and check the result.

Rendered HTML

Django form field genericipadress field
TextInput Django form fields (GenericIPAddressField)

Rendered HTML With Validation

Django form field genericipadress field
TextInput Django form fields (GenericIPAddressField)

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.
protocolLimits valid input to the specified protocol. Accepted values are both (default), IPv4, or IPv6. The matching case is insensitive.
unpack_ipv4Unpacked IPv4 mapped addresses such as ::ffff:192.0.2.1. If this option is enabled, the address will be unpacked on 192.0.2.1. By default it is disabled. Can only be used when the protocol is set to ‘both’.
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. name = forms.GenericIPAddressField(widget=forms.TextInput(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.

RegexField

The default widget for this input is the TextInput. Uses RegexValidator to verify that a given value corresponds to a specific regular expression. It normalizes to a string. It takes regex as a required argument.

Syntax: RegexField(**kwargs)

Example:

from django import forms

class TextInfo(forms.Form):
    regex = forms.RegexField(label='Enter Regex', label_suffix=" : ", min_length=5, max_length=10,
                             regex=r'^[a-zA-Z0-9]+$',
                             required=True, widget=forms.TextInput(attrs={'class': 'form-control'}),
                             help_text="Please enter regex format should be[a-z, A-Z, 0-9]", disabled=False,
                             error_messages={'required': "Please enter regex"})

Let’s run the server and check the result.

Rendered HTML

Django form field regex field
TextInput Django form fields (RegexField)

Rendered HTML with validation

Django form field regex field
TextInput Django form fields (RegexField)

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.
regexThe regular expression is specified as either a string or a compile regular expression object.
min_lengthEnsures minimum label length.
max_lengthEnsures maximum label length.
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. name = forms.RegexField(widget=forms.TextInput(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.
stripThis field is set to False by default. If enabled, stripping will be applied before regex validation.

UUIDField

The default widget for this input is the TextInput. This field will accept any string format accepted by the UUID constructor as a hex argument. It Normalizes to a UUID object.

Syntax: UUIDField(**kwargs)

Example:

from django import forms

class TextInfo(forms.Form):
    uuid = forms.UUIDField(label='Enter uuid', label_suffix=" : ", required=True,  disabled=False, 
                           widget=forms.TextInput(attrs={'class': 'form-control'}), 
                           help_text="Please enter uuid format should be[a-z, A-Z, 0-9]", 
                           error_messages={'required': "Please enter uuid"})

Let’s run the server and check the result.

Rendered HTML

Django form fields uuid field
TextInput Django form fields (UUIDField)

Rendered HTML with validation

Django form fields uuid field
TextInput Django form fields (UUIDField)

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.
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. name = forms.UUIDField(widget=forms.TextInput(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.

ComboField

The default widget for this input is the TextInput. Combofield validates the values ​​given against each field specified as the argument. It Normalizes to a string.

Takes an additional required argument:

fields: List of fields used to validate field values ​​(in the order they are provided).

Syntax: ComboField(**kwargs)

Example:

from django import forms

from django.forms import CharField, EmailField

class TextInfo(forms.Form):
    combo_field = forms.ComboField(label='Enter Email Id', label_suffix=" : ", required=True,  disabled=False,
                                   fields=[CharField(max_length=20), EmailField()],
                                   widget=forms.TextInput(attrs={'class': 'form-control'}),
                                   help_text="Pass valid email id with max length 20",
                                   error_messages={'required': "Please Email Id"})

Let’s run the server and check the result.

Rendered HTML

Django form fields combo field
TextInput Django form fields (ComboField)

Rendered HTML with validation

Django form fields combo field
TextInput Django form fields (ComboField)

Example:

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.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
fieldsList of fields used to validate field values ​​(in the order they are provided).
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. combo_field = forms.ComboField(widget=forms.TextInput(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 TextInput Django form fields. For more details, you can check out the official site.

Find the source code for TextInput Django form fields on Github.

Leave a Comment