Field
(**kwargs)¶When you create a Form
class, the most important part is defining the
fields of the form. Each field has custom validation logic, along with a few
other hooks.
Field.
clean
(value)¶Although the primary way you’ll use Field
classes is in Form
classes,
you can also instantiate them and use them directly to get a better idea of
how they work. Each Field
instance has a clean()
method, which takes
a single argument and either raises a
django.core.exceptions.ValidationError
exception or returns the clean
value:
>>> from django import forms
>>> f = forms.EmailField()
>>> f.clean('foo@example.com')
'foo@example.com'
>>> f.clean('invalid email address')
Traceback (most recent call last):
...
ValidationError: ['Enter a valid email address.']
Each Field
class constructor takes at least these arguments. Some
Field
classes take additional, field-specific arguments, but the following
should always be accepted:
required
¶Field.
required
¶By default, each Field
class assumes the value is required, so if you pass
an empty value – either None
or the empty string (""
) – then
clean()
will raise a ValidationError
exception:
>>> from django import forms
>>> f = forms.CharField()
>>> f.clean('foo')
'foo'
>>> f.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(None)
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
>>> f.clean(' ')
' '
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
To specify that a field is not required, pass required=False
to the
Field
constructor:
>>> f = forms.CharField(required=False)
>>> f.clean('foo')
'foo'
>>> f.clean('')
''
>>> f.clean(None)
''
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'
If a Field
has required=False
and you pass clean()
an empty value,
then clean()
will return a normalized empty value rather than raising
ValidationError
. For CharField
, this will return
empty_value
which defaults to an empty string. For other
Field
classes, it might be None
. (This varies from field to field.)
Widgets of required form fields have the required
HTML attribute. Set the
Form.use_required_attribute
attribute to False
to disable it. The
required
attribute isn’t included on forms of formsets because the browser
validation may not be correct when adding and deleting formsets.
label
¶Field.
label
¶The label
argument lets you specify the “human-friendly” label for this
field. This is used when the Field
is displayed in a Form
.
As explained in “Outputting forms as HTML” above, the default label for a
Field
is generated from the field name by converting all underscores to
spaces and upper-casing the first letter. Specify label
if that default
behavior doesn’t result in an adequate label.
Here’s a full example Form
that implements label
for two of its fields.
We’ve specified auto_id=False
to simplify the output:
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(label='Your name')
... url = forms.URLField(label='Your website', required=False)
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Your name:</th><td><input type="text" name="name" required></td></tr>
<tr><th>Your website:</th><td><input type="url" name="url"></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
label_suffix
¶Field.
label_suffix
¶The label_suffix
argument lets you override the form’s
label_suffix
on a per-field basis:
>>> class ContactForm(forms.Form):
... age = forms.IntegerField()
... nationality = forms.CharField()
... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
>>> f = ContactForm(label_suffix='?')
>>> print(f.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
<p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
<p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required></p>
initial
¶Field.
initial
¶The initial
argument lets you specify the initial value to use when
rendering this Field
in an unbound Form
.
To specify dynamic initial data, see the Form.initial
parameter.
The use-case for this is when you want to display an “empty” form in which a field is initialized to a particular value. For example:
>>> from django import forms
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
You may be thinking, why not just pass a dictionary of the initial values as data when displaying the form? Well, if you do that, you’ll trigger validation, and the HTML output will include any validation errors:
>>> class CommentForm(forms.Form):
... name = forms.CharField()
... url = forms.URLField()
... comment = forms.CharField()
>>> default_data = {'name': 'Your name', 'url': 'http://'}
>>> f = CommentForm(default_data, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required></td></tr>
This is why initial
values are only displayed for unbound forms. For bound
forms, the HTML output will use the bound data.
Also note that initial
values are not used as “fallback” data in
validation if a particular field’s value is not given. initial
values are
only intended for initial form display:
>>> class CommentForm(forms.Form):
... name = forms.CharField(initial='Your name')
... url = forms.URLField(initial='http://')
... comment = forms.CharField()
>>> data = {'name': '', 'url': '', 'comment': 'Foo'}
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fall back to using the initial values.
>>> f.errors
{'url': ['This field is required.'], 'name': ['This field is required.']}
Instead of a constant, you can also pass any callable:
>>> import datetime
>>> class DateForm(forms.Form):
... day = forms.DateField(initial=datetime.date.today)
>>> print(DateForm())
<tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required><td></tr>
The callable will be evaluated only when the unbound form is displayed, not when it is defined.
widget
¶Field.
widget
¶The widget
argument lets you specify a Widget
class to use when
rendering this Field
. See Widgets for more information.
help_text
¶Field.
help_text
¶The help_text
argument lets you specify descriptive text for this
Field
. If you provide help_text
, it will be displayed next to the
Field
when the Field
is rendered by one of the convenience Form
methods (e.g., as_ul()
).
Like the model field’s help_text
, this value
isn’t HTML-escaped in automatically-generated forms.
Here’s a full example Form
that implements help_text
for two of its
fields. We’ve specified auto_id=False
to simplify the output:
>>> from django import forms
>>> class HelpTextContactForm(forms.Form):
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
... message = forms.CharField()
... sender = forms.EmailField(help_text='A valid email address, please.')
... cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False)
>>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required><br><span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" required><br>A valid email address, please.</td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
>>> print(f.as_ul()))
<li>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" required></li>
<li>Sender: <input type="email" name="sender" required> A valid email address, please.</li>
<li>Cc myself: <input type="checkbox" name="cc_myself"></li>
>>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></p>
<p>Message: <input type="text" name="message" required></p>
<p>Sender: <input type="email" name="sender" required> A valid email address, please.</p>
<p>Cc myself: <input type="checkbox" name="cc_myself"></p>
error_messages
¶Field.
error_messages
¶The error_messages
argument lets you override the default messages that the
field will raise. Pass in a dictionary with keys matching the error messages you
want to override. For example, here is the default error message:
>>> from django import forms
>>> generic = forms.CharField()
>>> generic.clean('')
Traceback (most recent call last):
...
ValidationError: ['This field is required.']
And here is a custom error message:
>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
...
ValidationError: ['Please enter your name']
In the built-in Field classes section below, each Field
defines the
error message keys it uses.
validators
¶Field.
validators
¶The validators
argument lets you provide a list of validation functions
for this field.
See the validators documentation for more information.
localize
¶Field.
localize
¶The localize
argument enables the localization of form data input, as well
as the rendered output.
See the format localization documentation for more information.
disabled
¶Field.
disabled
¶The disabled
boolean argument, when set to True
, disables a form field
using the disabled
HTML attribute so that it won’t be editable by users.
Even if a user tampers with the field’s value submitted to the server, it will
be ignored in favor of the value from the form’s initial data.
has_changed()
¶Field.
has_changed
()¶The has_changed()
method is used to determine if the field value has changed
from the initial value. Returns True
or False
.
See the Form.has_changed()
documentation for more information.
Field
classes¶Naturally, the forms
library comes with a set of Field
classes that
represent common validation needs. This section documents each built-in field.
For each field, we describe the default widget used if you don’t specify
widget
. We also specify the value returned when you provide an empty value
(see the section on required
above to understand what that means).
BooleanField
¶BooleanField
(**kwargs)¶CheckboxInput
False
True
or False
value.True
(e.g. the check box is checked) if
the field has required=True
.required
تبصره
Since all Field
subclasses have required=True
by default, the
validation condition here is important. If you want to include a boolean
in your form that can be either True
or False
(e.g. a checked or
unchecked checkbox), you must remember to pass in required=False
when
creating the BooleanField
.
CharField
¶CharField
(**kwargs)¶TextInput
empty_value
.MaxLengthValidator
and
MinLengthValidator
if max_length
and
min_length
are provided. Otherwise, all inputs are valid.required
, max_length
, min_length
Has four optional arguments for validation:
max_length
¶min_length
¶If provided, these arguments ensure that the string is at most or at least the given length.
strip
¶If True
(default), the value will be stripped of leading and
trailing whitespace.
empty_value
¶The value to use to represent “empty”. Defaults to an empty string.
ChoiceField
¶ChoiceField
(**kwargs)¶Select
''
(an empty string)required
, invalid_choice
The invalid_choice
error message may contain %(value)s
, which will be
replaced with the selected choice.
Takes one extra argument:
choices
¶Either an iterable of 2-tuples to use as choices for this
field, enumeration choices, or a
callable that returns such an iterable. This argument accepts the same
formats as the choices
argument to a model field. See the
model field reference documentation on choices
for more details. If the argument is a callable, it is evaluated each
time the field’s form is initialized, in addition to during rendering.
Defaults to an empty list.
TypedChoiceField
¶TypedChoiceField
(**kwargs)¶Just like a ChoiceField
, except TypedChoiceField
takes two
extra arguments, coerce
and empty_value
.
Select
empty_value
.coerce
argument.required
, invalid_choice
Takes extra arguments:
coerce
¶A function that takes one argument and returns a coerced value. Examples
include the built-in int
, float
, bool
and other types. Defaults
to an identity function. Note that coercion happens after input
validation, so it is possible to coerce to a value not present in
choices
.
empty_value
¶The value to use to represent “empty.” Defaults to the empty string;
None
is another common choice here. Note that this value will not be
coerced by the function given in the coerce
argument, so choose it
accordingly.
DateField
¶DateField
(**kwargs)¶DateInput
None
datetime.date
object.datetime.date
,
datetime.datetime
or string formatted in a particular date format.required
, invalid
Takes one optional argument:
input_formats
¶A list of formats used to attempt to convert a string to a valid
datetime.date
object.
If no input_formats
argument is provided, the default input formats are
taken from DATE_INPUT_FORMATS
if USE_L10N
is
False
, or from the active locale format DATE_INPUT_FORMATS
key if
localization is enabled. See also format localization.
DateTimeField
¶DateTimeField
(**kwargs)¶DateTimeInput
None
datetime.datetime
object.datetime.datetime
,
datetime.date
or string formatted in a particular datetime format.required
, invalid
Takes one optional argument:
input_formats
¶A list of formats used to attempt to convert a string to a valid
datetime.datetime
object, in addition to ISO 8601 formats.
The field always accepts strings in ISO 8601 formatted dates or similar
recognized by parse_datetime()
. Some examples
are:
* '2006-10-25 14:30:59'
* '2006-10-25T14:30:59'
* '2006-10-25 14:30'
* '2006-10-25T14:30'
* '2006-10-25T14:30Z'
* '2006-10-25T14:30+02:00'
* '2006-10-25'
If no input_formats
argument is provided, the default input formats are
taken from DATETIME_INPUT_FORMATS
and
DATE_INPUT_FORMATS
if USE_L10N
is False
, or from
the active locale format DATETIME_INPUT_FORMATS
and
DATE_INPUT_FORMATS
keys if localization is enabled. See also
format localization.
Support for ISO 8601 date string parsing (including optional timezone) was added.
The fallback on DATE_INPUT_FORMATS
in the default input_formats
was added.
DecimalField
¶DecimalField
(**kwargs)¶NumberInput
when Field.localize
is
False
, else TextInput
.None
decimal
.MaxValueValidator
and
MinValueValidator
if max_value
and
min_value
are provided. Leading and trailing whitespace is ignored.required
, invalid
, max_value
,
min_value
, max_digits
, max_decimal_places
,
max_whole_digits
The max_value
and min_value
error messages may contain
%(limit_value)s
, which will be substituted by the appropriate limit.
Similarly, the max_digits
, max_decimal_places
and
max_whole_digits
error messages may contain %(max)s
.
Takes four optional arguments:
max_value
¶min_value
¶These control the range of values permitted in the field, and should be
given as decimal.Decimal
values.
max_digits
¶The maximum number of digits (those before the decimal point plus those after the decimal point, with leading zeros stripped) permitted in the value.
decimal_places
¶The maximum number of decimal places permitted.
DurationField
¶DurationField
(**kwargs)¶TextInput
None
timedelta
.timedelta
. The value must be between datetime.timedelta.min
and datetime.timedelta.max
.required
, invalid
, overflow
.Accepts any format understood by
parse_duration()
.
EmailField
¶EmailField
(**kwargs)¶EmailInput
empty_value
.EmailValidator
to validate that
the given value is a valid email address, using a moderately complex
regular expression.required
, invalid
Has three optional arguments max_length
, min_length
, and
empty_value
which work just as they do for CharField
.
FileField
¶FileField
(**kwargs)¶ClearableFileInput
None
UploadedFile
object that wraps the file content
and file name into a single object.required
, invalid
, missing
, empty
,
max_length
Has two optional arguments for validation, max_length
and
allow_empty_file
. If provided, these ensure that the file name is at
most the given length, and that validation will succeed even if the file
content is empty.
To learn more about the UploadedFile
object, see the file uploads
documentation.
When you use a FileField
in a form, you must also remember to
bind the file data to the form.
The max_length
error refers to the length of the filename. In the error
message for that key, %(max)d
will be replaced with the maximum filename
length and %(length)d
will be replaced with the current filename length.
FilePathField
¶FilePathField
(**kwargs)¶Select
''
(an empty string)required
, invalid_choice
The field allows choosing from files inside a certain directory. It takes five
extra arguments; only path
is required:
path
¶The absolute path to the directory whose contents you want listed. This directory must exist.
recursive
¶If False
(the default) only the direct contents of path
will be
offered as choices. If True
, the directory will be descended into
recursively and all descendants will be listed as choices.
match
¶A regular expression pattern; only files with names matching this expression will be allowed as choices.
allow_files
¶Optional. Either True
or False
. Default is True
. Specifies
whether files in the specified location should be included. Either this or
allow_folders
must be True
.
allow_folders
¶Optional. Either True
or False
. Default is False
. Specifies
whether folders in the specified location should be included. Either this or
allow_files
must be True
.
FloatField
¶FloatField
(**kwargs)¶NumberInput
when Field.localize
is
False
, else TextInput
.None
MaxValueValidator
and
MinValueValidator
if max_value
and
min_value
are provided. Leading and trailing whitespace is allowed,
as in Python’s float()
function.required
, invalid
, max_value
,
min_value
Takes two optional arguments for validation, max_value
and min_value
.
These control the range of values permitted in the field.
ImageField
¶ImageField
(**kwargs)¶ClearableFileInput
None
UploadedFile
object that wraps the file content
and file name into a single object.FileExtensionValidator
to validate that
the file extension is supported by Pillow.required
, invalid
, missing
, empty
,
invalid_image
Using an ImageField
requires that Pillow is installed with support
for the image formats you use. If you encounter a corrupt image
error
when you upload an image, it usually means that Pillow doesn’t understand
its format. To fix this, install the appropriate library and reinstall
Pillow.
When you use an ImageField
on a form, you must also remember to
bind the file data to the form.
After the field has been cleaned and validated, the UploadedFile
object will have an additional image
attribute containing the Pillow
Image instance used to check if the file was a valid image. Pillow
closes the underlying file descriptor after verifying an image, so while
non-image data attributes, such as format
, height
, and width
,
are available, methods that access the underlying image data, such as
getdata()
or getpixel()
, cannot be used without reopening the file.
For example:
>>> from PIL import Image
>>> from django import forms
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> class ImageForm(forms.Form):
... img = forms.ImageField()
>>> file_data = {'img': SimpleUploadedFile('test.png', <file data>)}
>>> form = ImageForm({}, file_data)
# Pillow closes the underlying file descriptor.
>>> form.is_valid()
True
>>> image_field = form.cleaned_data['img']
>>> image_field.image
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
>>> image_field.image.width
191
>>> image_field.image.height
287
>>> image_field.image.format
'PNG'
>>> image_field.image.getdata()
# Raises AttributeError: 'NoneType' object has no attribute 'seek'.
>>> image = Image.open(image_field)
>>> image.getdata()
<ImagingCore object at 0x7f5984f874b0>
Additionally, UploadedFile.content_type
will be updated with the
image’s content type if Pillow can determine it, otherwise it will be set
to None
.
IntegerField
¶IntegerField
(**kwargs)¶NumberInput
when Field.localize
is
False
, else TextInput
.None
MaxValueValidator
and
MinValueValidator
if max_value
and
min_value
are provided. Leading and trailing whitespace is allowed,
as in Python’s int()
function.required
, invalid
, max_value
,
min_value
The max_value
and min_value
error messages may contain
%(limit_value)s
, which will be substituted by the appropriate limit.
Takes two optional arguments for validation:
max_value
¶min_value
¶These control the range of values permitted in the field.
JSONField
¶JSONField
(encoder=None, decoder=None, **kwargs)¶A field which accepts JSON encoded data for a
JSONField
.
Textarea
None
dict
, list
, or None
), depending on JSONField.decoder
.required
, invalid
Takes two optional arguments:
encoder
¶A json.JSONEncoder
subclass to serialize data types not
supported by the standard JSON serializer (e.g. datetime.datetime
or UUID
). For example, you can use the
DjangoJSONEncoder
class.
Defaults to json.JSONEncoder
.
decoder
¶A json.JSONDecoder
subclass to deserialize the input. Your
deserialization may need to account for the fact that you can’t be
certain of the input type. For example, you run the risk of returning a
datetime
that was actually a string that just happened to be in the
same format chosen for datetime
s.
The decoder
can be used to validate the input. If
json.JSONDecodeError
is raised during the deserialization,
a ValidationError
will be raised.
Defaults to json.JSONDecoder
.
User friendly forms
JSONField
is not particularly user friendly in most cases. However,
it is a useful way to format data from a client-side widget for
submission to the server.
GenericIPAddressField
¶GenericIPAddressField
(**kwargs)¶A field containing either an IPv4 or an IPv6 address.
TextInput
''
(an empty string)required
, invalid
The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2,
including using the IPv4 format suggested in paragraph 3 of that section, like
::ffff:192.0.2.0
. For example, 2001:0::0:01
would be normalized to
2001::1
, and ::ffff:0a0a:0a0a
to ::ffff:10.10.10.10
. All characters
are converted to lowercase.
Takes two optional arguments:
protocol
¶Limits valid inputs to the specified protocol.
Accepted values are both
(default), IPv4
or IPv6
. Matching is case insensitive.
unpack_ipv4
¶Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1
.
If this option is enabled that address would be unpacked to
192.0.2.1
. Default is disabled. Can only be used
when protocol
is set to 'both'
.
MultipleChoiceField
¶MultipleChoiceField
(**kwargs)¶SelectMultiple
[]
(an empty list)required
, invalid_choice
, invalid_list
The invalid_choice
error message may contain %(value)s
, which will be
replaced with the selected choice.
Takes one extra required argument, choices
, as for ChoiceField
.
TypedMultipleChoiceField
¶TypedMultipleChoiceField
(**kwargs)¶Just like a MultipleChoiceField
, except TypedMultipleChoiceField
takes two extra arguments, coerce
and empty_value
.
SelectMultiple
empty_value
coerce
argument.required
, invalid_choice
The invalid_choice
error message may contain %(value)s
, which will be
replaced with the selected choice.
Takes two extra arguments, coerce
and empty_value
, as for
TypedChoiceField
.
NullBooleanField
¶NullBooleanField
(**kwargs)¶NullBooleanSelect
None
True
, False
or None
value.ValidationError
).NullBooleanField
may be used with widgets such as
Select
or RadioSelect
by providing the widget choices
:
NullBooleanField(
widget=Select(
choices=[
('', 'Unknown'),
(True, 'Yes'),
(False, 'No'),
]
)
)
RegexField
¶RegexField
(**kwargs)¶TextInput
empty_value
.RegexValidator
to validate that
the given value matches a certain regular expression.required
, invalid
Takes one required argument:
regex
¶A regular expression specified either as a string or a compiled regular expression object.
Also takes max_length
, min_length
, strip
, and empty_value
which work just as they do for CharField
.
strip
¶Defaults to False
. If enabled, stripping will be applied before the
regex validation.
SlugField
¶SlugField
(**kwargs)¶TextInput
empty_value
.validate_slug
or
validate_unicode_slug
to validate that
the given value contains only letters, numbers, underscores, and hyphens.required
, invalid
This field is intended for use in representing a model
SlugField
in forms.
Takes two optional parameters:
allow_unicode
¶A boolean instructing the field to accept Unicode letters in addition
to ASCII letters. Defaults to False
.
empty_value
¶The value to use to represent “empty”. Defaults to an empty string.
TimeField
¶TimeField
(**kwargs)¶TimeInput
None
datetime.time
object.datetime.time
or string
formatted in a particular time format.required
, invalid
Takes one optional argument:
input_formats
¶A list of formats used to attempt to convert a string to a valid
datetime.time
object.
If no input_formats
argument is provided, the default input formats are
taken from TIME_INPUT_FORMATS
if USE_L10N
is
False
, or from the active locale format TIME_INPUT_FORMATS
key if
localization is enabled. See also format localization.
URLField
¶URLField
(**kwargs)¶URLInput
empty_value
.URLValidator
to validate that the
given value is a valid URL.required
, invalid
Has three optional arguments max_length
, min_length
, and
empty_value
which work just as they do for CharField
.
Field
classes¶ComboField
¶ComboField
(**kwargs)¶TextInput
''
(an empty string)ComboField
.required
, invalid
Takes one extra required argument:
fields
¶The list of fields that should be used to validate the field’s value (in the order in which they are provided).
>>> from django.forms import ComboField
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
>>> f.clean('test@example.com')
'test@example.com'
>>> f.clean('longemailaddress@example.com')
Traceback (most recent call last):
...
ValidationError: ['Ensure this value has at most 20 characters (it has 28).']
MultiValueField
¶MultiValueField
(fields=(), **kwargs)¶TextInput
''
(an empty string)compress
method of the subclass.MultiValueField
.required
, invalid
, incomplete
Aggregates the logic of multiple fields that together produce a single value.
This field is abstract and must be subclassed. In contrast with the
single-value fields, subclasses of MultiValueField
must not
implement clean()
but instead - implement
compress()
.
Takes one extra required argument:
fields
¶A tuple of fields whose values are cleaned and subsequently combined
into a single value. Each value of the field is cleaned by the
corresponding field in fields
– 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 combined into
a single value by compress()
.
Also takes some optional arguments:
require_all_fields
¶Defaults to True
, in which case a required
validation error
will be raised if no value is supplied for any field.
When set to False
, the Field.required
attribute can be set
to False
for individual fields to make them optional. If no value
is supplied for a required field, an incomplete
validation error
will be raised.
A default incomplete
error message can be defined on the
MultiValueField
subclass, or different messages can be defined
on each individual field. For example:
from django.core.validators import RegexValidator
class PhoneField(MultiValueField):
def __init__(self, **kwargs):
# Define one message for all fields.
error_messages = {
'incomplete': 'Enter a country calling code and a phone number.',
}
# Or define a different message for each field.
fields = (
CharField(
error_messages={'incomplete': 'Enter a country calling code.'},
validators=[
RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
],
),
CharField(
error_messages={'incomplete': 'Enter a phone number.'},
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
),
CharField(
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
required=False,
),
)
super().__init__(
error_messages=error_messages, fields=fields,
require_all_fields=False, **kwargs
)
widget
¶Must be a subclass of django.forms.MultiWidget
.
Default value is TextInput
, which
probably is not very useful in this case.
compress
(data_list)¶Takes a list of valid values and returns a “compressed” version of
those values – in a single value. For example,
SplitDateTimeField
is a subclass which combines a time field
and a date field into a datetime
object.
This method must be implemented in the subclasses.
SplitDateTimeField
¶SplitDateTimeField
(**kwargs)¶SplitDateTimeWidget
None
datetime.datetime
object.datetime.datetime
or string
formatted in a particular datetime format.required
, invalid
, invalid_date
,
invalid_time
Takes two optional arguments:
input_date_formats
¶A list of formats used to attempt to convert a string to a valid
datetime.date
object.
If no input_date_formats
argument is provided, the default input formats
for DateField
are used.
input_time_formats
¶A list of formats used to attempt to convert a string to a valid
datetime.time
object.
If no input_time_formats
argument is provided, the default input formats
for TimeField
are used.
Two fields are available for representing relationships between
models: ModelChoiceField
and
ModelMultipleChoiceField
. Both of these fields require a
single queryset
parameter that is used to create the choices for
the field. Upon form validation, these fields will place either one
model object (in the case of ModelChoiceField
) or multiple model
objects (in the case of ModelMultipleChoiceField
) into the
cleaned_data
dictionary of the form.
For more complex uses, you can specify queryset=None
when declaring the
form field and then populate the queryset
in the form’s __init__()
method:
class FooMultipleChoiceForm(forms.Form):
foo_select = forms.ModelMultipleChoiceField(queryset=None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['foo_select'].queryset = ...
Both ModelChoiceField
and ModelMultipleChoiceField
have an iterator
attribute which specifies the class used to iterate over the queryset when
generating choices. See Iterating relationship choices for details.
ModelChoiceField
¶ModelChoiceField
(**kwargs)¶Select
None
required
, invalid_choice
Allows the selection of a single model object, suitable for representing a
foreign key. Note that the default widget for ModelChoiceField
becomes
impractical when the number of entries increases. You should avoid using it
for more than 100 items.
A single argument is required:
queryset
¶A QuerySet
of model objects from which the choices for the field
are derived and which is used to validate the user’s selection. It’s
evaluated when the form is rendered.
ModelChoiceField
also takes two optional arguments:
empty_label
¶By default the <select>
widget used by ModelChoiceField
will have an
empty choice at the top of the list. You can change the text of this
label (which is "---------"
by default) with the empty_label
attribute, or you can disable the empty label entirely by setting
empty_label
to None
:
# A custom empty label
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
# No empty label
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Note that if a ModelChoiceField
is required and has a default
initial value, no empty choice is created (regardless of the value
of empty_label
).
to_field_name
¶This optional argument is used to specify the field to use as the value
of the choices in the field’s widget. Be sure it’s a unique field for
the model, otherwise the selected value could match more than one
object. By default it is set to None
, in which case the primary key
of each object will be used. For example:
# No custom to_field_name
field1 = forms.ModelChoiceField(queryset=...)
would yield:
<select id="id_field1" name="field1">
<option value="obj1.pk">Object1</option>
<option value="obj2.pk">Object2</option>
...
</select>
and:
# to_field_name provided
field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
would yield:
<select id="id_field2" name="field2">
<option value="obj1.name">Object1</option>
<option value="obj2.name">Object2</option>
...
</select>
ModelChoiceField
also has the attribute:
iterator
¶The iterator class used to generate field choices from queryset
. By
default, ModelChoiceIterator
.
The __str__()
method of the model will be called to generate string
representations of the objects for use in the field’s choices. To provide
customized representations, subclass ModelChoiceField
and override
label_from_instance
. This method will receive a model object and should
return a string suitable for representing it. For example:
from django.forms import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "My Object #%i" % obj.id
ModelMultipleChoiceField
¶ModelMultipleChoiceField
(**kwargs)¶SelectMultiple
QuerySet
(self.queryset.none()
)QuerySet
of model instances.required
, invalid_list
, invalid_choice
,
invalid_pk_value
The invalid_choice
message may contain %(value)s
and the
invalid_pk_value
message may contain %(pk)s
, which will be
substituted by the appropriate values.
Allows the selection of one or more model objects, suitable for
representing a many-to-many relation. As with ModelChoiceField
,
you can use label_from_instance
to customize the object
representations.
A single argument is required:
queryset
¶Same as ModelChoiceField.queryset
.
Takes one optional argument:
to_field_name
¶Same as ModelChoiceField.to_field_name
.
ModelMultipleChoiceField
also has the attribute:
iterator
¶Same as ModelChoiceField.iterator
.
Deprecated since version 3.1: The list
message is deprecated, use invalid_list
instead.
By default, ModelChoiceField
and ModelMultipleChoiceField
use
ModelChoiceIterator
to generate their field choices
.
When iterated, ModelChoiceIterator
yields 2-tuple choices containing
ModelChoiceIteratorValue
instances as the first value
element in
each choice. ModelChoiceIteratorValue
wraps the choice value while
maintaining a reference to the source model instance that can be used in custom
widget implementations, for example, to add data-* attributes to
<option>
elements.
For example, consider the following models:
from django.db import models
class Topping(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(decimal_places=2, max_digits=6)
def __str__(self):
return self.name
class Pizza(models.Model):
topping = models.ForeignKey(Topping, on_delete=models.CASCADE)
You can use a Select
widget subclass to include
the value of Topping.price
as the HTML attribute data-price
for each
<option>
element:
from django import forms
class ToppingSelect(forms.Select):
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
option = super().create_option(name, value, label, selected, index, subindex, attrs)
if value:
option['attrs']['data-price'] = value.instance.price
return option
class PizzaForm(forms.ModelForm):
class Meta:
model = Pizza
fields = ['topping']
widgets = {'topping': ToppingSelect}
This will render the Pizza.topping
select as:
<select id="id_topping" name="topping" required>
<option value="" selected>---------</option>
<option value="1" data-price="1.50">mushrooms</option>
<option value="2" data-price="1.25">onions</option>
<option value="3" data-price="1.75">peppers</option>
<option value="4" data-price="2.00">pineapple</option>
</select>
For more advanced usage you may subclass ModelChoiceIterator
in order to
customize the yielded 2-tuple choices.
ModelChoiceIterator
¶ModelChoiceIterator
(field)¶The default class assigned to the iterator
attribute of
ModelChoiceField
and ModelMultipleChoiceField
. An
iterable that yields 2-tuple choices from the queryset.
A single argument is required:
field
¶The instance of ModelChoiceField
or ModelMultipleChoiceField
to
iterate and yield choices.
ModelChoiceIterator
has the following method:
__iter__
()¶Yields 2-tuple choices, in the (value, label)
format used by
ChoiceField.choices
. The first value
element is a
ModelChoiceIteratorValue
instance.
In older versions, the first value
element in the choice tuple
is the field
value itself, rather than a
ModelChoiceIteratorValue
instance. In most cases this proxies
transparently but, if you need the field
value itself, use the
ModelChoiceIteratorValue.value
attribute instead.
ModelChoiceIteratorValue
¶ModelChoiceIteratorValue
(value, instance)¶Two arguments are required:
value
¶The value of the choice. This value is used to render the value
attribute of an HTML <option>
element.
instance
¶The model instance from the queryset. The instance can be accessed in
custom ChoiceWidget.create_option()
implementations to adjust the
rendered HTML.
ModelChoiceIteratorValue
has the following method:
__str__
()¶Return value
as a string to be rendered in HTML.
If the built-in Field
classes don’t meet your needs, you can create custom
Field
classes. To do this, create a subclass of django.forms.Field
. Its
only requirements are that it implement a clean()
method and that its
__init__()
method accept the core arguments mentioned above (required
,
label
, initial
, widget
, help_text
).
You can also customize how a field will be accessed by overriding
get_bound_field()
.
Jul 27, 2022