Form fields

  • class Field(**kwargs)[源代码]
  • When you create a Form 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)[源代码]

  • 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 ofhow they work. Each Field instance has a clean() method, which takesa single argument and either raises a django.forms.ValidationErrorexception or returns the clean value:
  1. >>> from django import forms
  2. >>> f = forms.EmailField()
  3. >>> f.clean('foo@example.com')
  4. 'foo@example.com'
  5. >>> f.clean('invalid email address')
  6. Traceback (most recent call last):
  7. ...
  8. ValidationError: ['Enter a valid email address.']

Core field arguments

Each Field class constructor takes at least these arguments. SomeField classes take additional, field-specific arguments, but the followingshould always be accepted:

required

  • Field.required
  • By default, each Field class assumes the value is required, so if you passan empty value — either None or the empty string ("") — thenclean() will raise a ValidationError exception:
  1. >>> from django import forms
  2. >>> f = forms.CharField()
  3. >>> f.clean('foo')
  4. 'foo'
  5. >>> f.clean('')
  6. Traceback (most recent call last):
  7. ...
  8. ValidationError: ['This field is required.']
  9. >>> f.clean(None)
  10. Traceback (most recent call last):
  11. ...
  12. ValidationError: ['This field is required.']
  13. >>> f.clean(' ')
  14. ' '
  15. >>> f.clean(0)
  16. '0'
  17. >>> f.clean(True)
  18. 'True'
  19. >>> f.clean(False)
  20. 'False'

To specify that a field is not required, pass required=False to theField constructor:

  1. >>> f = forms.CharField(required=False)
  2. >>> f.clean('foo')
  3. 'foo'
  4. >>> f.clean('')
  5. ''
  6. >>> f.clean(None)
  7. ''
  8. >>> f.clean(0)
  9. '0'
  10. >>> f.clean(True)
  11. 'True'
  12. >>> f.clean(False)
  13. 'False'

If a Field has required=False and you pass clean() an empty value,then clean() will return a normalized empty value rather than raisingValidationError. For CharField, this will be an empty string. For otherField classes, it might be None. (This varies from field to field.)

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

label

  • Field.label
  • The label argument lets you specify the "human-friendly" label for thisfield. This is used when the Field is displayed in a Form.

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. Specify label if that defaultbehavior 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:

  1. >>> from django import forms
  2. >>> class CommentForm(forms.Form):
  3. ... name = forms.CharField(label='Your name')
  4. ... url = forms.URLField(label='Your website', required=False)
  5. ... comment = forms.CharField()
  6. >>> f = CommentForm(auto_id=False)
  7. >>> print(f)
  8. <tr><th>Your name:</th><td><input type="text" name="name" required></td></tr>
  9. <tr><th>Your website:</th><td><input type="url" name="url"></td></tr>
  10. <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'slabel_suffix on a per-field basis:
  1. >>> class ContactForm(forms.Form):
  2. ... age = forms.IntegerField()
  3. ... nationality = forms.CharField()
  4. ... captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
  5. >>> f = ContactForm(label_suffix='?')
  6. >>> print(f.as_p())
  7. <p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required></p>
  8. <p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required></p>
  9. <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 whenrendering 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 afield is initialized to a particular value. For example:

  1. >>> from django import forms
  2. >>> class CommentForm(forms.Form):
  3. ... name = forms.CharField(initial='Your name')
  4. ... url = forms.URLField(initial='http://')
  5. ... comment = forms.CharField()
  6. >>> f = CommentForm(auto_id=False)
  7. >>> print(f)
  8. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
  9. <tr><th>Url:</th><td><input type="url" name="url" value="http://" required></td></tr>
  10. <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:

  1. >>> class CommentForm(forms.Form):
  2. ... name = forms.CharField()
  3. ... url = forms.URLField()
  4. ... comment = forms.CharField()
  5. >>> default_data = {'name': 'Your name', 'url': 'http://'}
  6. >>> f = CommentForm(default_data, auto_id=False)
  7. >>> print(f)
  8. <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required></td></tr>
  9. <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>
  10. <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 boundforms, the HTML output will use the bound data.

Also note that initial values are not used as "fallback" data invalidation if a particular field's value is not given. initial values areonly intended for initial form display:

  1. >>> class CommentForm(forms.Form):
  2. ... name = forms.CharField(initial='Your name')
  3. ... url = forms.URLField(initial='http://')
  4. ... comment = forms.CharField()
  5. >>> data = {'name': '', 'url': '', 'comment': 'Foo'}
  6. >>> f = CommentForm(data)
  7. >>> f.is_valid()
  8. False
  9. # The form does *not* fall back to using the initial values.
  10. >>> f.errors
  11. {'url': ['This field is required.'], 'name': ['This field is required.']}

