Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

Form fields

classField(**kwargs)[source]

When you create aForm class, the most important part is defining thefields of the form. Each field has custom validation logic, along with a fewother hooks.

Field.clean(value)[source]

Although the primary way you’ll useField classes is inForm classes,you can also instantiate them and use them directly to get a better idea ofhow they work. EachField instance has aclean() method, which takesa single argument and either raises adjango.forms.ValidationErrorexception or returns the clean value:

>>>fromdjangoimportforms>>>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.']

Core field arguments

EachField class constructor takes at least these arguments. SomeField classes take additional, field-specific arguments, but the followingshouldalways be accepted:

required

Field.required

By default, eachField class assumes the value is required, so if you passan empty value – eitherNone or the empty string ("") – thenclean() will raise aValidationError exception:

>>>fromdjangoimportforms>>>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 isnot required, passrequired=False to theField 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 aField hasrequired=False and you passclean() an empty value,thenclean() will return anormalized empty value rather than raisingValidationError. ForCharField, this will be a Unicode empty string.For otherField classes, it might beNone. (This varies from field tofield.)

Widgets of required form fields have therequired HTML attribute. Set theForm.use_required_attribute attribute toFalse to disable it. Therequired attribute isn’t included on forms of formsets because the browservalidation may not be correct when adding and deleting formsets.

New in Django 1.10:

Support for therequired HTML attribute was added.

label

Field.label

Thelabel argument lets you specify the “human-friendly” label for thisfield. This is used when theField is displayed in aForm.

As explained in “Outputting forms as HTML” above, the default label for aField is generated from the field name by converting all underscores tospaces and upper-casing the first letter. Specifylabel if that defaultbehavior doesn’t result in an adequate label.

Here’s a full exampleForm that implementslabel for two of its fields.We’ve specifiedauto_id=False to simplify the output:

