URLInput Django form fields

Listen as audio
URLInput Django form fields

Hello Techies,

In this blog, we will check different URLInput Django form fields(URLField) 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 URLInput Django form fields

URLField

The default widget for this input is the URLInput. Uses an URLValidator to verify that a given URL is a valid URL or not. Empty value is an empty string(”). It normalizes to a String.

There are two optional arguments for validation, max_length, and min_length. If provided, this argument ensures that the string has a maximum or minimum given length is the same as CharField.

Syntax: URLField(**kwargs)

Example:

from django import forms

class URLInputForm(forms.Form):
    url= forms.URLField(label='Enter URL', label_suffix = " : ",
                                  required = True,  disabled = False,
                                  widget=forms.URLInput(attrs={'class': 'form-control'}),
                                  help_text = "Please provide a valid URL.",
                                  error_messages = {'required':"Please provide valid URL."})

Let’s run the server and check the result.

Rendered HTML

URLInput Django form fields(URLField)

Rendered HTML With Validation

URLInput Django form fields(URLField)

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.
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. url = forms.URLField(widget=forms.URLInput(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 URLInput Django form fields. For more details, you can check out the official site.

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

https://github.com/pranalikambli/django_form_fields

thank you

Leave a Comment