Form fields¶
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.
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.core.exceptions.ValidationError exception or returns the cleanvalue:
>>>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(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 returnempty_value which defaults to an empty string. For otherField classes, it might beNone. (This varies from field to field.)
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.
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 inOutputting forms as HTML, 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)<div>Your name:<input type="text" name="name" required></div><div>Your website:<input type="url" name="url"></div><div>Comment:<input type="text" name="comment" required></div>
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)<div><label for="id_age">Age?</label><input type="number" name="age" required id="id_age"></div><div><label for="id_nationality">Nationality?</label><input type="text" name="nationality" required id="id_nationality"></div><div><label for="id_captcha_answer">2 + 2 =</label><input type="number" name="captcha_answer" required id="id_captcha_answer"></div>
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="https://")...comment=forms.CharField()...>>>f=CommentForm(auto_id=False)>>>print(f)<div>Name:<input type="text" name="name" value="Your name" required></div><div>Url:<input type="url" name="url" value="https://" required></div><div>Comment:<input type="text" name="comment" required></div>
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":"https://"}>>>f=CommentForm(default_data,auto_id=False)>>>print(f)<div>Name: <input type="text" name="name" value="Your name" required></div><div>Url: <ul class="errorlist"><li>Enter a valid URL.</li></ul> <input type="url" name="url" value="https://" required aria-invalid="true"></div><div>Comment: <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="comment" required aria-invalid="true"></div>
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="https://")...comment=forms.CharField()...>>>data={"name":"","url":"","comment":"Foo"}>>>f=CommentForm(data)>>>f.is_valid()False# The form does *not* fallback 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())<div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div>
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)<div>Subject:<div class="helptext">100 characters max.</div><input type="text" name="subject" maxlength="100" required></div><div>Message:<input type="text" name="message" required></div><div>Sender:<div class="helptext">A valid email address, please.</div><input type="email" name="sender" required></div><div>Cc myself:<input type="checkbox" name="cc_myself"></div>
When a field has help text it is associated with its input using thearia-describedby HTML attribute. If the widget is rendered in a<fieldset> thenaria-describedby is added to this element, otherwise itis added to the widget’s<input>:
>>>fromdjangoimportforms>>>classUserForm(forms.Form):...username=forms.CharField(max_length=255,help_text="e.g., user@example.com")...>>>f=UserForm()>>>print(f)<div><label for="id_username">Username:</label><div class="helptext" id="id_username_helptext">e.g., user@example.com</div><input type="text" name="username" maxlength="255" required aria-describedby="id_username_helptext" id="id_username"></div>
When adding a customaria-describedby attribute, make sure to also includetheid of thehelp_text element (if used) in the desired order. Forscreen reader users, descriptions will be read in their order of appearanceinsidearia-describedby:
>>>classUserForm(forms.Form):...username=forms.CharField(...max_length=255,...help_text="e.g., user@example.com",...widget=forms.TextInput(...attrs={"aria-describedby":"custom-description id_username_helptext"},...),...)...>>>f=UserForm()>>>print(f["username"])<input type="text" name="username" aria-describedby="custom-description id_username_helptext" maxlength="255" id="id_username" required>
aria-describedby was added to associatehelp_text with its input.
aria-describedby support was added for<fieldset>.
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¶
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.
template_name¶
- Field.template_name¶
Thetemplate_name argument allows a custom template to be used when thefield is rendered withas_field_group(). Bydefault this value is set to"django/forms/field.html". Can be changed perfield by overriding this attribute or more generally by overriding the defaulttemplate, see alsoOverriding built-in field templates.
Checking if the field data has changed¶
has_changed()¶
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:
CheckboxInputEmpty value:
FalseNormalizes to: A Python
TrueorFalsevalue.Validates that the value is
True(e.g. the check box is checked) ifthe field hasrequired=True.Error message keys:
required
Note
Since all
Fieldsubclasses haverequired=Trueby default, thevalidation condition here is important. If you want to include a booleanin your form that can be eitherTrueorFalse(e.g. a checked orunchecked checkbox), you must remember to pass inrequired=Falsewhencreating theBooleanField.
CharField¶
- classCharField(**kwargs)[source]¶
Default widget:
TextInputEmpty value: Whatever you’ve given as
empty_value.Normalizes to: A string.
Uses
MaxLengthValidatorandMinLengthValidatorifmax_lengthandmin_lengthare provided. Otherwise, all inputs are valid.Error message keys:
required,max_length,min_length
Has the following optional arguments for validation:
- max_length¶
- min_length¶
If provided, these arguments ensure that the string is at most or atleast the 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¶
- classChoiceField(**kwargs)[source]¶
Default widget:
SelectEmpty 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_choiceerror message may contain%(value)s, which will bereplaced with the selected choice.Takes one extra argument:
- choices[source]¶
Either aniterable of 2-tuples to use as choices for thisfield,enumeration type, or acallable that returns such an iterable. This argument accepts the sameformats as the
choicesargument to a model field. See themodel field reference documentation on choicesfor more details. If the argument is a callable, it is evaluated eachtime the field’s form is initialized, in addition to during rendering.Defaults to an empty list.
Choice type
This field normalizes choices to strings, so if choices are required inother data types, such as integers or booleans, consider using
TypedChoiceFieldinstead.Changed in Django 5.0:Support for mappings and usingenumeration types directly in
choiceswas added.
DateField¶
- classDateField(**kwargs)[source]¶
Default widget:
DateInputEmpty value:
NoneNormalizes to: A Python
datetime.dateobject.Validates that the given value is either a
datetime.date,datetime.datetimeor string formatted in a particular date format.Error message keys:
required,invalid
Takes one optional argument:
- input_formats¶
An iterable of formats used to attempt to convert a string to a valid
datetime.dateobject.
If no
input_formatsargument is provided, the default input formats aretaken from the active locale formatDATE_INPUT_FORMATSkey, or fromDATE_INPUT_FORMATSif localization is disabled. See alsoformat localization.
DateTimeField¶
- classDateTimeField(**kwargs)[source]¶
Default widget:
DateTimeInputEmpty value:
NoneNormalizes to: A Python
datetime.datetimeobject.Validates that the given value is either a
datetime.datetime,datetime.dateor string formatted in a particular datetime format.Error message keys:
required,invalid
Takes one optional argument:
- input_formats¶
An iterable of formats used to attempt to convert a string to a valid
datetime.datetimeobject, in addition to ISO 8601 formats.
The field always accepts strings in ISO 8601 formatted dates or similarrecognized by
parse_datetime(). Some examplesare:'2006-10-2514:30:59''2006-10-25T14:30:59''2006-10-2514:30''2006-10-25T14:30''2006-10-25T14:30Z''2006-10-25T14:30+02:00''2006-10-25'
If no
input_formatsargument is provided, the default input formats aretaken from the active locale formatDATETIME_INPUT_FORMATSandDATE_INPUT_FORMATSkeys, or fromDATETIME_INPUT_FORMATSandDATE_INPUT_FORMATSif localization is disabled. See alsoformat localization.
DecimalField¶
- classDecimalField(**kwargs)[source]¶
Default widget:
NumberInputwhenField.localizeisFalse, elseTextInput.Empty value:
NoneNormalizes to: A Python
decimal.Validates that the given value is a decimal. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. UsesStepValueValidatorifstep_sizeisprovided. Leading and trailing whitespace is ignored.Error message keys:
required,invalid,max_value,min_value,max_digits,max_decimal_places,max_whole_digits,step_size.
The
max_valueandmin_valueerror messages may contain%(limit_value)s, which will be substituted by the appropriate limit.Similarly, themax_digits,max_decimal_placesandmax_whole_digitserror messages may contain%(max)s.Takes five optional arguments:
- max_value¶
- min_value¶
These control the range of values permitted in the field, and should begiven as
decimal.Decimalvalues.
- 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.
- step_size¶
Limit valid inputs to an integral multiple of
step_size. Ifmin_valueis also provided, it’s added as an offset to determine ifthe step size matches.
DurationField¶
- classDurationField(**kwargs)[source]¶
Default widget:
TextInputEmpty value:
NoneNormalizes to: A Python
timedelta.Validates that the given value is a string which can be converted into a
timedelta. The value must be betweendatetime.timedelta.minanddatetime.timedelta.max.Error message keys:
required,invalid,overflow.
Accepts any format understood by
parse_duration().
EmailField¶
- classEmailField(**kwargs)[source]¶
Default widget:
EmailInputEmpty value: Whatever you’ve given as
empty_value.Normalizes to: A string.
Uses
EmailValidatorto validate thatthe given value is a valid email address, using a moderately complexregular expression.Error message keys:
required,invalid
Has the optional arguments
max_length,min_length, andempty_valuewhich work just as they do forCharField. Themax_lengthargument defaults to 320 (seeRFC 3696 Section 3).
FileField¶
- classFileField(**kwargs)[source]¶
Default widget:
ClearableFileInputEmpty value:
NoneNormalizes to: An
UploadedFileobject 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 the optional arguments for validation:
max_lengthandallow_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
UploadedFileobject, see thefile uploadsdocumentation.When you use a
FileFieldin a form, you must also remember tobind the file data to the form.The
max_lengtherror refers to the length of the filename. In the errormessage for that key,%(max)dwill be replaced with the maximum filenamelength and%(length)dwill be replaced with the current filename length.
FilePathField¶
- classFilePathField(**kwargs)[source]¶
Default widget:
SelectEmpty value:
''(an empty string)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
pathis 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 ofpathwill 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. Either
TrueorFalse. Default isTrue. Specifieswhether files in the specified location should be included. Either this orallow_foldersmust beTrue.
- allow_folders¶
Optional. Either
TrueorFalse. Default isFalse. Specifieswhether folders in the specified location should be included. Either this orallow_filesmust beTrue.
FloatField¶
- classFloatField(**kwargs)[source]¶
Default widget:
NumberInputwhenField.localizeisFalse, elseTextInput.Empty value:
NoneNormalizes to: A Python float.
Validates that the given value is a float. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. UsesStepValueValidatorifstep_sizeisprovided. Leading and trailing whitespace is allowed, as in Python’sfloat()function.Error message keys:
required,invalid,max_value,min_value,step_size.
Takes three optional arguments:
- max_value¶
- min_value¶
These control the range of values permitted in the field.
- step_size¶
Limit valid inputs to an integral multiple of
step_size. Ifmin_valueis also provided, it’s added as an offset to determine ifthe step size matches.
GenericIPAddressField¶
- classGenericIPAddressField(**kwargs)[source]¶
A field containing either an IPv4 or an IPv6 address.
Default widget:
TextInputEmpty 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,max_length
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:01would be normalized to2001::1, and::ffff:0a0a:0a0ato::ffff:10.10.10.10. All charactersare converted to lowercase.Takes three optional arguments:
- protocol¶
Limits valid inputs to the specified protocol.Accepted values are
both(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 usedwhenprotocolis set to'both'.
Changed in Django 4.2.18:The default value for
max_lengthwas set to 39 characters.
ImageField¶
- classImageField(**kwargs)[source]¶
Default widget:
ClearableFileInputEmpty value:
NoneNormalizes to: An
UploadedFileobject that wraps the file contentand file name into a single object.Validates that file data has been bound to the form. Also uses
FileExtensionValidatorto validate thatthe file extension is supported by Pillow.Error message keys:
required,invalid,missing,empty,invalid_image
Using an
ImageFieldrequires thatpillow is installed withsupport for the image formats you use. If you encounter acorruptimageerror when you upload an image, it usually means that Pillow doesn’tunderstand its format. To fix this, install the appropriate library andreinstall Pillow.When you use an
ImageFieldon 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 additionalimageattribute containing the PillowImage instance used to check if the file was a valid image. Pillowcloses the underlying file descriptor after verifying an image, so whilenon-image data attributes, such asformat,height, andwidth,are available, methods that access the underlying image data, such asgetdata()orgetpixel(), cannot be used without reopening the file.For example:>>>fromPILimportImage>>>fromdjangoimportforms>>>fromdjango.core.files.uploadedfileimportSimpleUploadedFile>>>classImageForm(forms.Form):...img=forms.ImageField()...>>>file_data={"img":SimpleUploadedFile("test.png",b"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.width191>>>image_field.image.height287>>>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_typewill be updated with theimage’s content type if Pillow can determine it, otherwise it will be settoNone.
IntegerField¶
- classIntegerField(**kwargs)[source]¶
Default widget:
NumberInputwhenField.localizeisFalse, elseTextInput.Empty value:
NoneNormalizes to: A Python integer.
Validates that the given value is an integer. Uses
MaxValueValidatorandMinValueValidatorifmax_valueandmin_valueare provided. UsesStepValueValidatorifstep_sizeisprovided. Leading and trailing whitespace is allowed, as in Python’sint()function.Error message keys:
required,invalid,max_value,min_value,step_size
The
max_value,min_valueandstep_sizeerror messages maycontain%(limit_value)s, which will be substituted by the appropriatelimit.Takes three optional arguments for validation:
- max_value¶
- min_value¶
These control the range of values permitted in the field.
- step_size¶
Limit valid inputs to an integral multiple of
step_size. Ifmin_valueis also provided, it’s added as an offset to determine ifthe step size matches.
JSONField¶
- classJSONField(encoder=None,decoder=None,**kwargs)[source]¶
A field which accepts JSON encoded data for a
JSONField.Default widget:
TextareaEmpty value:
NoneNormalizes to: A Python representation of the JSON value (usually as a
dict,list, orNone), depending onJSONField.decoder.Validates that the given value is a valid JSON.
Error message keys:
required,invalid
Takes two optional arguments:
- encoder¶
A
json.JSONEncodersubclass to serialize data types notsupported by the standard JSON serializer (e.g.datetime.datetimeorUUID). For example, you can use theDjangoJSONEncoderclass.Defaults to
json.JSONEncoder.
- decoder¶
A
json.JSONDecodersubclass to deserialize the input. Yourdeserialization may need to account for the fact that you can’t becertain of the input type. For example, you run the risk of returning adatetimethat was actually a string that just happened to be in thesame format chosen fordatetimes.The
decodercan be used to validate the input. Ifjson.JSONDecodeErroris raised during the deserialization,aValidationErrorwill be raised.Defaults to
json.JSONDecoder.
User friendly forms
JSONFieldis not particularly user friendly in most cases. However,it is a useful way to format data from a client-side widget forsubmission to the server.
MultipleChoiceField¶
- classMultipleChoiceField(**kwargs)[source]¶
Default widget:
SelectMultipleEmpty 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_choiceerror message may contain%(value)s, which will bereplaced with the selected choice.Takes one extra required argument,
choices, as forChoiceField.
NullBooleanField¶
- classNullBooleanField(**kwargs)[source]¶
Default widget:
NullBooleanSelectEmpty value:
NoneNormalizes to: A Python
True,FalseorNonevalue.Validates nothing (i.e., it never raises a
ValidationError).
NullBooleanFieldmay be used with widgets such asSelectorRadioSelectby providing the widgetchoices:NullBooleanField(widget=Select(choices=[("","Unknown"),(True,"Yes"),(False,"No"),]))
RegexField¶
- classRegexField(**kwargs)[source]¶
Default widget:
TextInputEmpty value: Whatever you’ve given as
empty_value.Normalizes to: A string.
Uses
RegexValidatorto 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,strip, andempty_valuewhich work just as they do forCharField.- strip¶
Defaults to
False. If enabled, stripping will be applied before theregex validation.
SlugField¶
- classSlugField(**kwargs)[source]¶
Default widget:
TextInputEmpty value: Whatever you’ve given as
empty_value.Normalizes to: A string.
Uses
validate_slugorvalidate_unicode_slugto validate thatthe given value contains only letters, numbers, underscores, and hyphens.Error messages:
required,invalid
This field is intended for use in representing a model
SlugFieldin forms.Takes two optional parameters:
- allow_unicode¶
A boolean instructing the field to accept Unicode letters in additionto ASCII letters. Defaults to
False.
- empty_value¶
The value to use to represent “empty”. Defaults to an empty string.
TimeField¶
- classTimeField(**kwargs)[source]¶
Default widget:
TimeInputEmpty value:
NoneNormalizes to: A Python
datetime.timeobject.Validates that the given value is either a
datetime.timeor stringformatted in a particular time format.Error message keys:
required,invalid
Takes one optional argument:
- input_formats¶
An iterable of formats used to attempt to convert a string to a valid
datetime.timeobject.
If no
input_formatsargument is provided, the default input formats aretaken from the active locale formatTIME_INPUT_FORMATSkey, or fromTIME_INPUT_FORMATSif localization is disabled. See alsoformat localization.
TypedChoiceField¶
- classTypedChoiceField(**kwargs)[source]¶
Just like a
ChoiceField, exceptTypedChoiceFieldtakes twoextra arguments,coerceandempty_value.Default widget:
SelectEmpty 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,booland 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;
Noneis another common choice here. Note that this value will not becoerced by the function given in thecoerceargument, so choose itaccordingly.
TypedMultipleChoiceField¶
- classTypedMultipleChoiceField(**kwargs)[source]¶
Just like a
MultipleChoiceField, exceptTypedMultipleChoiceFieldtakes two extra arguments,coerceandempty_value.Default widget:
SelectMultipleEmpty value: Whatever you’ve given as
empty_valueNormalizes 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_choiceerror message may contain%(value)s, which will bereplaced with the selected choice.Takes two extra arguments,
coerceandempty_value, as forTypedChoiceField.
URLField¶
- classURLField(**kwargs)[source]¶
Default widget:
URLInputEmpty value: Whatever you’ve given as
empty_value.Normalizes to: A string.
Uses
URLValidatorto validate that thegiven value is a valid URL.Error message keys:
required,invalid
Has the optional arguments
max_length,min_length,empty_valuewhich work just as they do forCharField, and one more argument:- assume_scheme¶
- New in Django 5.0.
The scheme assumed for URLs provided without one. Defaults to
"http". For example, ifassume_schemeis"https"and theprovided value is"example.com", the normalized value will be"https://example.com".
Deprecated since version 5.0:The default value for
assume_schemewill change from"http"to"https"in Django 6.0. SetFORMS_URLFIELD_ASSUME_HTTPStransitional setting toTrueto opt into using"https"duringthe Django 5.x release cycle.
UUIDField¶
Slightly complex built-inField classes¶
ComboField¶
- classComboField(**kwargs)[source]¶
Default widget:
TextInputEmpty 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).
>>>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:
TextInputEmpty value:
''(an empty string)Normalizes to: the type returned by the
compressmethod 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
MultiValueFieldmust 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 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 bycompress().
Also takes some optional arguments:
- require_all_fields¶
Defaults to
True, in which case arequiredvalidation errorwill be raised if no value is supplied for any field.When set to
False, theField.requiredattribute can be settoFalsefor individual fields to make them optional. If no valueis supplied for a required field, anincompletevalidation errorwill be raised.A default
incompleteerror message can be defined on theMultiValueFieldsubclass, or different messages can be definedon each individual field. For example:fromdjango.core.validatorsimportRegexValidatorclassPhoneField(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 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,
SplitDateTimeFieldis a subclass which combines a time fieldand a date field into adatetimeobject.This method must be implemented in the subclasses.
SplitDateTimeField¶
- classSplitDateTimeField(**kwargs)[source]¶
Default widget:
SplitDateTimeWidgetEmpty value:
NoneNormalizes to: A Python
datetime.datetimeobject.Validates that the given value is a
datetime.datetimeor 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 valid
datetime.dateobject.
If no
input_date_formatsargument is provided, the default input formatsforDateFieldare used.- input_time_formats¶
A list of formats used to attempt to convert a string to a valid
datetime.timeobject.
If no
input_time_formatsargument is provided, the default input formatsforTimeFieldare 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().__init__(*args,**kwargs)self.fields["foo_select"].queryset=...
BothModelChoiceField andModelMultipleChoiceField have aniteratorattribute which specifies the class used to iterate over the queryset whengenerating choices. SeeIterating relationship choices for details.
ModelChoiceField¶
- classModelChoiceField(**kwargs)[source]¶
Default widget:
SelectEmpty value:
NoneNormalizes to: A model instance.
Validates that the given id exists in the queryset.
Error message keys:
required,invalid_choice
The
invalid_choiceerror message may contain%(value)s, which willbe replaced with the selected choice.Allows the selection of a single model object, suitable for representing aforeign key. Note that the default widget for
ModelChoiceFieldbecomesimpractical when the number of entries increases. You should avoid using itfor more than 100 items.A single argument is required:
- queryset¶
A
QuerySetof 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.
ModelChoiceFieldalso takes several optional arguments:- empty_label¶
By default the
<select>widget used byModelChoiceFieldwill 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_labeltoNone:# A custom empty labelfield1=forms.ModelChoiceField(queryset=...,empty_label="(Nothing)")# No empty labelfield2=forms.ModelChoiceField(queryset=...,empty_label=None)
Note that no empty choice is created (regardless of the value of
empty_label) if aModelChoiceFieldis required and has adefault initial value, or awidgetis set toRadioSelectand theblankargument isFalse.
- 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:# 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>
- blank¶
When using the
RadioSelectwidget, this optionalboolean argument determines whether an empty choice is created. Bydefault,blankisFalse, in which case no empty choice iscreated.
ModelChoiceFieldalso has the attribute:- iterator¶
The iterator class used to generate field choices from
queryset. Bydefault,ModelChoiceIterator.
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, subclassModelChoiceFieldand overridelabel_from_instance. This method will receive a model object and shouldreturn a string suitable for representing it. For example:fromdjango.formsimportModelChoiceFieldclassMyModelChoiceField(ModelChoiceField):deflabel_from_instance(self,obj):return"My Object #%i"%obj.id
ModelMultipleChoiceField¶
- classModelMultipleChoiceField(**kwargs)[source]¶
Default widget:
SelectMultipleEmpty value: An empty
QuerySet(self.queryset.none())Normalizes to: A
QuerySetof model instances.Validates that every id in the given list of values exists in thequeryset.
Error message keys:
required,invalid_list,invalid_choice,invalid_pk_value
The
invalid_choicemessage may contain%(value)sand theinvalid_pk_valuemessage 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 uselabel_from_instanceto customize the objectrepresentations.A single argument is required:
- queryset¶
Same as
ModelChoiceField.queryset.
Takes one optional argument:
- to_field_name¶
Same as
ModelChoiceField.to_field_name.
ModelMultipleChoiceFieldalso has the attribute:- iterator¶
Same as
ModelChoiceField.iterator.
Iterating relationship choices¶
By default,ModelChoiceField andModelMultipleChoiceField useModelChoiceIterator to generate their fieldchoices.
When iterated,ModelChoiceIterator yields 2-tuple choices containingModelChoiceIteratorValue instances as the firstvalue element ineach choice.ModelChoiceIteratorValue wraps the choice value whilemaintaining a reference to the source model instance that can be used in customwidget implementations, for example, to adddata-* attributes to<option> elements.
For example, consider the following models:
fromdjango.dbimportmodelsclassTopping(models.Model):name=models.CharField(max_length=100)price=models.DecimalField(decimal_places=2,max_digits=6)def__str__(self):returnself.nameclassPizza(models.Model):topping=models.ForeignKey(Topping,on_delete=models.CASCADE)
You can use aSelect widget subclass to includethe value ofTopping.price as the HTML attributedata-price for each<option> element:
fromdjangoimportformsclassToppingSelect(forms.Select):defcreate_option(self,name,value,label,selected,index,subindex=None,attrs=None):option=super().create_option(name,value,label,selected,index,subindex,attrs)ifvalue:option["attrs"]["data-price"]=value.instance.pricereturnoptionclassPizzaForm(forms.ModelForm):classMeta:model=Pizzafields=["topping"]widgets={"topping":ToppingSelect}
This will render thePizza.topping select as:
<selectid="id_topping"name="topping"required><optionvalue=""selected>---------</option><optionvalue="1"data-price="1.50">mushrooms</option><optionvalue="2"data-price="1.25">onions</option><optionvalue="3"data-price="1.75">peppers</option><optionvalue="4"data-price="2.00">pineapple</option></select>
For more advanced usage you may subclassModelChoiceIterator in order tocustomize the yielded 2-tuple choices.
ModelChoiceIterator¶
- classModelChoiceIterator(field)[source]¶
The default class assigned to the
iteratorattribute ofModelChoiceFieldandModelMultipleChoiceField. Aniterable that yields 2-tuple choices from the queryset.A single argument is required:
- field¶
The instance of
ModelChoiceFieldorModelMultipleChoiceFieldtoiterate and yield choices.
ModelChoiceIteratorhas the following method:- __iter__()[source]¶
Yields 2-tuple choices, in the
(value,label)format used byChoiceField.choices. The firstvalueelement is aModelChoiceIteratorValueinstance.
ModelChoiceIteratorValue¶
- classModelChoiceIteratorValue(value,instance)[source]¶
Two arguments are required:
- value¶
The value of the choice. This value is used to render the
valueattribute of an HTML<option>element.
- instance¶
The model instance from the queryset. The instance can be accessed incustom
ChoiceWidget.create_option()implementations to adjust therendered HTML.
ModelChoiceIteratorValuehas the following method:
Creating custom fields¶
If the built-inField classes don’t meet your needs, you can create customField classes. To do this, create a subclass ofdjango.forms.Field. Itsonly requirements are that it implement aclean() 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 overridingget_bound_field().

