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
| Attribute | Type | Description |
|---|---|---|
| widget | [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = URLInput | The default form widget class used to render this field in HTML, which defaults to URLInput. |
| default_error_messages | dict = {"invalid": "Enter a valid URL."} | A dictionary containing the default error message for the 'invalid' key used when URL validation fails. |
| default_validators | list = [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
| Name | Type | Description |
|---|---|---|
| assume_scheme | string = None | The scheme to prepend to URLs that do not have one (e.g., 'https'). Defaults to 'https' if not provided. |
| **kwargs | dict | Additional 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
| Name | Type | Description |
|---|---|---|
| value | string | The raw input string representing a URL or partial URL to be normalized. |
Returns
| Type | Description |
|---|---|
string | The normalized URL string with an explicit protocol scheme (e.g., 'https://') prepended if necessary. |