doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
Form.clean() | django.ref.forms.api#django.forms.Form.clean |
Form.cleaned_data | django.ref.forms.api#django.forms.Form.cleaned_data |
Form.default_renderer | django.ref.forms.api#django.forms.Form.default_renderer |
Form.error_css_class | django.ref.forms.api#django.forms.Form.error_css_class |
Form.errors | django.ref.forms.api#django.forms.Form.errors |
Form.errors.as_data() | django.ref.forms.api#django.forms.Form.errors.as_data |
Form.errors.as_json(escape_html=False) | django.ref.forms.api#django.forms.Form.errors.as_json |
Form.errors.get_json_data(escape_html=False) | django.ref.forms.api#django.forms.Form.errors.get_json_data |
Form.field_order | django.ref.forms.api#django.forms.Form.field_order |
Form.fields | django.ref.forms.api#django.forms.Form.fields |
Form.get_context() | django.ref.forms.api#django.forms.Form.get_context |
Form.get_initial_for_field(field, field_name) | django.ref.forms.api#django.forms.Form.get_initial_for_field |
Form.has_changed() | django.ref.forms.api#django.forms.Form.has_changed |
Form.has_error(field, code=None) | django.ref.forms.api#django.forms.Form.has_error |
Form.initial | django.ref.forms.api#django.forms.Form.initial |
Form.is_bound | django.ref.forms.api#django.forms.Form.is_bound |
Form.is_multipart() | django.ref.forms.api#django.forms.Form.is_multipart |
Form.is_valid() | django.ref.forms.api#django.forms.Form.is_valid |
Form.label_suffix | django.ref.forms.api#django.forms.Form.label_suffix |
Form.non_field_errors() | django.ref.forms.api#django.forms.Form.non_field_errors |
Form.order_fields(field_order) | django.ref.forms.api#django.forms.Form.order_fields |
Form.prefix | django.ref.forms.api#django.forms.Form.prefix |
Form.render(template_name=None, context=None, renderer=None) | django.ref.forms.api#django.forms.Form.render |
Form.required_css_class | django.ref.forms.api#django.forms.Form.required_css_class |
Form.template_name | django.ref.forms.api#django.forms.Form.template_name |
Form.template_name_label | django.ref.forms.api#django.forms.Form.template_name_label |
Form.use_required_attribute | django.ref.forms.api#django.forms.Form.use_required_attribute |
class BaseFormSet | django.topics.forms.formsets#django.forms.formsets.BaseFormSet |
BaseFormSet.as_p()
Renders the formset with the template_name_p template. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.as_p |
BaseFormSet.as_table()
Renders the formset with the template_name_table template. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.as_table |
BaseFormSet.as_ul()
Renders the formset with the template_name_ul template. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.as_ul |
BaseFormSet.can_delete | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.can_delete |
BaseFormSet.can_delete_extra | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.can_delete_extra |
BaseFormSet.can_order | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.can_order |
BaseFormSet.deletion_widget | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.deletion_widget |
BaseFormSet.get_context()
New in Django 4.0. Returns the context for rendering a formset in a template. The available context is:
formset : The instance of the formset. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.get_context |
BaseFormSet.get_deletion_widget() | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.get_deletion_widget |
BaseFormSet.get_ordering_widget() | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.get_ordering_widget |
BaseFormSet.ordering_widget | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.ordering_widget |
BaseFormSet.render(template_name=None, context=None, renderer=None)
New in Django 4.0. The render method is called by __str__ as well as the as_p(), as_ul(), and as_table() methods. All arguments are optional and will default to:
template_name: template_name
context: Value returned by get_context()
renderer: Value returned by renderer | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.render |
BaseFormSet.renderer
New in Django 4.0. Specifies the renderer to use for the formset. Defaults to the renderer specified by the FORM_RENDERER setting. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.renderer |
BaseFormSet.template_name
New in Django 4.0. The name of the template used when calling __str__ or render(). This template renders the formset’s management form and then each form in the formset as per the template defined by the form’s template_name. This is a proxy of as_table by default. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.template_name |
BaseFormSet.template_name_p
New in Django 4.0. The name of the template used when calling as_p(). By default this is 'django/forms/formsets/p.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_p() method. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.template_name_p |
BaseFormSet.template_name_table
New in Django 4.0. The name of the template used when calling as_table(). By default this is 'django/forms/formsets/table.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_table() method. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.template_name_table |
BaseFormSet.template_name_ul
New in Django 4.0. The name of the template used when calling as_ul(). By default this is 'django/forms/formsets/ul.html'. This template renders the formset’s management form and then each form in the formset as per the form’s as_ul() method. | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.template_name_ul |
BaseFormSet.total_error_count() | django.topics.forms.formsets#django.forms.formsets.BaseFormSet.total_error_count |
formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True, renderer=None)
Returns a FormSet class for the given form class. See formsets for example usage. Changed in Django 3.2: The absolute_max and can_delete_extra arguments were added. Changed in Django 4.0: The renderer argument was added. | django.ref.forms.formsets#django.forms.formsets.formset_factory |
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 to 2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All characters are converted to lowercase. Takes two optional arguments:
protocol
Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive.
unpack_ipv4
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. | django.ref.forms.fields#django.forms.GenericIPAddressField |
protocol
Limits valid inputs to the specified protocol. Accepted values are both (default), IPv4 or IPv6. Matching is case insensitive. | django.ref.forms.fields#django.forms.GenericIPAddressField.protocol |
unpack_ipv4
Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. | django.ref.forms.fields#django.forms.GenericIPAddressField.unpack_ipv4 |
class HiddenInput
input_type: 'hidden'
template_name: 'django/forms/widgets/hidden.html'
Renders as: <input type="hidden" ...>
Note that there also is a MultipleHiddenInput widget that encapsulates a set of hidden input elements. | django.ref.forms.widgets#django.forms.HiddenInput |
class ImageField(**kwargs)
Default widget: ClearableFileInput
Empty value: None
Normalizes to: An UploadedFile object that wraps the file content and file name into a single object. Validates that file data has been bound to the form. Also uses FileExtensionValidator to validate that the file extension is supported by Pillow. Error message keys: required, invalid, missing, empty, invalid_image
Using an ImageField requires that Pillow is installed with support for the image formats you use. If you encounter a corrupt image error when you upload an image, it usually means that Pillow doesn’t understand its format. To fix this, install the appropriate library and reinstall Pillow. When you use an ImageField on a form, you must also remember to bind the file data to the form. After the field has been cleaned and validated, the UploadedFile object will have an additional image attribute containing the Pillow Image instance used to check if the file was a valid image. Pillow closes the underlying file descriptor after verifying an image, so while non-image data attributes, such as format, height, and width, are available, methods that access the underlying image data, such as getdata() or getpixel(), cannot be used without reopening the file. For example: >>> from PIL import Image
>>> from django import forms
>>> from django.core.files.uploadedfile import SimpleUploadedFile
>>> class ImageForm(forms.Form):
... img = forms.ImageField()
>>> file_data = {'img': SimpleUploadedFile('test.png', <file data>)}
>>> form = ImageForm({}, file_data)
# Pillow closes the underlying file descriptor.
>>> form.is_valid()
True
>>> image_field = form.cleaned_data['img']
>>> image_field.image
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>
>>> image_field.image.width
191
>>> image_field.image.height
287
>>> image_field.image.format
'PNG'
>>> image_field.image.getdata()
# Raises AttributeError: 'NoneType' object has no attribute 'seek'.
>>> image = Image.open(image_field)
>>> image.getdata()
<ImagingCore object at 0x7f5984f874b0>
Additionally, UploadedFile.content_type will be updated with the image’s content type if Pillow can determine it, otherwise it will be set to None. | django.ref.forms.fields#django.forms.ImageField |
class IntegerField(**kwargs)
Default widget: NumberInput when Field.localize is False, else TextInput. Empty value: None
Normalizes to: A Python integer. Validates that the given value is an integer. Uses MaxValueValidator and MinValueValidator if max_value and min_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. | django.ref.forms.fields#django.forms.IntegerField |
max_value | django.ref.forms.fields#django.forms.IntegerField.max_value |
min_value
These control the range of values permitted in the field. | django.ref.forms.fields#django.forms.IntegerField.min_value |
class JSONField(encoder=None, decoder=None, **kwargs)
A field which accepts JSON encoded data for a JSONField. Default widget: Textarea
Empty value: None
Normalizes to: A Python representation of the JSON value (usually as a dict, list, or None), depending on JSONField.decoder. Validates that the given value is a valid JSON. Error message keys: required, invalid
Takes two optional arguments:
encoder
A json.JSONEncoder subclass to serialize data types not supported by the standard JSON serializer (e.g. datetime.datetime or UUID). For example, you can use the DjangoJSONEncoder class. Defaults to json.JSONEncoder.
decoder
A json.JSONDecoder subclass to deserialize the input. Your deserialization may need to account for the fact that you can’t be certain of the input type. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes. The decoder can be used to validate the input. If json.JSONDecodeError is raised during the deserialization, a ValidationError will be raised. Defaults to json.JSONDecoder.
Note If you use a ModelForm, the encoder and decoder from JSONField will be used. User friendly forms JSONField is not particularly user friendly in most cases. However, it is a useful way to format data from a client-side widget for submission to the server. | django.ref.forms.fields#django.forms.JSONField |
decoder
A json.JSONDecoder subclass to deserialize the input. Your deserialization may need to account for the fact that you can’t be certain of the input type. For example, you run the risk of returning a datetime that was actually a string that just happened to be in the same format chosen for datetimes. The decoder can be used to validate the input. If json.JSONDecodeError is raised during the deserialization, a ValidationError will be raised. Defaults to json.JSONDecoder. | django.ref.forms.fields#django.forms.JSONField.decoder |
encoder
A json.JSONEncoder subclass to serialize data types not supported by the standard JSON serializer (e.g. datetime.datetime or UUID). For example, you can use the DjangoJSONEncoder class. Defaults to json.JSONEncoder. | django.ref.forms.fields#django.forms.JSONField.encoder |
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
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice. Allows the selection of a single model object, suitable for representing a foreign key. Note that the default widget for ModelChoiceField becomes impractical when the number of entries increases. You should avoid using it for more than 100 items. A single argument is required:
queryset
A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered.
ModelChoiceField also takes two optional arguments:
empty_label
By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None: # A custom empty label
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
# No empty label
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label).
to_field_name
This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to None, in which case the primary key of each object will be used. For example: # No custom to_field_name
field1 = forms.ModelChoiceField(queryset=...)
would yield: <select id="id_field1" name="field1">
<option value="obj1.pk">Object1</option>
<option value="obj2.pk">Object2</option>
...
</select>
and: # to_field_name provided
field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
would yield: <select id="id_field2" name="field2">
<option value="obj1.name">Object1</option>
<option value="obj2.name">Object2</option>
...
</select>
ModelChoiceField also has the attribute:
iterator
The iterator class used to generate field choices from queryset. By default, ModelChoiceIterator.
The __str__() method of the model will be called to generate string representations of the objects for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object and should return a string suitable for representing it. For example: from django.forms import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "My Object #%i" % obj.id
Changed in Django 4.0: Support for containing %(value)s in the invalid_choice error message was added. | django.ref.forms.fields#django.forms.ModelChoiceField |
empty_label
By default the <select> widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None: # A custom empty label
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")
# No empty label
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)
Note that if a ModelChoiceField is required and has a default initial value, no empty choice is created (regardless of the value of empty_label). | django.ref.forms.fields#django.forms.ModelChoiceField.empty_label |
iterator
The iterator class used to generate field choices from queryset. By default, ModelChoiceIterator. | django.ref.forms.fields#django.forms.ModelChoiceField.iterator |
queryset
A QuerySet of model objects from which the choices for the field are derived and which is used to validate the user’s selection. It’s evaluated when the form is rendered. | django.ref.forms.fields#django.forms.ModelChoiceField.queryset |
to_field_name
This optional argument is used to specify the field to use as the value of the choices in the field’s widget. Be sure it’s a unique field for the model, otherwise the selected value could match more than one object. By default it is set to None, in which case the primary key of each object will be used. For example: # No custom to_field_name
field1 = forms.ModelChoiceField(queryset=...)
would yield: <select id="id_field1" name="field1">
<option value="obj1.pk">Object1</option>
<option value="obj2.pk">Object2</option>
...
</select>
and: # to_field_name provided
field2 = forms.ModelChoiceField(queryset=..., to_field_name="name")
would yield: <select id="id_field2" name="field2">
<option value="obj1.name">Object1</option>
<option value="obj2.name">Object2</option>
...
</select> | django.ref.forms.fields#django.forms.ModelChoiceField.to_field_name |
class ModelChoiceIterator(field)
The default class assigned to the iterator attribute of ModelChoiceField and ModelMultipleChoiceField. An iterable that yields 2-tuple choices from the queryset. A single argument is required:
field
The instance of ModelChoiceField or ModelMultipleChoiceField to iterate and yield choices.
ModelChoiceIterator has the following method:
__iter__()
Yields 2-tuple choices, in the (value, label) format used by ChoiceField.choices. The first value element is a ModelChoiceIteratorValue instance. | django.ref.forms.fields#django.forms.ModelChoiceIterator |
__iter__()
Yields 2-tuple choices, in the (value, label) format used by ChoiceField.choices. The first value element is a ModelChoiceIteratorValue instance. | django.ref.forms.fields#django.forms.ModelChoiceIterator.__iter__ |
field
The instance of ModelChoiceField or ModelMultipleChoiceField to iterate and yield choices. | django.ref.forms.fields#django.forms.ModelChoiceIterator.field |
class ModelChoiceIteratorValue(value, instance)
Two arguments are required:
value
The value of the choice. This value is used to render the value attribute of an HTML <option> element.
instance
The model instance from the queryset. The instance can be accessed in custom ChoiceWidget.create_option() implementations to adjust the rendered HTML.
ModelChoiceIteratorValue has the following method:
__str__()
Return value as a string to be rendered in HTML. | django.ref.forms.fields#django.forms.ModelChoiceIteratorValue |
__str__()
Return value as a string to be rendered in HTML. | django.ref.forms.fields#django.forms.ModelChoiceIteratorValue.__str__ |
instance
The model instance from the queryset. The instance can be accessed in custom ChoiceWidget.create_option() implementations to adjust the rendered HTML. | django.ref.forms.fields#django.forms.ModelChoiceIteratorValue.instance |
value
The value of the choice. This value is used to render the value attribute of an HTML <option> element. | django.ref.forms.fields#django.forms.ModelChoiceIteratorValue.value |
class ModelForm | django.topics.forms.modelforms#django.forms.ModelForm |
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 the queryset. Error message keys: required, invalid_list, invalid_choice, invalid_pk_value
The invalid_choice message may contain %(value)s and the invalid_pk_value message may contain %(pk)s, which will be substituted by the appropriate values. Allows the selection of one or more model objects, suitable for representing a many-to-many relation. As with ModelChoiceField, you can use label_from_instance to customize the object representations. A single argument is required:
queryset
Same as ModelChoiceField.queryset.
Takes one optional argument:
to_field_name
Same as ModelChoiceField.to_field_name.
ModelMultipleChoiceField also has the attribute:
iterator
Same as ModelChoiceField.iterator. | django.ref.forms.fields#django.forms.ModelMultipleChoiceField |
iterator
Same as ModelChoiceField.iterator. | django.ref.forms.fields#django.forms.ModelMultipleChoiceField.iterator |
queryset
Same as ModelChoiceField.queryset. | django.ref.forms.fields#django.forms.ModelMultipleChoiceField.queryset |
to_field_name
Same as ModelChoiceField.to_field_name. | django.ref.forms.fields#django.forms.ModelMultipleChoiceField.to_field_name |
class models.BaseInlineFormSet | django.topics.forms.modelforms#django.forms.models.BaseInlineFormSet |
class models.BaseModelFormSet | django.topics.forms.modelforms#django.forms.models.BaseModelFormSet |
models.BaseModelFormSet.changed_objects | django.topics.forms.modelforms#django.forms.models.BaseModelFormSet.changed_objects |
models.BaseModelFormSet.deleted_objects | django.topics.forms.modelforms#django.forms.models.BaseModelFormSet.deleted_objects |
models.BaseModelFormSet.new_objects | django.topics.forms.modelforms#django.forms.models.BaseModelFormSet.new_objects |
inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None)
Returns an InlineFormSet using modelformset_factory() with defaults of formset=BaseInlineFormSet, can_delete=True, and extra=3. If your model has more than one ForeignKey to the parent_model, you must specify a fk_name. See Inline formsets for example usage. Changed in Django 3.2: The absolute_max and can_delete_extra arguments were added. Changed in Django 4.0: The renderer argument was added. | django.ref.forms.models#django.forms.models.inlineformset_factory |
modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None)
Returns a ModelForm class for the given model. You can optionally pass a form argument to use as a starting point for constructing the ModelForm. fields is an optional list of field names. If provided, only the named fields will be included in the returned fields. exclude is an optional list of field names. If provided, the named fields will be excluded from the returned fields, even if they are listed in the fields argument. formfield_callback is a callable that takes a model field and returns a form field. widgets is a dictionary of model field names mapped to a widget. localized_fields is a list of names of fields which should be localized. labels is a dictionary of model field names mapped to a label. help_texts is a dictionary of model field names mapped to a help text. error_messages is a dictionary of model field names mapped to a dictionary of error messages. field_classes is a dictionary of model field names mapped to a form field class. See ModelForm factory function for example usage. You must provide the list of fields explicitly, either via keyword arguments fields or exclude, or the corresponding attributes on the form’s inner Meta class. See Selecting the fields to use for more information. Omitting any definition of the fields to use will result in an ImproperlyConfigured exception. | django.ref.forms.models#django.forms.models.modelform_factory |
modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None)
Returns a FormSet class for the given model class. Arguments model, form, fields, exclude, formfield_callback, widgets, localized_fields, labels, help_texts, error_messages, and field_classes are all passed through to modelform_factory(). Arguments formset, extra, can_delete, can_order, max_num, validate_max, min_num, validate_min, absolute_max, can_delete_extra, and renderer are passed through to formset_factory(). See formsets for details. See Model formsets for example usage. Changed in Django 3.2: The absolute_max and can_delete_extra arguments were added. Changed in Django 4.0: The renderer argument was added. | django.ref.forms.models#django.forms.models.modelformset_factory |
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 list of choices. Error message keys: required, invalid_choice, invalid_list
The invalid_choice error message may contain %(value)s, which will be replaced with the selected choice. Takes one extra required argument, choices, as for ChoiceField. | django.ref.forms.fields#django.forms.MultipleChoiceField |
class MultipleHiddenInput
template_name: 'django/forms/widgets/multiple_hidden.html'
Renders as: multiple <input type="hidden" ...> tags A widget that handles multiple hidden widgets for fields that have a list of values. | django.ref.forms.widgets#django.forms.MultipleHiddenInput |
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 specified as an argument to the MultiValueField. Error message keys: required, invalid, incomplete
Aggregates the logic of multiple fields that together produce a single value. This field is abstract and must be subclassed. In contrast with the single-value fields, subclasses of MultiValueField must not implement clean() but instead - implement compress(). Takes one extra required argument:
fields
A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in fields – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value by compress().
Also takes some optional arguments:
require_all_fields
Defaults to True, in which case a required validation error will be raised if no value is supplied for any field. When set to False, the Field.required attribute can be set to False for individual fields to make them optional. If no value is supplied for a required field, an incomplete validation error will be raised. A default incomplete error message can be defined on the MultiValueField subclass, or different messages can be defined on each individual field. For example: from django.core.validators import RegexValidator
class PhoneField(MultiValueField):
def __init__(self, **kwargs):
# Define one message for all fields.
error_messages = {
'incomplete': 'Enter a country calling code and a phone number.',
}
# Or define a different message for each field.
fields = (
CharField(
error_messages={'incomplete': 'Enter a country calling code.'},
validators=[
RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
],
),
CharField(
error_messages={'incomplete': 'Enter a phone number.'},
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
),
CharField(
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
required=False,
),
)
super().__init__(
error_messages=error_messages, fields=fields,
require_all_fields=False, **kwargs
)
widget
Must be a subclass of django.forms.MultiWidget. Default value is TextInput, which probably is not very useful in this case.
compress(data_list)
Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example, SplitDateTimeField is a subclass which combines a time field and a date field into a datetime object. This method must be implemented in the subclasses. | django.ref.forms.fields#django.forms.MultiValueField |
compress(data_list)
Takes a list of valid values and returns a “compressed” version of those values – in a single value. For example, SplitDateTimeField is a subclass which combines a time field and a date field into a datetime object. This method must be implemented in the subclasses. | django.ref.forms.fields#django.forms.MultiValueField.compress |
fields
A tuple of fields whose values are cleaned and subsequently combined into a single value. Each value of the field is cleaned by the corresponding field in fields – the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is combined into a single value by compress(). | django.ref.forms.fields#django.forms.MultiValueField.fields |
require_all_fields
Defaults to True, in which case a required validation error will be raised if no value is supplied for any field. When set to False, the Field.required attribute can be set to False for individual fields to make them optional. If no value is supplied for a required field, an incomplete validation error will be raised. A default incomplete error message can be defined on the MultiValueField subclass, or different messages can be defined on each individual field. For example: from django.core.validators import RegexValidator
class PhoneField(MultiValueField):
def __init__(self, **kwargs):
# Define one message for all fields.
error_messages = {
'incomplete': 'Enter a country calling code and a phone number.',
}
# Or define a different message for each field.
fields = (
CharField(
error_messages={'incomplete': 'Enter a country calling code.'},
validators=[
RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),
],
),
CharField(
error_messages={'incomplete': 'Enter a phone number.'},
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],
),
CharField(
validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],
required=False,
),
)
super().__init__(
error_messages=error_messages, fields=fields,
require_all_fields=False, **kwargs
) | django.ref.forms.fields#django.forms.MultiValueField.require_all_fields |
widget
Must be a subclass of django.forms.MultiWidget. Default value is TextInput, which probably is not very useful in this case. | django.ref.forms.fields#django.forms.MultiValueField.widget |
class MultiWidget(widgets, attrs=None)
A widget that is composed of multiple widgets. MultiWidget works hand in hand with the MultiValueField. MultiWidget has one required argument:
widgets
An iterable containing the widgets needed. For example: >>> from django.forms import MultiWidget, TextInput
>>> widget = MultiWidget(widgets=[TextInput, TextInput])
>>> widget.render('name', ['john', 'paul'])
'<input type="text" name="name_0" value="john"><input type="text" name="name_1" value="paul">'
You may provide a dictionary in order to specify custom suffixes for the name attribute on each subwidget. In this case, for each (key, widget) pair, the key will be appended to the name of the widget in order to generate the attribute value. You may provide the empty string ('') for a single key, in order to suppress the suffix for one widget. For example: >>> widget = MultiWidget(widgets={'': TextInput, 'last': TextInput})
>>> widget.render('name', ['john', 'paul'])
'<input type="text" name="name" value="john"><input type="text" name="name_last" value="paul">'
And one required method:
decompress(value)
This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty. This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive. The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget. An example of this is how SplitDateTimeWidget turns a datetime value into a list with date and time split into two separate values: from django.forms import MultiWidget
class SplitDateTimeWidget(MultiWidget):
# ...
def decompress(self, value):
if value:
return [value.date(), value.time()]
return [None, None]
Tip Note that MultiValueField has a complementary method compress() with the opposite responsibility - to combine cleaned values of all member fields into one.
It provides some custom context:
get_context(name, value, attrs)
In addition to the 'widget' key described in Widget.get_context(), MultiWidget adds a widget['subwidgets'] key. These can be looped over in the widget template: {% for subwidget in widget.subwidgets %}
{% include subwidget.template_name with widget=subwidget %}
{% endfor %}
Here’s an example widget which subclasses MultiWidget to display a date with the day, month, and year in different select boxes. This widget is intended to be used with a DateField rather than a MultiValueField, thus we have implemented value_from_datadict(): from datetime import date
from django import forms
class DateSelectorWidget(forms.MultiWidget):
def __init__(self, attrs=None):
days = [(day, day) for day in range(1, 32)]
months = [(month, month) for month in range(1, 13)]
years = [(year, year) for year in [2018, 2019, 2020]]
widgets = [
forms.Select(attrs=attrs, choices=days),
forms.Select(attrs=attrs, choices=months),
forms.Select(attrs=attrs, choices=years),
]
super().__init__(widgets, attrs)
def decompress(self, value):
if isinstance(value, date):
return [value.day, value.month, value.year]
elif isinstance(value, str):
year, month, day = value.split('-')
return [day, month, year]
return [None, None, None]
def value_from_datadict(self, data, files, name):
day, month, year = super().value_from_datadict(data, files, name)
# DateField expects a single string that it can parse into a date.
return '{}-{}-{}'.format(year, month, day)
The constructor creates several Select widgets in a list. The super() method uses this list to set up the widget. The required method decompress() breaks up a datetime.date value into the day, month, and year values corresponding to each widget. If an invalid date was selected, such as the non-existent 30th February, the DateField passes this method a string instead, so that needs parsing. The final return handles when value is None, meaning we don’t have any defaults for our subwidgets. The default implementation of value_from_datadict() returns a list of values corresponding to each Widget. This is appropriate when using a MultiWidget with a MultiValueField. But since we want to use this widget with a DateField, which takes a single value, we have overridden this method. The implementation here combines the data from the subwidgets into a string in the format that DateField expects. | django.ref.forms.widgets#django.forms.MultiWidget |
decompress(value)
This method takes a single “compressed” value from the field and returns a list of “decompressed” values. The input value can be assumed valid, but not necessarily non-empty. This method must be implemented by the subclass, and since the value may be empty, the implementation must be defensive. The rationale behind “decompression” is that it is necessary to “split” the combined value of the form field into the values for each widget. An example of this is how SplitDateTimeWidget turns a datetime value into a list with date and time split into two separate values: from django.forms import MultiWidget
class SplitDateTimeWidget(MultiWidget):
# ...
def decompress(self, value):
if value:
return [value.date(), value.time()]
return [None, None]
Tip Note that MultiValueField has a complementary method compress() with the opposite responsibility - to combine cleaned values of all member fields into one. | django.ref.forms.widgets#django.forms.MultiWidget.decompress |
get_context(name, value, attrs)
In addition to the 'widget' key described in Widget.get_context(), MultiWidget adds a widget['subwidgets'] key. These can be looped over in the widget template: {% for subwidget in widget.subwidgets %}
{% include subwidget.template_name with widget=subwidget %}
{% endfor %} | django.ref.forms.widgets#django.forms.MultiWidget.get_context |
widgets
An iterable containing the widgets needed. For example: >>> from django.forms import MultiWidget, TextInput
>>> widget = MultiWidget(widgets=[TextInput, TextInput])
>>> widget.render('name', ['john', 'paul'])
'<input type="text" name="name_0" value="john"><input type="text" name="name_1" value="paul">'
You may provide a dictionary in order to specify custom suffixes for the name attribute on each subwidget. In this case, for each (key, widget) pair, the key will be appended to the name of the widget in order to generate the attribute value. You may provide the empty string ('') for a single key, in order to suppress the suffix for one widget. For example: >>> widget = MultiWidget(widgets={'': TextInput, 'last': TextInput})
>>> widget.render('name', ['john', 'paul'])
'<input type="text" name="name" value="john"><input type="text" name="name_last" value="paul">' | django.ref.forms.widgets#django.forms.MultiWidget.widgets |
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). NullBooleanField may be used with widgets such as Select or RadioSelect by providing the widget choices: NullBooleanField(
widget=Select(
choices=[
('', 'Unknown'),
(True, 'Yes'),
(False, 'No'),
]
)
) | django.ref.forms.fields#django.forms.NullBooleanField |
class NullBooleanSelect
template_name: 'django/forms/widgets/select.html'
option_template_name: 'django/forms/widgets/select_option.html'
Select widget with options ‘Unknown’, ‘Yes’ and ‘No’ | django.ref.forms.widgets#django.forms.NullBooleanSelect |
class NumberInput
input_type: 'number'
template_name: 'django/forms/widgets/number.html'
Renders as: <input type="number" ...>
Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True. | django.ref.forms.widgets#django.forms.NumberInput |
class PasswordInput
input_type: 'password'
template_name: 'django/forms/widgets/password.html'
Renders as: <input type="password" ...>
Takes one optional argument:
render_value
Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False). | django.ref.forms.widgets#django.forms.PasswordInput |
render_value
Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is False). | django.ref.forms.widgets#django.forms.PasswordInput.render_value |
class RadioSelect
template_name: 'django/forms/widgets/radio.html'
option_template_name: 'django/forms/widgets/radio_option.html'
Similar to Select, but rendered as a list of radio buttons within <div> tags: <div>
<div><input type="radio" name="..."></div>
...
</div>
Changed in Django 4.0: So they are announced more concisely by screen readers, radio buttons were changed to render in <div> tags. For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form myform with a field beatles that uses a RadioSelect as its widget: <fieldset>
<legend>{{ myform.beatles.label }}</legend>
{% for radio in myform.beatles %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
</fieldset>
This would generate the following HTML: <fieldset>
<legend>Radio buttons</legend>
<div class="myradio">
<label for="id_beatles_0"><input id="id_beatles_0" name="beatles" type="radio" value="john" required> John</label>
</div>
<div class="myradio">
<label for="id_beatles_1"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required> Paul</label>
</div>
<div class="myradio">
<label for="id_beatles_2"><input id="id_beatles_2" name="beatles" type="radio" value="george" required> George</label>
</div>
<div class="myradio">
<label for="id_beatles_3"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required> Ringo</label>
</div>
</fieldset>
That included the <label> tags. To get more granular, you can use each radio button’s tag, choice_label and id_for_label attributes. For example, this template… <fieldset>
<legend>{{ myform.beatles.label }}</legend>
{% for radio in myform.beatles %}
<label for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
<span class="radio">{{ radio.tag }}</span>
</label>
{% endfor %}
</fieldset>
…will result in the following HTML: <fieldset>
<legend>Radio buttons</legend>
<label for="id_beatles_0">
John
<span class="radio"><input id="id_beatles_0" name="beatles" type="radio" value="john" required></span>
</label>
<label for="id_beatles_1">
Paul
<span class="radio"><input id="id_beatles_1" name="beatles" type="radio" value="paul" required></span>
</label>
<label for="id_beatles_2">
George
<span class="radio"><input id="id_beatles_2" name="beatles" type="radio" value="george" required></span>
</label>
<label for="id_beatles_3">
Ringo
<span class="radio"><input id="id_beatles_3" name="beatles" type="radio" value="ringo" required></span>
</label>
</fieldset>
If you decide not to loop over the radio buttons – e.g., if your template includes {{ myform.beatles }} – they’ll be output in a <div> with <div> tags, as above. The outer <div> container receives the id attribute of the widget, if defined, or BoundField.auto_id otherwise. When looping over the radio buttons, the label and input tags include for and id attributes, respectively. Each radio button has an id_for_label attribute to output the element’s ID. | django.ref.forms.widgets#django.forms.RadioSelect |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.