Instead of a constant, you can also pass any callable:

  1. >>> import datetime
  2. >>> class DateForm(forms.Form):
  3. ... day = forms.DateField(initial=datetime.date.today)
  4. >>> print(DateForm())
  5. <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 whenrendering this Field. See Widgets for more information.

help_text

  • Field.help_text
  • The help_text argument lets you specify descriptive text for thisField. If you provide help_text, it will be displayed next to theField when the Field is rendered by one of the convenience Formmethods (e.g., as_ul()).

Like the model field's help_text, this valueisn't HTML-escaped in automatically-generated forms.

Here's a full example Form that implements help_text for two of itsfields. We've specified auto_id=False to simplify the output:

  1. >>> from django import forms
  2. >>> class HelpTextContactForm(forms.Form):
  3. ... subject = forms.CharField(max_length=100, help_text='100 characters max.')
  4. ... message = forms.CharField()
  5. ... sender = forms.EmailField(help_text='A valid email address, please.')
  6. ... cc_myself = forms.BooleanField(required=False)
  7. >>> f = HelpTextContactForm(auto_id=False)
  8. >>> print(f.as_table())
  9. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required><br><span class="helptext">100 characters max.</span></td></tr>
  10. <tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
  11. <tr><th>Sender:</th><td><input type="email" name="sender" required><br>A valid email address, please.</td></tr>
  12. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
  13. >>> print(f.as_ul()))
  14. <li>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></li>
  15. <li>Message: <input type="text" name="message" required></li>
  16. <li>Sender: <input type="email" name="sender" required> A valid email address, please.</li>
  17. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
  18. >>> print(f.as_p())
  19. <p>Subject: <input type="text" name="subject" maxlength="100" required> <span class="helptext">100 characters max.</span></p>
  20. <p>Message: <input type="text" name="message" required></p>
  21. <p>Sender: <input type="email" name="sender" required> A valid email address, please.</p>
  22. <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 thefield will raise. Pass in a dictionary with keys matching the error messages youwant to override. For example, here is the default error message:
  1. >>> from django import forms
  2. >>> generic = forms.CharField()
  3. >>> generic.clean('')
  4. Traceback (most recent call last):
  5. ...
  6. ValidationError: ['This field is required.']

And here is a custom error message:

  1. >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
  2. >>> name.clean('')
  3. Traceback (most recent call last):
  4. ...
  5. ValidationError: ['Please enter your name']

In the built-in Field classes section below, each Field defines theerror message keys it uses.

validators

  • Field.validators
  • The validators argument lets you provide a list of validation functionsfor this field.

See the validators documentation for more information.

localize

  • Field.localize
  • The localize argument enables the localization of form data input, as wellas the rendered output.

See the format localization documentation formore information.

disabled

  • Field.disabled
  • The disabled boolean argument, when set to True, disables a form fieldusing 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 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()[源代码]
  • The has_changed() method is used to determine if the field value has changedfrom the initial value. Returns True or False.

See the Form.has_changed() documentation for more information.

Built-in Field classes

Naturally, the forms library comes with a set of Field 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 on required above to understand what that means).

BooleanField

  • class BooleanField(**kwargs)[源代码]
    • Default widget: CheckboxInput
    • Empty value: False
    • Normalizes to: A Python True or False value.
    • Validates that the value is True (e.g. the check box is checked) ifthe field has required=True.
    • Error message keys: required

注解

Since all Field subclasses have required=True by default, thevalidation condition here is important. If you want to include a booleanin your form that can be either True or False (e.g. a checked orunchecked checkbox), you must remember to pass in required=False whencreating the BooleanField.

