Skip to main content

URLField

This class represents a form field for entering and validating URLs, extending the functionality of a standard character field. It automatically strips whitespace, validates input against URL patterns, and ensures a protocol scheme is present by prepending a default scheme if one is missing. The field uses a specialized widget and provides customizable error messages for invalid URL formats.

Attributes

AttributeTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = URLInputThe default form widget class used to render this field in HTML, which defaults to URLInput.
default_error_messagesdict = {"invalid": "Enter a valid URL."}A dictionary containing the default error message for the 'invalid' key used when URL validation fails.
default_validatorslist = [validators.URLValidator()]A list of validation functions applied to the field value, initialized with a URLValidator instance.

Constructor

Signature

def URLField(
assume_scheme: string = None,
**kwargs: dict
) - > null

Parameters

NameTypeDescription
assume_schemestring = NoneThe scheme to prepend to URLs that do not have one (e.g., 'https'). Defaults to 'https' if not provided.
**kwargsdictAdditional keyword arguments passed to the parent CharField constructor.

Methods


to_python()

@classmethod
def to_python(
value: string
) - > string

Normalizes the input value into a valid URL string by prepending a default protocol scheme if one is missing. This ensures that relative or schemeless URLs are converted into absolute URLs suitable for validation and storage.

Parameters

NameTypeDescription
valuestringThe raw input string representing a URL or partial URL to be normalized.

Returns

TypeDescription
stringThe normalized URL string with an explicit protocol scheme (e.g., 'https://') prepended if necessary.