Fields API

Field

class Field([kwargs])

An object that is responsible for doing validation and normalisation, or “cleaning” – for example: an EmailField() makes sure its data is a valid e-mail address – and makes sure that acceptable “blank” values all have the same representation.

Arguments:
  • kwargs (Object) – field options, which are as follows:
  • kwargs.required (Boolean) – determines if the field is required – defaults to true.
  • kwargs.widget (Widget) – overrides the widget used to render the field – if not provided, the field’s default will be used.
  • kwargs.label (String) – the label to be displayed for the field - if not provided, will be generated from the field’s name.
  • kwargs.initial – an initial value for the field to be used if none is specified by the field’s form.
  • kwargs.helpText (String) – help text for the field.
  • kwargs.errorMessages (Object) – custom error messages for the field, by error code.
  • kwargs.showHiddenInitial (Boolean) – specifies if it is necessary to render a hidden widget with initial value after the widget.
  • kwargs.validators (Array.<Function>) – list of addtional validators to use - a validator is a function which takes a single value and throws a ValidationError if it’s invalid.
  • kwargs.cssClass (String) – space-separated CSS classes to be applied to the field’s container when default rendering fuctions are used.
  • kwargs.custom

    this argument is provided to pass any custom metadata you require on the field, e.g. extra per-field options for a custom layout you’ve implemented. Newforms will set anything you pass for this argument in a custom instance property on the field.

    New in version 0.5.

  • kwargs.validation

    Configures validation when the user interacts with this field’s widget in the browser.

    This can be used to configure validation for only specific fields, or to override any form-wide validation that’s been configured.

    Takes the same arguments as Form’s validation configuration

    If validation configuration is given, the Form containing the Field must be configured with an onChange callback, or an Error will be thrown.

    New in version 0.6.

  • controlled (Boolean) –

    Configures whether or not the field will render a controlled component

    This can be used to configure creation of controlled components for only specific fields, or to override any form-wide controlled that’s been configured.

    New in version 0.6.

Prototype Functions

Field#prepareValue(value)

Hook for any pre-preparation required before a value can be used.

Field#toJavaScript(value)

Hook for coercing a value to an appropriate JavaScript object.

Field#isEmptyValue(value)

Checks for the given value being === one of the configured empty values for this field, plus any additional checks required due to JavaScript’s lack of a generic object equality checking mechanism.

This function will use the field’s emptyValues property for the === check – this defaults to [null, undefined, ''] via Field.prototype.

If the field has an emptyValueArray property which is true, the value’s type and length will be checked to see if it’s an empty Array – this defaults to true via Field.prototype.

Field#validate(value)

Hook for validating a value.

Field#clean(value)

Validates the given value and returns its “cleaned” value as an appropriate JavaScript object.

Raises ValidationError() for any errors.

class CharField([kwargs])

Validates that its input is a valid string.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.maxLength (Number) – a maximum valid length for the input string.
  • kwargs.minLength (Number) – a minimum valid length for the input string.

Numeric fields

class IntegerField([kwargs])

Validates that its input is a valid integer.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.maxValue (Number) – a maximum valid value for the input.
  • kwargs.minValue (Number) – a minimum valid value for the input.
class FloatField([kwargs])

Validates that its input is a valid float.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.maxValue (Number) – a maximum valid value for the input.
  • kwargs.minValue (Number) – a minimum valid value for the input.
class DecimalField([kwargs])

Validates that its input is a decimal number.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.maxValue (Number) – a maximum value for the input.
  • kwargs.minValue (Number) – a minimum value for the input.
  • kwargs.maxDigits (Number) – the maximum number of digits the input may contain.
  • kwargs.decimalPlaces (Number) – the maximum number of decimal places the input may contain.

Date/Time fields

class DateField([kwargs])

Validates that its input is a date.

Normalises to a Date with its time fields set to zero.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.inputFormats (Array.<String>) – a list of time.strptime() format strings which are considered valid.
class TimeField([kwargs])

Validates that its input is a time.

Normalises to a Date with its date fields set to 1900-01-01.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.inputFormats (Array.<String>) – a list of time.strptime() format strings which are considered valid.
class DateTimeField([kwargs])

Validates that its input is a date/time.

Normalises to a Date.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.inputFormats (Array.<String>) – a list of time.strptime() format strings which are considered valid.

Format fields

class RegexField(regex[, kwargs])

Validates that its input matches a given regular expression.

Arguments:
  • regex (RegExp or String) – a regular expression to validate input against. If a string is given, it will be compiled to a RegExp.
  • kwargs (Object) – field options, as in CharField()
class EmailField([kwargs])

Validates that its input appears to be a valid e-mail address.

Arguments:
class IPAddressField([kwargs])

Validates that its input is a valid IPv4 address.

Deprecated since version 0.5: use GenericIPAddressField() instead.

class GenericIPAddressField([kwargs])

Validates that its input is a valid IPv4 or IPv6 address.

Arguments:
  • kwargs (Object) – field options additional to those specified in CharField()
  • kwargs.protocol (String) –

    determines which protocols are accepted as input. One of:

    • 'both'
    • 'ipv4'
    • 'ipv6'

    Defaults to 'both'.

  • kwargs.unpackIPv4 (Boolean) – Determines if an IPv4 address that was mapped in a compressed IPv6 address will be unpacked. Defaults to false and can only be set to true if kwargs.protocol is 'both'.