CharField

  • class CharField(**kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: Whatever you've given as empty_value.
    • Normalizes to: A string.
    • Uses MaxLengthValidator andMinLengthValidator if max_length andmin_length 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

    • If True (default), the value will be stripped of leading andtrailing whitespace.

    • empty_value

    • The value to use to represent "empty". Defaults to an empty string.

ChoiceField

  • class ChoiceField(**kwargs)[源代码]
    • Default widget: Select
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Validates that the given value exists in the list of choices.
    • Error message keys: required, invalid_choice
      The invalid_choice error message may contain %(value)s, which will bereplaced with the selected choice.

Takes one extra 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 the choices argument to amodel field. See the model field reference documentation onchoices for more details. If the argument is acallable, it is evaluated each time the field's form is initialized.Defaults to an empty list.

TypedChoiceField

  • class TypedChoiceField(**kwargs)[源代码]
  • Just like a ChoiceField, except TypedChoiceField takes twoextra arguments, coerce and empty_value.

    • Default widget: Select
    • Empty value: Whatever you've given as empty_value.
    • Normalizes to: A value of the type provided by the coerceargument.
    • 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-in int, 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 the coerce argument, so choose itaccordingly.

DateField

  • class DateField(**kwargs)[源代码]
    • Default widget: DateInput
    • Empty value: None
    • Normalizes to: A Python datetime.date object.
    • Validates that the given value is either a datetime.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 no input_formats argument is provided, the default input formats are:

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

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

  1. ['%b %d %Y', # 'Oct 25 2006'
  2. '%b %d, %Y', # 'Oct 25, 2006'
  3. '%d %b %Y', # '25 Oct 2006'
  4. '%d %b, %Y', # '25 Oct, 2006'
  5. '%B %d %Y', # 'October 25 2006'
  6. '%B %d, %Y', # 'October 25, 2006'
  7. '%d %B %Y', # '25 October 2006'
  8. '%d %B, %Y'] # '25 October, 2006'

See also format localization.

DateTimeField

  • class DateTimeField(**kwargs)[源代码]
    • Default widget: DateTimeInput
    • Empty value: None
    • Normalizes to: A Python datetime.datetime object.
    • Validates that the given value is either a datetime.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 no input_formats argument is provided, the default input formats are:

  1. ['%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  2. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  3. '%Y-%m-%d', # '2006-10-25'
  4. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  5. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  6. '%m/%d/%Y', # '10/25/2006'
  7. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  8. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  9. '%m/%d/%y'] # '10/25/06'

See also format localization.

DecimalField

  • class DecimalField(**kwargs)[源代码]
    • Default widget: NumberInput when Field.localize isFalse, else TextInput.
    • Empty value: None
    • Normalizes to: A Python decimal.
    • Validates that the given value is a decimal. UsesMaxValueValidator andMinValueValidator if max_value andmin_value are provided. Leading and trailing whitespace is ignored.
    • Error message keys: 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 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 as decimal.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

EmailField

  • class EmailField(**kwargs)[源代码]
    • Default widget: EmailInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Uses EmailValidator to validate thatthe given value is a valid email address, using a moderately complexregular expression.
    • Error message keys: required, invalid
      Has two optional arguments for validation, max_length and min_length.If provided, these arguments ensure that the string is at most or at least thegiven length.

FileField

  • class FileField(**kwargs)[源代码]
    • Default widget: ClearableFileInput
    • Empty value: None
    • Normalizes to: An UploadedFile 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 the UploadedFile object, see the file uploadsdocumentation.

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

The max_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

  • class FilePathField(**kwargs)[源代码]
    • Default widget: Select
    • Empty value: None
    • Normalizes to: A string.
    • 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; only path is required:

    • path

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

    • recursive

    • If False (the default) only the direct contents of path will beoffered as choices. If True, 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. Either True or False. Default is True. Specifieswhether files in the specified location should be included. Either this orallow_folders must be True.

    • allow_folders

    • Optional. Either True or False. Default is False. Specifieswhether folders in the specified location should be included. Either this orallow_files must be True.

FloatField

  • class FloatField(**kwargs)[源代码]
    • Default widget: NumberInput when Field.localize isFalse, else TextInput.
    • Empty value: None
    • Normalizes to: A Python float.
    • Validates that the given value is a float. UsesMaxValueValidator andMinValueValidator if max_value andmin_value are provided. Leading and trailing whitespace is allowed,as in Python's float() function.
    • Error message keys: 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

  • class ImageField(**kwargs)[源代码]
    • Default widget: ClearableFileInput
    • Empty value: None
    • Normalizes to: An UploadedFile object that wraps the file contentand file name into a single object.
    • Validates that file data has been bound to the form. Also usesFileExtensionValidator to validate thatthe file extension is supported by Pillow.
    • Error message keys: required, invalid, missing, empty,invalid_image
      Using an ImageField requires that Pillow is installed with supportfor the image formats you use. If you encounter a corrupt image 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 an ImageField on a form, you must also remember tobind the file data to the form.

After the field has been cleaned and validated, the UploadedFileobject will have an additional image 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 to None.

IntegerField

  • class IntegerField(**kwargs)[源代码]
    • Default widget: NumberInput when Field.localize isFalse, else TextInput.
    • Empty value: None
    • Normalizes to: A Python integer.
    • Validates that the given value is an integer. UsesMaxValueValidator andMinValueValidator if max_value andmin_value are provided. Leading and trailing whitespace is allowed,as in Python's int() function.
    • Error message keys: 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.

GenericIPAddressField

  • class GenericIPAddressField(**kwargs)[源代码]
  • A field containing either an IPv4 or an IPv6 address.

    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string. IPv6 addresses are normalized as described below.
    • Validates that the given value is a valid IP address.
    • Error message keys: 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 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 are both (default), IPv4or 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 to192.0.2.1. Default is disabled. Can only be usedwhen protocol is set to 'both'.

MultipleChoiceField

  • class MultipleChoiceField(**kwargs)[源代码]
    • Default widget: SelectMultiple
    • Empty value: [] (an empty list)
    • Normalizes to: A list of strings.
    • Validates that every value in the given list of values exists in the listof choices.
    • Error message keys: required, invalid_choice, invalid_list
      The invalid_choice error message may contain %(value)s, which will bereplaced with the selected choice.

Takes one extra required argument, choices, as for ChoiceField.

TypedMultipleChoiceField

  • class TypedMultipleChoiceField(**kwargs)[源代码]
  • Just like a MultipleChoiceField, except TypedMultipleChoiceFieldtakes two extra arguments, coerce and empty_value.

    • Default widget: SelectMultiple
    • Empty value: Whatever you've given as empty_value
    • Normalizes to: A list of values of the type provided by the coerceargument.
    • Validates that the given values exists in the list of choices and can becoerced.
    • Error message keys: required, invalid_choice
      The invalid_choice error message may contain %(value)s, which will bereplaced with the selected choice.

Takes two extra arguments, coerce and empty_value, as forTypedChoiceField.

NullBooleanField

  • class NullBooleanField(**kwargs)[源代码]
    • Default widget: NullBooleanSelect
    • Empty value: None
    • Normalizes to: A Python True, False or None value.
    • Validates nothing (i.e., it never raises a ValidationError).

RegexField

  • class RegexField(**kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Uses RegexValidator to validate thatthe given value matches a certain regular expression.
    • Error message keys: required, invalid
      Takes one required argument:

    • regex

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

Also takes max_length, min_length, and strip, which work justas they do for CharField.

  • strip
  • Defaults to False. If enabled, stripping will be applied before theregex validation.

SlugField

  • class SlugField(**kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Uses validate_slug orvalidate_unicode_slug to validate thatthe 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
  • A boolean instructing the field to accept Unicode letters in additionto ASCII letters. Defaults to False.

TimeField

  • class TimeField(**kwargs)[源代码]
    • Default widget: TimeInput
    • Empty value: None
    • Normalizes to: A Python datetime.time object.
    • Validates that the given value is either a datetime.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 no input_formats argument is provided, the default input formats are:

  1. '%H:%M:%S', # '14:30:59'
  2. '%H:%M', # '14:30'

URLField

  • class URLField(**kwargs)[源代码]
    • Default widget: URLInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Uses URLValidator to validate that thegiven value is a valid URL.
    • Error message keys: required, invalid
      Takes the following optional arguments:

    • max_length

    • min_length
    • These are the same as CharField.max_length and CharField.min_length.

UUIDField

  • class UUIDField(**kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: A UUID object.
    • Error message keys: required, invalid
      This field will accept any string format accepted as the hex argumentto the UUID constructor.

Slightly complex built-in Field classes

ComboField

  • class ComboField(**kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: A string.
    • Validates the given value against each of the fields specifiedas an argument to the ComboField.
    • 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).
  1. >>> from django.forms import ComboField
  2. >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
  3. >>> f.clean('test@example.com')
  4. 'test@example.com'
  5. >>> f.clean('longemailaddress@example.com')
  6. Traceback (most recent call last):
  7. ...
  8. ValidationError: ['Ensure this value has at most 20 characters (it has 28).']

MultiValueField

  • class MultiValueField(fields=(), **kwargs)[源代码]
    • Default widget: TextInput
    • Empty value: '' (an empty string)
    • Normalizes to: the type returned by the compress method of the subclass.
    • Validates the given value against each of the fields specifiedas an argument to the MultiValueField.
    • 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 of MultiValueField must notimplement clean() 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 in fields — 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 by compress().

Also takes some optional arguments:

  • require_all_fields
  • Defaults to True, in which case a required validation errorwill be raised if no value is supplied for any field.

When set to False, the Field.required attribute can be setto False for individual fields to make them optional. If no valueis supplied for a required field, an incomplete validation errorwill be raised.

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

  1. from django.core.validators import RegexValidator
  2.  
  3. class PhoneField(MultiValueField):
  4. def __init__(self, **kwargs):
  5. # Define one message for all fields.
  6. error_messages = {
  7. 'incomplete': 'Enter a country calling code and a phone number.',
  8. }
  9. # Or define a different message for each field.
  10. fields = (
  11. CharField(
  12. error_messages={'incomplete': 'Enter a country calling code.'},
  13. validators=[
  14. RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
  15. ],
  16. ),
  17. CharField(
  18. error_messages={'incomplete': 'Enter a phone number.'},
  19. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
  20. ),
  21. CharField(
  22. validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
  23. required=False,
  24. ),
  25. )
  26. super().__init__(
  27. error_messages=error_messages, fields=fields,
  28. require_all_fields=False, **kwargs
  29. )
  • widget
  • Must be a subclass of django.forms.MultiWidget.Default value is TextInput, whichprobably is not very useful in this case.

  • compress(data_list)[源代码]

  • 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 a datetime object.

This method must be implemented in the subclasses.

SplitDateTimeField

  • class SplitDateTimeField(**kwargs)[源代码]
    • Default widget: SplitDateTimeWidget
    • Empty value: None
    • Normalizes to: A Python datetime.datetime object.
    • Validates that the given value is a datetime.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 no input_date_formats argument is provided, the default input formatsfor DateField are used.

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

If no input_time_formats argument is provided, the default input formatsfor TimeField are used.

Fields which handle relationships

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

For more complex uses, you can specify queryset=None when declaring theform field and then populate the queryset in the form's init()method:

  1. class FooMultipleChoiceForm(forms.Form):
  2. foo_select = forms.ModelMultipleChoiceField(queryset=None)
  3.  
  4. def __init__(self, *args, **kwargs):
  5. super().__init__(*args, **kwargs)
  6. self.fields['foo_select'].queryset = ...

ModelChoiceField

  • class ModelChoiceField(**kwargs)[源代码]
    • 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 for ModelChoiceField becomesimpractical when the number of entries increases. You should avoid using itfor more than 100 items.

A single argument is required:

  • queryset
  • A QuerySet of model objects from which the choices for the fieldare derived and which is used to validate the user's selection. It'sevaluated when the form is rendered.

ModelChoiceField also takes two optional arguments:

  • empty_label
  • By default the <select> widget used by ModelChoiceField will have anempty choice at the top of the list. You can change the text of thislabel (which is "————-" by default) with the empty_labelattribute, or you can disable the empty label entirely by settingempty_label to None:
  1. # A custom empty label
  2. field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
  3.  
  4. # No empty label
  5. field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

Note that if a ModelChoiceField is required and has a defaultinitial value, no empty choice is created (regardless of the valueof empty_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 to None, in which case the primary keyof each object will be used. For example:
  1. # No custom to_field_name
  2. field1 = forms.ModelChoiceField(queryset=...)

would yield:

  1. <select id="id_field1" name="field1">
  2. <option value="obj1.pk">Object1</option>
  3. <option value="obj2.pk">Object2</option>
  4. ...
  5. </select>

and:

  1. # to_field_name provided
  2. field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")

would yield:

  1. <select id="id_field2" name="field2">
  2. <option value="obj1.name">Object1</option>
  3. <option value="obj2.name">Object2</option>
  4. ...
  5. </select>

The str() method of the model will be called to generate stringrepresentations of the objects for use in the field's choices. To providecustomized representations, subclass ModelChoiceField and overridelabel_from_instance. This method will receive a model object and shouldreturn a string suitable for representing it. For example:

  1. from django.forms import ModelChoiceField
  2.  
  3. class MyModelChoiceField(ModelChoiceField):
  4. def label_from_instance(self, obj):
  5. return "My Object #%i" % obj.id

ModelMultipleChoiceField

  • class ModelMultipleChoiceField(**kwargs)[源代码]
    • Default widget: SelectMultiple
    • Empty value: An empty QuerySet (self.queryset.none())
    • Normalizes to: A QuerySet 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
      The invalid_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 with ModelChoiceField,you can use label_from_instance to customize the objectrepresentations.

A single argument is required:

Takes one optional argument:

Creating custom fields

If the built-in Field classes don't meet your needs, you can easily createcustom Field 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().