>>>fromdjangoimportforms>>>classCommentForm(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

Thelabel_suffix argument lets you override the form’slabel_suffix on a per-field basis:

>>>classContactForm(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

Theinitial argument lets you specify the initial value to use whenrendering thisField in an unboundForm.

To specify dynamic initial data, see theForm.initial parameter.

The use-case for this is when you want to display an “empty” form in which afield is initialized to a particular value. For example:

>>>fromdjangoimportforms>>>classCommentForm(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 asdata when displaying the form? Well, if you do that, you’ll trigger validation,and the HTML output will include any validation errors:

>>>classCommentForm(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 whyinitial values are only displayed for unbound forms. For boundforms, the HTML output will use the bound data.

Also note thatinitial values arenot used as “fallback” data invalidation if a particular field’s value is not given.initial values areonly intended for initial form display:

>>>classCommentForm(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:

>>>importdatetime>>>classDateForm(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

Thewidget argument lets you specify aWidget class to use whenrendering thisField. SeeWidgets for more information.

help_text

Field.help_text

Thehelp_text argument lets you specify descriptive text for thisField. If you providehelp_text, it will be displayed next to theField when theField is rendered by one of the convenienceFormmethods (e.g.,as_ul()).

Like the model field’shelp_text, this valueisn’t HTML-escaped in automatically-generated forms.

Here’s a full exampleForm that implementshelp_text for two of itsfields. We’ve specifiedauto_id=False to simplify the output:

>>>fromdjangoimportforms>>>classHelpTextContactForm(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

Theerror_messages argument lets you override the default messages that thefield will raise. Pass in a dictionary with keys matching the error messages youwant to override. For example, here is the default error message:

>>>fromdjangoimportforms>>>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 thebuilt-in Field classes section below, eachField defines theerror message keys it uses.

validators

Field.validators

Thevalidators argument lets you provide a list of validation functionsfor this field.

See thevalidators documentation for more information.

localize

Field.localize

Thelocalize argument enables the localization of form data input, as wellas the rendered output.

See theformat localization documentation formore information.

disabled

Field.disabled
New in Django 1.9.

Thedisabled boolean argument, when set toTrue, disables a form fieldusing thedisabled 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 willbe ignored in favor of the value from the form’s initial data.

Checking if the field data has changed

has_changed()

Field.has_changed()[source]

Thehas_changed() method is used to determine if the field value has changedfrom the initial value. ReturnsTrue orFalse.

See theForm.has_changed() documentation for more information.

Built-inField classes

Naturally, theforms library comes with a set ofField classes thatrepresent common validation needs. This section documents each built-in field.

For each field, we describe the default widget used if you don’t specifywidget. We also specify the value returned when you provide an empty value(see the section onrequired above to understand what that means).

BooleanField

classBooleanField(**kwargs)[source]
  • Default widget:CheckboxInput
  • Empty value:False
  • Normalizes to: A PythonTrue orFalse value.
  • Validates that the value isTrue (e.g. the check box is checked) ifthe field hasrequired=True.
  • Error message keys:required

Note

Since allField subclasses haverequired=True by default, thevalidation condition here is important. If you want to include a booleanin your form that can be eitherTrue orFalse (e.g. a checked orunchecked checkbox), you must remember to pass inrequired=False whencreating theBooleanField.

CharField

classCharField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validatesmax_length ormin_length, if they are provided.Otherwise, all inputs are valid.
  • Error message keys:required,max_length,min_length

Has three optional arguments for validation:

max_length
min_length

If provided, these arguments ensure that the string is at most or at leastthe given length.

strip
New in Django 1.9.

IfTrue (default), the value will be stripped of leading andtrailing whitespace.

ChoiceField

classChoiceField(**kwargs)[source]
  • Default widget:Select
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates that the given value exists in the list of choices.
  • Error message keys:required,invalid_choice

Theinvalid_choice error message may contain%(value)s, which will bereplaced with the selected choice.

Takes one extra required argument:

choices

Either an iterable (e.g., a list or tuple) of 2-tuples to use aschoices for this field, or a callable that returns such an iterable.This argument accepts the same formats as thechoices argument to amodel field. See themodel field reference documentation onchoices for more details. If the argument is acallable, it is evaluated each time the field’s form is initialized.

TypedChoiceField

classTypedChoiceField(**kwargs)[source]

Just like aChoiceField, exceptTypedChoiceField takes twoextra arguments,coerce andempty_value.

  • Default widget:Select
  • Empty value: Whatever you’ve given asempty_value.
  • Normalizes to: A value of the type provided by thecoerceargument.
  • Validates that the given value exists in the list of choices and can becoerced.
  • Error message keys:required,invalid_choice

Takes extra arguments:

coerce

A function that takes one argument and returns a coerced value. Examplesinclude the built-inint,float,bool and other types. Defaultsto an identity function. Note that coercion happens after inputvalidation, so it is possible to coerce to a value not present inchoices.

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 becoerced by the function given in thecoerce argument, so choose itaccordingly.

DateField

classDateField(**kwargs)[source]
  • Default widget:DateInput
  • Empty value:None
  • Normalizes to: A Pythondatetime.date object.
  • Validates that the given value is either adatetime.date,datetime.datetime or string formatted in a particular date format.
  • Error message keys:required,invalid

Takes one optional argument:

input_formats

A list of formats used to attempt to convert a string to a validdatetime.date object.

If noinput_formats argument is provided, the default input formats are:

['%Y-%m-%d',# '2006-10-25''%m/%d/%Y',# '10/25/2006''%m/%d/%y']# '10/25/06'

Additionally, if you specifyUSE_L10N=False in your settings, thefollowing will also be included in the default input formats:

['%b%d %Y',# 'Oct 25 2006''%b%d, %Y',# 'Oct 25, 2006''%d %b %Y',# '25 Oct 2006''%d %b, %Y',# '25 Oct, 2006''%B%d %Y',# 'October 25 2006''%B%d, %Y',# 'October 25, 2006''%d %B %Y',# '25 October 2006''%d %B, %Y']# '25 October, 2006'

See alsoformat localization.

DateTimeField

classDateTimeField(**kwargs)[source]
  • Default widget:DateTimeInput
  • Empty value:None
  • Normalizes to: A Pythondatetime.datetime object.
  • Validates that the given value is either adatetime.datetime,datetime.date or string formatted in a particular datetime format.
  • Error message keys:required,invalid

Takes one optional argument:

input_formats

A list of formats used to attempt to convert a string to a validdatetime.datetime object.

If noinput_formats argument is provided, the default input formats are:

['%Y-%m-%d %H:%M:%S',# '2006-10-25 14:30:59''%Y-%m-%d %H:%M',# '2006-10-25 14:30''%Y-%m-%d',# '2006-10-25''%m/%d/%Y %H:%M:%S',# '10/25/2006 14:30:59''%m/%d/%Y %H:%M',# '10/25/2006 14:30''%m/%d/%Y',# '10/25/2006''%m/%d/%y %H:%M:%S',# '10/25/06 14:30:59''%m/%d/%y %H:%M',# '10/25/06 14:30''%m/%d/%y']# '10/25/06'

See alsoformat localization.

DecimalField

classDecimalField(**kwargs)[source]
  • Default widget:NumberInput whenField.localize isFalse, elseTextInput.
  • Empty value:None
  • Normalizes to: A Pythondecimal.
  • Validates that the given value is a decimal. Leading and trailingwhitespace is ignored.
  • Error message keys:required,invalid,max_value,min_value,max_digits,max_decimal_places,max_whole_digits

Themax_value andmin_value error messages may contain%(limit_value)s, which will be substituted by the appropriate limit.Similarly, themax_digits,max_decimal_places andmax_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 begiven asdecimal.Decimal values.

max_digits

The maximum number of digits (those before the decimal point plus thoseafter the decimal point, with leading zeros stripped) permitted in thevalue.

decimal_places

The maximum number of decimal places permitted.

DurationField

classDurationField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:None
  • Normalizes to: A Pythontimedelta.
  • Validates that the given value is a string which can be converted into atimedelta.
  • Error message keys:required,invalid.

Accepts any format understood byparse_duration().

EmailField

classEmailField(**kwargs)[source]
  • Default widget:EmailInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates that the given value is a valid email address, using amoderately complex regular expression.
  • Error message keys:required,invalid

Has two optional arguments for validation,max_length andmin_length.If provided, these arguments ensure that the string is at most or at least thegiven length.

FileField

classFileField(**kwargs)[source]
  • Default widget:ClearableFileInput
  • Empty value:None
  • Normalizes to: AnUploadedFile object that wraps the file contentand file name into a single object.
  • Can validate that non-empty file data has been bound to the form.
  • Error message keys:required,invalid,missing,empty,max_length

Has two optional arguments for validation,max_length andallow_empty_file. If provided, these ensure that the file name is atmost the given length, and that validation will succeed even if the filecontent is empty.

To learn more about theUploadedFile object, see thefile uploadsdocumentation.

When you use aFileField in a form, you must also remember tobind the file data to the form.

Themax_length error refers to the length of the filename. In the errormessage for that key,%(max)d will be replaced with the maximum filenamelength and%(length)d will be replaced with the current filename length.

FilePathField

classFilePathField(**kwargs)[source]
  • Default widget:Select
  • Empty value:None
  • Normalizes to: A unicode object
  • Validates that the selected choice exists in the list of choices.
  • Error message keys:required,invalid_choice

The field allows choosing from files inside a certain directory. It takes fiveextra arguments; onlypath is required:

path

The absolute path to the directory whose contents you want listed. Thisdirectory must exist.

recursive

IfFalse (the default) only the direct contents ofpath will beoffered as choices. IfTrue, the directory will be descended intorecursively and all descendants will be listed as choices.

match

A regular expression pattern; only files with names matching this expressionwill be allowed as choices.

allow_files

Optional. EitherTrue orFalse. Default isTrue. Specifieswhether files in the specified location should be included. Either this orallow_folders must beTrue.

allow_folders

Optional. EitherTrue orFalse. Default isFalse. Specifieswhether folders in the specified location should be included. Either this orallow_files must beTrue.

FloatField

classFloatField(**kwargs)[source]
  • Default widget:NumberInput whenField.localize isFalse, elseTextInput.
  • Empty value:None
  • Normalizes to: A Python float.
  • Validates that the given value is a float. Leading and trailingwhitespace is allowed, as in Python’sfloat() function.
  • Error message keys:required,invalid,max_value,min_value

Takes two optional arguments for validation,max_value andmin_value.These control the range of values permitted in the field.

ImageField

classImageField(**kwargs)[source]
  • Default widget:ClearableFileInput
  • Empty value:None
  • Normalizes to: AnUploadedFile object that wraps the file contentand file name into a single object.
  • Validates that file data has been bound to the form, and that thefile is of an image format understood by Pillow.
  • Error message keys:required,invalid,missing,empty,invalid_image

Using anImageField requires thatPillow is installed with supportfor the image formats you use. If you encounter acorruptimage errorwhen you upload an image, it usually means that Pillow doesn’t understandits format. To fix this, install the appropriate library and reinstallPillow.

When you use anImageField on a form, you must also remember tobind the file data to the form.

After the field has been cleaned and validated, theUploadedFileobject will have an additionalimage attribute containing the PillowImage instance used to check if the file was a valid image. Also,UploadedFile.content_type will be updated with the image’s content typeif Pillow can determine it, otherwise it will be set toNone.

IntegerField

classIntegerField(**kwargs)[source]
  • Default widget:NumberInput whenField.localize isFalse, elseTextInput.
  • Empty value:None
  • Normalizes to: A Python integer or long integer.
  • Validates that the given value is an integer. Leading and trailingwhitespace is allowed, as in Python’sint() function.
  • Error message keys:required,invalid,max_value,min_value

Themax_value andmin_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.

GenericIPAddressField

classGenericIPAddressField(**kwargs)[source]

A field containing either an IPv4 or an IPv6 address.

  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object. IPv6 addresses arenormalized as described below.
  • Validates that the given value is a valid IP address.
  • Error message keys:required,invalid

The IPv6 address normalization followsRFC 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 to2001::1, and::ffff:0a0a:0a0a to::ffff:10.10.10.10. All charactersare converted to lowercase.

Takes two optional arguments:

protocol

Limits valid inputs to the specified protocol.Accepted values areboth (default),IPv4orIPv6. 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 to192.0.2.1. Default is disabled. Can only be usedwhenprotocol is set to'both'.

MultipleChoiceField

classMultipleChoiceField(**kwargs)[source]
  • Default widget:SelectMultiple
  • Empty value:[] (an empty list)
  • Normalizes to: A list of Unicode objects.
  • Validates that every value in the given list of values exists in the listof choices.
  • Error message keys:required,invalid_choice,invalid_list

Theinvalid_choice error message may contain%(value)s, which will bereplaced with the selected choice.

Takes one extra required argument,choices, as forChoiceField.

TypedMultipleChoiceField

classTypedMultipleChoiceField(**kwargs)[source]

Just like aMultipleChoiceField, exceptTypedMultipleChoiceFieldtakes two extra arguments,coerce andempty_value.

  • Default widget:SelectMultiple
  • Empty value: Whatever you’ve given asempty_value
  • Normalizes to: A list of values of the type provided by thecoerceargument.
  • Validates that the given values exists in the list of choices and can becoerced.
  • Error message keys:required,invalid_choice

Theinvalid_choice error message may contain%(value)s, which will bereplaced with the selected choice.

Takes two extra arguments,coerce andempty_value, as forTypedChoiceField.

NullBooleanField

classNullBooleanField(**kwargs)[source]
  • Default widget:NullBooleanSelect
  • Empty value:None
  • Normalizes to: A PythonTrue,False orNone value.
  • Validates nothing (i.e., it never raises aValidationError).

RegexField

classRegexField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates that the given value matches against a certain regularexpression.
  • Error message keys:required,invalid

Takes one required argument:

regex

A regular expression specified either as a string or a compiled regularexpression object.

Also takesmax_length,min_length, andstrip, which work justas they do forCharField.

strip
New in Django 1.9.

Defaults toFalse. If enabled, stripping will be applied before theregex validation.

SlugField

classSlugField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates that the given value contains only letters, numbers,underscores, and hyphens.
  • Error messages:required,invalid

This field is intended for use in representing a modelSlugField in forms.

Takes an optional parameter:

allow_unicode
New in Django 1.9.

A boolean instructing the field to accept Unicode letters in additionto ASCII letters. Defaults toFalse.

TimeField

classTimeField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:None
  • Normalizes to: A Pythondatetime.time object.
  • Validates that the given value is either adatetime.time or stringformatted in a particular time format.
  • Error message keys:required,invalid

Takes one optional argument:

input_formats

A list of formats used to attempt to convert a string to a validdatetime.time object.

If noinput_formats argument is provided, the default input formats are:

'%H:%M:%S',# '14:30:59''%H:%M',# '14:30'

URLField

classURLField(**kwargs)[source]
  • Default widget:URLInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates that the given value is a valid URL.
  • Error message keys:required,invalid

Takes the following optional arguments:

max_length
min_length

These are the same asCharField.max_length andCharField.min_length.

UUIDField

classUUIDField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: AUUID object.
  • Error message keys:required,invalid

This field will accept any string format accepted as thehex argumentto theUUID constructor.

Slightly complex built-inField classes

ComboField

classComboField(**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: A Unicode object.
  • Validates the given value against each of the fields specifiedas an argument to theComboField.
  • Error message keys:required,invalid

Takes one extra required argument:

fields

The list of fields that should be used to validate the field’s value (inthe order in which they are provided).

>>>fromdjango.formsimportComboField>>>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

classMultiValueField(fields=(),**kwargs)[source]
  • Default widget:TextInput
  • Empty value:'' (an empty string)
  • Normalizes to: the type returned by thecompress method of the subclass.
  • Validates the given value against each of the fields specifiedas an argument to theMultiValueField.
  • Error message keys:required,invalid,incomplete

Aggregates the logic of multiple fields that together produce a singlevalue.

This field is abstract and must be subclassed. In contrast with thesingle-value fields, subclasses ofMultiValueField must notimplementclean() but instead - implementcompress().

Takes one extra required argument:

fields

A tuple of fields whose values are cleaned and subsequently combinedinto a single value. Each value of the field is cleaned by thecorresponding field infields – the first value is cleaned by thefirst field, the second value is cleaned by the second field, etc.Once all fields are cleaned, the list of clean values is combined intoa single value bycompress().

Also takes one extra optional argument:

require_all_fields

Defaults toTrue, in which case arequired validation errorwill be raised if no value is supplied for any field.

When set toFalse, theField.required attribute can be settoFalse for individual fields to make them optional. If no valueis supplied for a required field, anincomplete validation errorwill be raised.

A defaultincomplete error message can be defined on theMultiValueField subclass, or different messages can be definedon each individual field. For example:

fromdjango.core.validatorsimportRegexValidatorclassPhoneField(MultiValueField):def__init__(self,*args,**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(PhoneField,self).__init__(error_messages=error_messages,fields=fields,require_all_fields=False,*args,**kwargs)
widget

Must be a subclass ofdjango.forms.MultiWidget.Default value isTextInput, whichprobably is not very useful in this case.

compress(data_list)[source]

Takes a list of valid values and returns a “compressed” version ofthose values – in a single value. For example,SplitDateTimeField is a subclass which combines a time fieldand a date field into adatetime object.

This method must be implemented in the subclasses.

SplitDateTimeField

classSplitDateTimeField(**kwargs)[source]
  • Default widget:SplitDateTimeWidget
  • Empty value:None
  • Normalizes to: A Pythondatetime.datetime object.
  • Validates that the given value is adatetime.datetime or stringformatted in a particular datetime format.
  • Error message keys: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 validdatetime.date object.

If noinput_date_formats argument is provided, the default input formatsforDateField are used.

input_time_formats

A list of formats used to attempt to convert a string to a validdatetime.time object.

If noinput_time_formats argument is provided, the default input formatsforTimeField are used.

Fields which handle relationships

Two fields are available for representing relationships betweenmodels:ModelChoiceField andModelMultipleChoiceField. Both of these fields require asinglequeryset parameter that is used to create the choices forthe field. Upon form validation, these fields will place either onemodel object (in the case ofModelChoiceField) or multiple modelobjects (in the case ofModelMultipleChoiceField) into thecleaned_data dictionary of the form.

For more complex uses, you can specifyqueryset=None when declaring theform field and then populate thequeryset in the form’s__init__()method:

classFooMultipleChoiceForm(forms.Form):foo_select=forms.ModelMultipleChoiceField(queryset=None)def__init__(self,*args,**kwargs):super(FooMultipleChoiceForm,self).__init__(*args,**kwargs)self.fields['foo_select'].queryset=...

ModelChoiceField

classModelChoiceField(**kwargs)[source]
  • Default widget:Select
  • Empty value:None
  • Normalizes to: A model instance.
  • Validates that the given id exists in the queryset.
  • Error message keys:required,invalid_choice

Allows the selection of a single model object, suitable for representing aforeign key. Note that the default widget forModelChoiceField becomesimpractical when the number of entries increases. You should avoid using itfor more than 100 items.

A single argument is required:

queryset

AQuerySet of model objects from which the choices for thefield will be derived, and which will be used to validate theuser’s selection.

ModelChoiceField also takes two optional arguments:

empty_label

By default the<select> widget used byModelChoiceField will have anempty choice at the top of the list. You can change the text of thislabel (which is"---------" by default) with theempty_labelattribute, or you can disable the empty label entirely by settingempty_label toNone:

# A custom empty labelfield1=forms.ModelChoiceField(queryset=...,empty_label="(Nothing)")# No empty labelfield2=forms.ModelChoiceField(queryset=...,empty_label=None)

Note that if aModelChoiceField is required and has a defaultinitial value, no empty choice is created (regardless of the valueofempty_label).

to_field_name

This optional argument is used to specify the field to use as the valueof the choices in the field’s widget. Be sure it’s a unique field forthe model, otherwise the selected value could match more than oneobject. By default it is set toNone, in which case the primary keyof each object will be used. For example:

# No custom to_field_namefield1=forms.ModelChoiceField(queryset=...)

would yield:

<selectid="id_field1"name="field1"><optionvalue="obj1.pk">Object1</option><optionvalue="obj2.pk">Object2</option>...</select>

and:

# to_field_name providedfield2=forms.ModelChoiceField(queryset=...,to_field_name="name")

would yield:

<selectid="id_field2"name="field2"><optionvalue="obj1.name">Object1</option><optionvalue="obj2.name">Object2</option>...</select>

The__str__ (__unicode__ on Python 2) method of the model will becalled to generate string representations of the objects for use in thefield’s choices; to provide customized representations, subclassModelChoiceField and overridelabel_from_instance. This method willreceive a model object, and should return a string suitable for representingit. For example:

fromdjango.formsimportModelChoiceFieldclassMyModelChoiceField(ModelChoiceField):deflabel_from_instance(self,obj):return"My Object #%i"%obj.id

ModelMultipleChoiceField

classModelMultipleChoiceField(**kwargs)[source]
  • Default widget:SelectMultiple
  • Empty value: An emptyQuerySet (self.queryset.none())
  • Normalizes to: AQuerySet of model instances.
  • Validates that every id in the given list of values exists in thequeryset.
  • Error message keys:required,list,invalid_choice,invalid_pk_value

Theinvalid_choice message may contain%(value)s and theinvalid_pk_value message may contain%(pk)s, which will besubstituted by the appropriate values.

Allows the selection of one or more model objects, suitable forrepresenting a many-to-many relation. As withModelChoiceField,you can uselabel_from_instance to customize the objectrepresentations.

A single argument is required:

queryset

Same asModelChoiceField.queryset.

Takes one optional argument:

to_field_name

Same asModelChoiceField.to_field_name.

Creating custom fields

If the built-inField classes don’t meet your needs, you can easily createcustomField classes. To do this, just create a subclass ofdjango.forms.Field. Its only requirements are that it implement aclean() method and that its__init__() method accept the core argumentsmentioned above (required,label,initial,widget,help_text).

You can also customize how a field will be accessed by overridingget_bound_field().

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 1.10):HTML |PDF |ePub
Provided byRead the Docs.

Diamond and Platinum Members

Sentry
JetBrains
This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release!

[8]ページ先頭

©2009-2025 Movatter.jp