class SlugField([kwargs])

Validates that its input is a valid slug - i.e. that it contains only letters, numbers, underscores, and hyphens.

Arguments:

File fields

class FileField([kwargs])

Validates that its input is a valid uploaded file – the behaviour of this field varies depending on the environmnet newforms is running in:

On the client

Validates that a file has been selected if the field is required.

On the server

Validates uploaded file data from form.files.

The contents of form.files are expected to have a name property corresponding to the uploaded file’s name and a size property corresponding to it size.

You will need write a wrapper to provide this information depending on how you’re handling file uploads.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field()
  • kwargs.maxLength (Number) – maximum length of the uploaded file anme.
  • kwargs.allowEmptyFile (Boolean) – if true, empty files will be allowed – defaults to false.
class ImageField([kwargs])

Validates that its input is a valid uploaded image – the behaviour of this field varies depending on the environmnet newforms is running in:

On the client

Validates that a file has been selected if the field is required.

On the server

Note

As of newform 0.5, server-side image validation has not been implemented yet – ImageField performs the same validation as FileField.

Adds an accept="image/*" attribute to its <input type="file"> widget.

class URLField([kwargs])

Validates that its input appears to be a valid URL.

Arguments:

Boolean fields

class BooleanField([kwargs])

Normalises its input to a boolean primitive.

Arguments:
  • kwargs (Object) – field options, as in Field()
class NullBooleanField([kwargs])

A field whose valid values are null, true and false.

Invalid values are cleaned to null.

Arguments:
  • kwargs (Object) – field options, as in Field()

Choice fields

class ChoiceField([kwargs])

Validates that its input is one of a valid list of choices.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field():
  • kwargs.choices (Array) –

    a list of choices - each choice should be specified as a list containing two items; the first item is a value which should be validated against, the second item is a display value for that choice, for example:

    {choices: [[1, 'One'], [2, 'Two']]}
    

    Defaults to [].

Prototype Functions

ChoiceField#choices()

Returns the current list of choices.

ChoiceField#setChoices(choices)

Updates the list of choices on this field and on its configured widget.

class TypedChoiceField([kwargs])

A ChoiceField which returns a value coerced by some provided function.

Arguments:
  • kwargs (Object) – field options additional to those specified in ChoiceField():
  • kwargs.coerce (Function(String)) – a function which takes the string value output from ChoiceField‘s clean method and coerces it to another type – defaults to a function which returns the given value unaltered.
  • kwargs.emptyValue – the value which should be returned if the selected value can be validly empty – defaults to ''.
class MultipleChoiceField([kwargs])

Validates that its input is one or more of a valid list of choices.

class TypedMultipleChoiceField([kwargs])

A MultipleChoiceField} which returns values coerced by some provided function.

Arguments:
  • kwargs (Object) – field options additional to those specified in MultipleChoiceField.
  • kwargs.coerce

    (Function)

    function which takes the String values output by MultipleChoiceField’s toJavaScript method and coerces it to another type – defaults to a function which returns the given value unaltered.

  • kwargs.emptyValue

    (Object)

    the value which should be returned if the selected value can be validly empty – defaults to ''.

class FilePathField([kwargs])

Note

As of newform 0.5, server-side logic for FilePathField hasn’t been implemented yet.

As such, this field isn’t much use yet and the API documentation below is speculative.

Allows choosing from files inside a certain directory.

Arguments:
  • path (String) – The absolute path to the directory whose contents you want listed - this directory must exist.
  • kwargs (Object) – field options additional to those supplied in ChoiceField().
  • kwargs.match (String or RegExp) – a regular expression pattern – if provided, only files with names matching this expression will be allowed as choices. If a string is given, it will be compiled to a RegExp.
  • kwargs.recursive (Boolean) – if true, the directory will be descended into recursively and all allowed descendants will be listed as choices – defaults to false.
  • kwargs.allowFiles (Boolean) – if true, files will be listed as choices. Defaults to true.
  • kwargs.allowFolders (Boolean) – if true, folders will be listed as choices. Defaults to false.

Slightly complex fields

class ComboField([kwargs])

A Field whose clean() method calls multiple Field clean() methods.

Arguments:
  • kwargs (Object) – field options additional to those specified in Field().
  • kwargs.fields (Array.<Field>) – fields which will be used to perform cleaning, in the order they’re given.
class MultiValueField([kwargs])

A Field that aggregates the logic of multiple Fields.

Its clean() method takes a “decompressed” list of values, which are then cleaned into a single value according to this.fields. Each value in this list is cleaned by the corresponding field – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is “compressed” into a single value.

Subclasses should not have to implement clean(). Instead, they must implement compress(), which takes a list of valid values and returns a “compressed” version of those values – a single value.

You’ll probably want to use this with MultiWidget().

Arguments:
  • kwargs (Object) – field options
  • kwargs.fields (Array.<Field>) – a list of fields to be used to clean a “decompressed” list of values.
  • kwargs.requireAllFields (Boolean) – when set to false, allows optional subfields. The required attribute for each individual field will be respected, and a new 'incomplete' validation error will be raised when any required fields are empty. Defaults to true.
class SplitDateTimeField([kwargs])

A MultiValueField consisting of a DateField() and a TimeField().