Refs #27656 -- Updated django.forms/http docstring verbs according to PEP 257.
This commit is contained in:
parent
afcf44c101
commit
3eb679a869
|
@ -118,7 +118,7 @@ class Signal:
|
||||||
Disconnect receiver from sender for signal.
|
Disconnect receiver from sender for signal.
|
||||||
|
|
||||||
If weak references are used, disconnect need not be called. The receiver
|
If weak references are used, disconnect need not be called. The receiver
|
||||||
will be remove from dispatch automatically.
|
will be removed from dispatch automatically.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
|
|
||||||
|
@ -168,7 +168,7 @@ class Signal:
|
||||||
named
|
named
|
||||||
Named arguments which will be passed to receivers.
|
Named arguments which will be passed to receivers.
|
||||||
|
|
||||||
Returns a list of tuple pairs [(receiver, response), ... ].
|
Return a list of tuple pairs [(receiver, response), ... ].
|
||||||
"""
|
"""
|
||||||
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
|
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
|
||||||
return []
|
return []
|
||||||
|
@ -194,12 +194,10 @@ class Signal:
|
||||||
arguments must be a subset of the argument names defined in
|
arguments must be a subset of the argument names defined in
|
||||||
providing_args.
|
providing_args.
|
||||||
|
|
||||||
Return a list of tuple pairs [(receiver, response), ... ]. May raise
|
Return a list of tuple pairs [(receiver, response), ... ].
|
||||||
DispatcherKeyError.
|
|
||||||
|
|
||||||
If any receiver raises an error (specifically any subclass of
|
If any receiver raises an error (specifically any subclass of
|
||||||
Exception), the error instance is returned as the result for that
|
Exception), return the error instance as the result for that receiver.
|
||||||
receiver.
|
|
||||||
"""
|
"""
|
||||||
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
|
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
|
||||||
return []
|
return []
|
||||||
|
|
|
@ -31,7 +31,7 @@ class BoundField:
|
||||||
self.help_text = field.help_text or ''
|
self.help_text = field.help_text or ''
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
"""Renders this field as an HTML widget."""
|
"""Render this field as an HTML widget."""
|
||||||
if self.field.show_hidden_initial:
|
if self.field.show_hidden_initial:
|
||||||
return self.as_widget() + self.as_hidden(only_initial=True)
|
return self.as_widget() + self.as_hidden(only_initial=True)
|
||||||
return self.as_widget()
|
return self.as_widget()
|
||||||
|
@ -69,16 +69,15 @@ class BoundField:
|
||||||
@property
|
@property
|
||||||
def errors(self):
|
def errors(self):
|
||||||
"""
|
"""
|
||||||
Returns an ErrorList for this field. Returns an empty ErrorList
|
Return an ErrorList (empty if there are no errors) for this field.
|
||||||
if there are none.
|
|
||||||
"""
|
"""
|
||||||
return self.form.errors.get(self.name, self.form.error_class())
|
return self.form.errors.get(self.name, self.form.error_class())
|
||||||
|
|
||||||
def as_widget(self, widget=None, attrs=None, only_initial=False):
|
def as_widget(self, widget=None, attrs=None, only_initial=False):
|
||||||
"""
|
"""
|
||||||
Renders the field by rendering the passed widget, adding any HTML
|
Render the field by rendering the passed widget, adding any HTML
|
||||||
attributes passed as attrs. If no widget is specified, then the
|
attributes passed as attrs. If a widget isn't specified, use the
|
||||||
field's default widget will be used.
|
field's default widget.
|
||||||
"""
|
"""
|
||||||
if not widget:
|
if not widget:
|
||||||
widget = self.field.widget
|
widget = self.field.widget
|
||||||
|
@ -119,30 +118,30 @@ class BoundField:
|
||||||
|
|
||||||
def as_text(self, attrs=None, **kwargs):
|
def as_text(self, attrs=None, **kwargs):
|
||||||
"""
|
"""
|
||||||
Returns a string of HTML for representing this as an <input type="text">.
|
Return a string of HTML for representing this as an <input type="text">.
|
||||||
"""
|
"""
|
||||||
return self.as_widget(TextInput(), attrs, **kwargs)
|
return self.as_widget(TextInput(), attrs, **kwargs)
|
||||||
|
|
||||||
def as_textarea(self, attrs=None, **kwargs):
|
def as_textarea(self, attrs=None, **kwargs):
|
||||||
"Returns a string of HTML for representing this as a <textarea>."
|
"""Return a string of HTML for representing this as a <textarea>."""
|
||||||
return self.as_widget(Textarea(), attrs, **kwargs)
|
return self.as_widget(Textarea(), attrs, **kwargs)
|
||||||
|
|
||||||
def as_hidden(self, attrs=None, **kwargs):
|
def as_hidden(self, attrs=None, **kwargs):
|
||||||
"""
|
"""
|
||||||
Returns a string of HTML for representing this as an <input type="hidden">.
|
Return a string of HTML for representing this as an <input type="hidden">.
|
||||||
"""
|
"""
|
||||||
return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
|
return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def data(self):
|
def data(self):
|
||||||
"""
|
"""
|
||||||
Returns the data for this BoundField, or None if it wasn't given.
|
Return the data for this BoundField, or None if it wasn't given.
|
||||||
"""
|
"""
|
||||||
return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
|
return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
|
||||||
|
|
||||||
def value(self):
|
def value(self):
|
||||||
"""
|
"""
|
||||||
Returns the value for this BoundField, using the initial value if
|
Return the value for this BoundField, using the initial value if
|
||||||
the form is not bound or the data otherwise.
|
the form is not bound or the data otherwise.
|
||||||
"""
|
"""
|
||||||
data = self.initial
|
data = self.initial
|
||||||
|
@ -152,13 +151,13 @@ class BoundField:
|
||||||
|
|
||||||
def label_tag(self, contents=None, attrs=None, label_suffix=None):
|
def label_tag(self, contents=None, attrs=None, label_suffix=None):
|
||||||
"""
|
"""
|
||||||
Wraps the given contents in a <label>, if the field has an ID attribute.
|
Wrap the given contents in a <label>, if the field has an ID attribute.
|
||||||
contents should be 'mark_safe'd to avoid HTML escaping. If contents
|
contents should be mark_safe'd to avoid HTML escaping. If contents
|
||||||
aren't given, uses the field's HTML-escaped label.
|
aren't given, use the field's HTML-escaped label.
|
||||||
|
|
||||||
If attrs are given, they're used as HTML attributes on the <label> tag.
|
If attrs are given, use them as HTML attributes on the <label> tag.
|
||||||
|
|
||||||
label_suffix allows overriding the form's label_suffix.
|
label_suffix overrides the form's label_suffix.
|
||||||
"""
|
"""
|
||||||
contents = contents or self.label
|
contents = contents or self.label
|
||||||
if label_suffix is None:
|
if label_suffix is None:
|
||||||
|
@ -189,7 +188,7 @@ class BoundField:
|
||||||
|
|
||||||
def css_classes(self, extra_classes=None):
|
def css_classes(self, extra_classes=None):
|
||||||
"""
|
"""
|
||||||
Returns a string of space-separated CSS classes for this field.
|
Return a string of space-separated CSS classes for this field.
|
||||||
"""
|
"""
|
||||||
if hasattr(extra_classes, 'split'):
|
if hasattr(extra_classes, 'split'):
|
||||||
extra_classes = extra_classes.split()
|
extra_classes = extra_classes.split()
|
||||||
|
@ -202,14 +201,14 @@ class BoundField:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_hidden(self):
|
def is_hidden(self):
|
||||||
"Returns True if this BoundField's widget is hidden."
|
"""Return True if this BoundField's widget is hidden."""
|
||||||
return self.field.widget.is_hidden
|
return self.field.widget.is_hidden
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def auto_id(self):
|
def auto_id(self):
|
||||||
"""
|
"""
|
||||||
Calculates and returns the ID attribute for this BoundField, if the
|
Calculate and return the ID attribute for this BoundField, if the
|
||||||
associated Form has specified auto_id. Returns an empty string otherwise.
|
associated Form has specified auto_id. Return an empty string otherwise.
|
||||||
"""
|
"""
|
||||||
auto_id = self.form.auto_id
|
auto_id = self.form.auto_id
|
||||||
if auto_id and '%s' in force_text(auto_id):
|
if auto_id and '%s' in force_text(auto_id):
|
||||||
|
|
|
@ -142,10 +142,8 @@ class Field:
|
||||||
|
|
||||||
def clean(self, value):
|
def clean(self, value):
|
||||||
"""
|
"""
|
||||||
Validates the given value and returns its "cleaned" value as an
|
Validate the given value and return its "cleaned" value as an
|
||||||
appropriate Python object.
|
appropriate Python object. Raise ValidationError for any errors.
|
||||||
|
|
||||||
Raises ValidationError for any errors.
|
|
||||||
"""
|
"""
|
||||||
value = self.to_python(value)
|
value = self.to_python(value)
|
||||||
self.validate(value)
|
self.validate(value)
|
||||||
|
@ -167,16 +165,14 @@ class Field:
|
||||||
|
|
||||||
def widget_attrs(self, widget):
|
def widget_attrs(self, widget):
|
||||||
"""
|
"""
|
||||||
Given a Widget instance (*not* a Widget class), returns a dictionary of
|
Given a Widget instance (*not* a Widget class), return a dictionary of
|
||||||
any HTML attributes that should be added to the Widget, based on this
|
any HTML attributes that should be added to the Widget, based on this
|
||||||
Field.
|
Field.
|
||||||
"""
|
"""
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def has_changed(self, initial, data):
|
def has_changed(self, initial, data):
|
||||||
"""
|
"""Return True if data differs from initial."""
|
||||||
Return True if data differs from initial.
|
|
||||||
"""
|
|
||||||
# Always return False if the field is disabled since self.bound_data
|
# Always return False if the field is disabled since self.bound_data
|
||||||
# always uses the initial value in this case.
|
# always uses the initial value in this case.
|
||||||
if self.disabled:
|
if self.disabled:
|
||||||
|
@ -222,7 +218,7 @@ class CharField(Field):
|
||||||
self.validators.append(validators.MaxLengthValidator(int(max_length)))
|
self.validators.append(validators.MaxLengthValidator(int(max_length)))
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"Returns a string."
|
"""Return a string."""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
return self.empty_value
|
return self.empty_value
|
||||||
value = force_text(value)
|
value = force_text(value)
|
||||||
|
@ -262,8 +258,8 @@ class IntegerField(Field):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that int() can be called on the input. Returns the result
|
Validate that int() can be called on the input. Return the result
|
||||||
of int(). Returns None for empty values.
|
of int() or None for empty values.
|
||||||
"""
|
"""
|
||||||
value = super().to_python(value)
|
value = super().to_python(value)
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -294,8 +290,8 @@ class FloatField(IntegerField):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that float() can be called on the input. Returns the result
|
Validate that float() can be called on the input. Return the result
|
||||||
of float(). Returns None for empty values.
|
of float() or None for empty values.
|
||||||
"""
|
"""
|
||||||
value = super(IntegerField, self).to_python(value)
|
value = super(IntegerField, self).to_python(value)
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -336,9 +332,9 @@ class DecimalField(IntegerField):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that the input is a decimal number. Returns a Decimal
|
Validate that the input is a decimal number. Return a Decimal
|
||||||
instance. Returns None for empty values. Ensures that there are no more
|
instance or None for empty values. Ensure that there are no more
|
||||||
than max_digits in the number, and no more than decimal_places digits
|
than max_digits in the number and no more than decimal_places digits
|
||||||
after the decimal point.
|
after the decimal point.
|
||||||
"""
|
"""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -405,7 +401,7 @@ class DateField(BaseTemporalField):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that the input can be converted to a date. Returns a Python
|
Validate that the input can be converted to a date. Return a Python
|
||||||
datetime.date object.
|
datetime.date object.
|
||||||
"""
|
"""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -429,7 +425,7 @@ class TimeField(BaseTemporalField):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that the input can be converted to a time. Returns a Python
|
Validate that the input can be converted to a time. Return a Python
|
||||||
datetime.time object.
|
datetime.time object.
|
||||||
"""
|
"""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -456,7 +452,7 @@ class DateTimeField(BaseTemporalField):
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that the input can be converted to a datetime. Returns a
|
Validate that the input can be converted to a datetime. Return a
|
||||||
Python datetime.datetime object.
|
Python datetime.datetime object.
|
||||||
"""
|
"""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
|
@ -605,8 +601,8 @@ class ImageField(FileField):
|
||||||
|
|
||||||
def to_python(self, data):
|
def to_python(self, data):
|
||||||
"""
|
"""
|
||||||
Checks that the file-upload field data contains a valid image (GIF, JPG,
|
Check that the file-upload field data contains a valid image (GIF, JPG,
|
||||||
PNG, possibly others -- whatever the Python Imaging Library supports).
|
PNG, etc. -- whatever Pillow supports).
|
||||||
"""
|
"""
|
||||||
f = super().to_python(data)
|
f = super().to_python(data)
|
||||||
if f is None:
|
if f is None:
|
||||||
|
@ -661,8 +657,8 @@ class URLField(CharField):
|
||||||
|
|
||||||
def split_url(url):
|
def split_url(url):
|
||||||
"""
|
"""
|
||||||
Returns a list of url parts via ``urlparse.urlsplit`` (or raises a
|
Return a list of url parts via urlparse.urlsplit(), or raise
|
||||||
``ValidationError`` exception for certain).
|
ValidationError for some malformed URLs.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return list(urlsplit(url))
|
return list(urlsplit(url))
|
||||||
|
@ -693,7 +689,7 @@ class BooleanField(Field):
|
||||||
widget = CheckboxInput
|
widget = CheckboxInput
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""Returns a Python boolean object."""
|
"""Return a Python boolean object."""
|
||||||
# Explicitly check for the string 'False', which is what a hidden field
|
# Explicitly check for the string 'False', which is what a hidden field
|
||||||
# will submit for False. Also check for '0', since this is what
|
# will submit for False. Also check for '0', since this is what
|
||||||
# RadioSelect will provide. Because bool("True") == bool('1') == True,
|
# RadioSelect will provide. Because bool("True") == bool('1') == True,
|
||||||
|
@ -716,19 +712,19 @@ class BooleanField(Field):
|
||||||
|
|
||||||
class NullBooleanField(BooleanField):
|
class NullBooleanField(BooleanField):
|
||||||
"""
|
"""
|
||||||
A field whose valid values are None, True and False. Invalid values are
|
A field whose valid values are None, True, and False. Clean invalid values
|
||||||
cleaned to None.
|
to None.
|
||||||
"""
|
"""
|
||||||
widget = NullBooleanSelect
|
widget = NullBooleanSelect
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"""
|
"""
|
||||||
Explicitly checks for the string 'True' and 'False', which is what a
|
Explicitly check for the string 'True' and 'False', which is what a
|
||||||
hidden field will submit for True and False, for 'true' and 'false',
|
hidden field will submit for True and False, for 'true' and 'false',
|
||||||
which are likely to be returned by JavaScript serializations of forms,
|
which are likely to be returned by JavaScript serializations of forms,
|
||||||
and for '1' and '0', which is what a RadioField will submit. Unlike
|
and for '1' and '0', which is what a RadioField will submit. Unlike
|
||||||
the Booleanfield we need to explicitly check for True, because we are
|
the Booleanfield, this field must check for True because it doesn't
|
||||||
not using the bool() function
|
use the bool() function.
|
||||||
"""
|
"""
|
||||||
if value in (True, 'True', 'true', '1'):
|
if value in (True, 'True', 'true', '1'):
|
||||||
return True
|
return True
|
||||||
|
@ -786,15 +782,13 @@ class ChoiceField(Field):
|
||||||
choices = property(_get_choices, _set_choices)
|
choices = property(_get_choices, _set_choices)
|
||||||
|
|
||||||
def to_python(self, value):
|
def to_python(self, value):
|
||||||
"Return a string."
|
"""Return a string."""
|
||||||
if value in self.empty_values:
|
if value in self.empty_values:
|
||||||
return ''
|
return ''
|
||||||
return force_text(value)
|
return force_text(value)
|
||||||
|
|
||||||
def validate(self, value):
|
def validate(self, value):
|
||||||
"""
|
"""Validate that the input is in self.choices."""
|
||||||
Validates that the input is in self.choices.
|
|
||||||
"""
|
|
||||||
super().validate(value)
|
super().validate(value)
|
||||||
if value and not self.valid_value(value):
|
if value and not self.valid_value(value):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
|
@ -804,7 +798,7 @@ class ChoiceField(Field):
|
||||||
)
|
)
|
||||||
|
|
||||||
def valid_value(self, value):
|
def valid_value(self, value):
|
||||||
"Check to see if the provided value is a valid choice"
|
"""Check to see if the provided value is a valid choice."""
|
||||||
text_value = force_text(value)
|
text_value = force_text(value)
|
||||||
for k, v in self.choices:
|
for k, v in self.choices:
|
||||||
if isinstance(v, (list, tuple)):
|
if isinstance(v, (list, tuple)):
|
||||||
|
@ -861,9 +855,7 @@ class MultipleChoiceField(ChoiceField):
|
||||||
return [force_text(val) for val in value]
|
return [force_text(val) for val in value]
|
||||||
|
|
||||||
def validate(self, value):
|
def validate(self, value):
|
||||||
"""
|
"""Validate that the input is a list or tuple."""
|
||||||
Validates that the input is a list or tuple.
|
|
||||||
"""
|
|
||||||
if self.required and not value:
|
if self.required and not value:
|
||||||
raise ValidationError(self.error_messages['required'], code='required')
|
raise ValidationError(self.error_messages['required'], code='required')
|
||||||
# Validate that each value in the value list is in self.choices.
|
# Validate that each value in the value list is in self.choices.
|
||||||
|
@ -895,7 +887,7 @@ class TypedMultipleChoiceField(MultipleChoiceField):
|
||||||
|
|
||||||
def _coerce(self, value):
|
def _coerce(self, value):
|
||||||
"""
|
"""
|
||||||
Validates that the values are in self.choices and can be coerced to the
|
Validate that the values are in self.choices and can be coerced to the
|
||||||
right type.
|
right type.
|
||||||
"""
|
"""
|
||||||
if value == self.empty_value or value in self.empty_values:
|
if value == self.empty_value or value in self.empty_values:
|
||||||
|
@ -938,7 +930,7 @@ class ComboField(Field):
|
||||||
|
|
||||||
def clean(self, value):
|
def clean(self, value):
|
||||||
"""
|
"""
|
||||||
Validates the given value against all of self.fields, which is a
|
Validate the given value against all of self.fields, which is a
|
||||||
list of Field instances.
|
list of Field instances.
|
||||||
"""
|
"""
|
||||||
super().clean(value)
|
super().clean(value)
|
||||||
|
@ -949,7 +941,7 @@ class ComboField(Field):
|
||||||
|
|
||||||
class MultiValueField(Field):
|
class MultiValueField(Field):
|
||||||
"""
|
"""
|
||||||
A Field that aggregates the logic of multiple Fields.
|
Aggregate the logic of multiple Fields.
|
||||||
|
|
||||||
Its clean() method takes a "decompressed" list of values, which are then
|
Its clean() method takes a "decompressed" list of values, which are then
|
||||||
cleaned into a single value according to self.fields. Each value in
|
cleaned into a single value according to self.fields. Each value in
|
||||||
|
@ -992,7 +984,7 @@ class MultiValueField(Field):
|
||||||
|
|
||||||
def clean(self, value):
|
def clean(self, value):
|
||||||
"""
|
"""
|
||||||
Validates every value in the given list. A value is validated against
|
Validate every value in the given list. A value is validated against
|
||||||
the corresponding Field in self.fields.
|
the corresponding Field in self.fields.
|
||||||
|
|
||||||
For example, if this MultiValueField was instantiated with
|
For example, if this MultiValueField was instantiated with
|
||||||
|
@ -1044,7 +1036,7 @@ class MultiValueField(Field):
|
||||||
|
|
||||||
def compress(self, data_list):
|
def compress(self, data_list):
|
||||||
"""
|
"""
|
||||||
Returns a single value for the given list of values. The values can be
|
Return a single value for the given list of values. The values can be
|
||||||
assumed to be valid.
|
assumed to be valid.
|
||||||
|
|
||||||
For example, if this MultiValueField was instantiated with
|
For example, if this MultiValueField was instantiated with
|
||||||
|
|
|
@ -24,9 +24,7 @@ __all__ = ('BaseForm', 'Form')
|
||||||
|
|
||||||
|
|
||||||
class DeclarativeFieldsMetaclass(MediaDefiningClass):
|
class DeclarativeFieldsMetaclass(MediaDefiningClass):
|
||||||
"""
|
"""Collect Fields declared on the base classes."""
|
||||||
Metaclass that collects Fields declared on the base classes.
|
|
||||||
"""
|
|
||||||
def __new__(mcs, name, bases, attrs):
|
def __new__(mcs, name, bases, attrs):
|
||||||
# Collect fields from current class.
|
# Collect fields from current class.
|
||||||
current_fields = []
|
current_fields = []
|
||||||
|
@ -63,10 +61,12 @@ class DeclarativeFieldsMetaclass(MediaDefiningClass):
|
||||||
|
|
||||||
@html_safe
|
@html_safe
|
||||||
class BaseForm:
|
class BaseForm:
|
||||||
# This is the main implementation of all the Form logic. Note that this
|
"""
|
||||||
# class is different than Form. See the comments by the Form class for more
|
The main implementation of all the Form logic. Note that this class is
|
||||||
# information. Any improvements to the form API should be made to *this*
|
different than Form. See the comments by the Form class for more info. Any
|
||||||
# class, not to the Form class.
|
improvements to the form API should be made to this class, not to the Form
|
||||||
|
class.
|
||||||
|
"""
|
||||||
default_renderer = None
|
default_renderer = None
|
||||||
field_order = None
|
field_order = None
|
||||||
prefix = None
|
prefix = None
|
||||||
|
@ -113,14 +113,14 @@ class BaseForm:
|
||||||
|
|
||||||
def order_fields(self, field_order):
|
def order_fields(self, field_order):
|
||||||
"""
|
"""
|
||||||
Rearranges the fields according to field_order.
|
Rearrange the fields according to field_order.
|
||||||
|
|
||||||
field_order is a list of field names specifying the order. Fields not
|
field_order is a list of field names specifying the order. Append fields
|
||||||
included in the list are appended in the default order for backward
|
not included in the list in the default order for backward compatibility
|
||||||
compatibility with subclasses not overriding field_order. If field_order
|
with subclasses not overriding field_order. If field_order is None,
|
||||||
is None, all fields are kept in the order defined in the class.
|
keep all fields in the order defined in the class. Ignore unknown
|
||||||
Unknown fields in field_order are ignored to allow disabling fields in
|
fields in field_order to allow disabling fields in form subclasses
|
||||||
form subclasses without redefining ordering.
|
without redefining ordering.
|
||||||
"""
|
"""
|
||||||
if field_order is None:
|
if field_order is None:
|
||||||
return
|
return
|
||||||
|
@ -153,7 +153,7 @@ class BaseForm:
|
||||||
yield self[name]
|
yield self[name]
|
||||||
|
|
||||||
def __getitem__(self, name):
|
def __getitem__(self, name):
|
||||||
"Returns a BoundField with the given name."
|
"""Return a BoundField with the given name."""
|
||||||
try:
|
try:
|
||||||
field = self.fields[name]
|
field = self.fields[name]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
|
@ -170,21 +170,18 @@ class BaseForm:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def errors(self):
|
def errors(self):
|
||||||
"Returns an ErrorDict for the data provided for the form"
|
"""Return an ErrorDict for the data provided for the form."""
|
||||||
if self._errors is None:
|
if self._errors is None:
|
||||||
self.full_clean()
|
self.full_clean()
|
||||||
return self._errors
|
return self._errors
|
||||||
|
|
||||||
def is_valid(self):
|
def is_valid(self):
|
||||||
"""
|
"""Return True if the form has no errors, or False otherwise."""
|
||||||
Returns True if the form has no errors. Otherwise, False. If errors are
|
|
||||||
being ignored, returns False.
|
|
||||||
"""
|
|
||||||
return self.is_bound and not self.errors
|
return self.is_bound and not self.errors
|
||||||
|
|
||||||
def add_prefix(self, field_name):
|
def add_prefix(self, field_name):
|
||||||
"""
|
"""
|
||||||
Returns the field name with a prefix appended, if this Form has a
|
Return the field name with a prefix appended, if this Form has a
|
||||||
prefix set.
|
prefix set.
|
||||||
|
|
||||||
Subclasses may wish to override.
|
Subclasses may wish to override.
|
||||||
|
@ -192,13 +189,11 @@ class BaseForm:
|
||||||
return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
|
return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
|
||||||
|
|
||||||
def add_initial_prefix(self, field_name):
|
def add_initial_prefix(self, field_name):
|
||||||
"""
|
"""Add a 'initial' prefix for checking dynamic initial values."""
|
||||||
Add a 'initial' prefix for checking dynamic initial values
|
|
||||||
"""
|
|
||||||
return 'initial-%s' % self.add_prefix(field_name)
|
return 'initial-%s' % self.add_prefix(field_name)
|
||||||
|
|
||||||
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
|
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
|
||||||
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
|
"Output HTML. Used by as_table(), as_ul(), as_p()."
|
||||||
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
|
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
|
||||||
output, hidden_fields = [], []
|
output, hidden_fields = [], []
|
||||||
|
|
||||||
|
@ -276,7 +271,7 @@ class BaseForm:
|
||||||
return mark_safe('\n'.join(output))
|
return mark_safe('\n'.join(output))
|
||||||
|
|
||||||
def as_table(self):
|
def as_table(self):
|
||||||
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
|
"Return this form rendered as HTML <tr>s -- excluding the <table></table>."
|
||||||
return self._html_output(
|
return self._html_output(
|
||||||
normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
|
normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
|
||||||
error_row='<tr><td colspan="2">%s</td></tr>',
|
error_row='<tr><td colspan="2">%s</td></tr>',
|
||||||
|
@ -285,7 +280,7 @@ class BaseForm:
|
||||||
errors_on_separate_row=False)
|
errors_on_separate_row=False)
|
||||||
|
|
||||||
def as_ul(self):
|
def as_ul(self):
|
||||||
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
|
"Return this form rendered as HTML <li>s -- excluding the <ul></ul>."
|
||||||
return self._html_output(
|
return self._html_output(
|
||||||
normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
|
||||||
error_row='<li>%s</li>',
|
error_row='<li>%s</li>',
|
||||||
|
@ -294,7 +289,7 @@ class BaseForm:
|
||||||
errors_on_separate_row=False)
|
errors_on_separate_row=False)
|
||||||
|
|
||||||
def as_p(self):
|
def as_p(self):
|
||||||
"Returns this form rendered as HTML <p>s."
|
"Return this form rendered as HTML <p>s."
|
||||||
return self._html_output(
|
return self._html_output(
|
||||||
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
|
||||||
error_row='%s',
|
error_row='%s',
|
||||||
|
@ -304,8 +299,8 @@ class BaseForm:
|
||||||
|
|
||||||
def non_field_errors(self):
|
def non_field_errors(self):
|
||||||
"""
|
"""
|
||||||
Returns an ErrorList of errors that aren't associated with a particular
|
Return an ErrorList of errors that aren't associated with a particular
|
||||||
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
|
field -- i.e., from Form.clean(). Return an empty ErrorList if there
|
||||||
are none.
|
are none.
|
||||||
"""
|
"""
|
||||||
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
|
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))
|
||||||
|
@ -315,15 +310,14 @@ class BaseForm:
|
||||||
Update the content of `self._errors`.
|
Update the content of `self._errors`.
|
||||||
|
|
||||||
The `field` argument is the name of the field to which the errors
|
The `field` argument is the name of the field to which the errors
|
||||||
should be added. If its value is None the errors will be treated as
|
should be added. If it's None, treat the errors as NON_FIELD_ERRORS.
|
||||||
NON_FIELD_ERRORS.
|
|
||||||
|
|
||||||
The `error` argument can be a single error, a list of errors, or a
|
The `error` argument can be a single error, a list of errors, or a
|
||||||
dictionary that maps field names to lists of errors. What we define as
|
dictionary that maps field names to lists of errors. An "error" can be
|
||||||
an "error" can be either a simple string or an instance of
|
either a simple string or an instance of ValidationError with its
|
||||||
ValidationError with its message attribute set and what we define as
|
message attribute set and a "list or dictionary" can be an actual
|
||||||
list or dictionary can be an actual `list` or `dict` or an instance
|
`list` or `dict` or an instance of ValidationError with its
|
||||||
of ValidationError with its `error_list` or `error_dict` attribute set.
|
`error_list` or `error_dict` attribute set.
|
||||||
|
|
||||||
If `error` is a dictionary, the `field` argument *must* be None and
|
If `error` is a dictionary, the `field` argument *must* be None and
|
||||||
errors will be added to the fields that correspond to the keys of the
|
errors will be added to the fields that correspond to the keys of the
|
||||||
|
@ -369,8 +363,7 @@ class BaseForm:
|
||||||
|
|
||||||
def full_clean(self):
|
def full_clean(self):
|
||||||
"""
|
"""
|
||||||
Cleans all of self.data and populates self._errors and
|
Clean all of self.data and populate self._errors and self.cleaned_data.
|
||||||
self.cleaned_data.
|
|
||||||
"""
|
"""
|
||||||
self._errors = ErrorDict()
|
self._errors = ErrorDict()
|
||||||
if not self.is_bound: # Stop further processing.
|
if not self.is_bound: # Stop further processing.
|
||||||
|
@ -433,9 +426,7 @@ class BaseForm:
|
||||||
return self.cleaned_data
|
return self.cleaned_data
|
||||||
|
|
||||||
def has_changed(self):
|
def has_changed(self):
|
||||||
"""
|
"""Return True if data differs from initial."""
|
||||||
Returns True if data differs from initial.
|
|
||||||
"""
|
|
||||||
return bool(self.changed_data)
|
return bool(self.changed_data)
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
|
@ -464,9 +455,7 @@ class BaseForm:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def media(self):
|
def media(self):
|
||||||
"""
|
"""Return all media required to render the widgets on this form."""
|
||||||
Provide a description of all media required to render the widgets on this form
|
|
||||||
"""
|
|
||||||
media = Media()
|
media = Media()
|
||||||
for field in self.fields.values():
|
for field in self.fields.values():
|
||||||
media = media + field.widget.media
|
media = media + field.widget.media
|
||||||
|
@ -474,8 +463,8 @@ class BaseForm:
|
||||||
|
|
||||||
def is_multipart(self):
|
def is_multipart(self):
|
||||||
"""
|
"""
|
||||||
Returns True if the form needs to be multipart-encoded, i.e. it has
|
Return True if the form needs to be multipart-encoded, i.e. it has
|
||||||
FileInput. Otherwise, False.
|
FileInput, or False otherwise.
|
||||||
"""
|
"""
|
||||||
for field in self.fields.values():
|
for field in self.fields.values():
|
||||||
if field.widget.needs_multipart_form:
|
if field.widget.needs_multipart_form:
|
||||||
|
@ -484,14 +473,14 @@ class BaseForm:
|
||||||
|
|
||||||
def hidden_fields(self):
|
def hidden_fields(self):
|
||||||
"""
|
"""
|
||||||
Returns a list of all the BoundField objects that are hidden fields.
|
Return a list of all the BoundField objects that are hidden fields.
|
||||||
Useful for manual form layout in templates.
|
Useful for manual form layout in templates.
|
||||||
"""
|
"""
|
||||||
return [field for field in self if field.is_hidden]
|
return [field for field in self if field.is_hidden]
|
||||||
|
|
||||||
def visible_fields(self):
|
def visible_fields(self):
|
||||||
"""
|
"""
|
||||||
Returns a list of BoundField objects that aren't hidden fields.
|
Return a list of BoundField objects that aren't hidden fields.
|
||||||
The opposite of the hidden_fields() method.
|
The opposite of the hidden_fields() method.
|
||||||
"""
|
"""
|
||||||
return [field for field in self if not field.is_hidden]
|
return [field for field in self if not field.is_hidden]
|
||||||
|
|
|
@ -27,9 +27,9 @@ DEFAULT_MAX_NUM = 1000
|
||||||
|
|
||||||
class ManagementForm(Form):
|
class ManagementForm(Form):
|
||||||
"""
|
"""
|
||||||
``ManagementForm`` is used to keep track of how many form instances
|
Keep track of how many form instances are displayed on the page. If adding
|
||||||
are displayed on the page. If adding new forms via javascript, you should
|
new forms via JavaScript, you should increment the count field of this form
|
||||||
increment the count field of this form as well.
|
as well.
|
||||||
"""
|
"""
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
|
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
|
||||||
|
@ -64,23 +64,26 @@ class BaseFormSet:
|
||||||
return self.as_table()
|
return self.as_table()
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
"""Yields the forms in the order they should be rendered"""
|
"""Yield the forms in the order they should be rendered."""
|
||||||
return iter(self.forms)
|
return iter(self.forms)
|
||||||
|
|
||||||
def __getitem__(self, index):
|
def __getitem__(self, index):
|
||||||
"""Returns the form at the given index, based on the rendering order"""
|
"""Return the form at the given index, based on the rendering order."""
|
||||||
return self.forms[index]
|
return self.forms[index]
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self.forms)
|
return len(self.forms)
|
||||||
|
|
||||||
def __bool__(self):
|
def __bool__(self):
|
||||||
"""All formsets have a management form which is not included in the length"""
|
"""
|
||||||
|
Return True since all formsets have a management form which is not
|
||||||
|
included in the length.
|
||||||
|
"""
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def management_form(self):
|
def management_form(self):
|
||||||
"""Returns the ManagementForm instance for this FormSet."""
|
"""Return the ManagementForm instance for this FormSet."""
|
||||||
if self.is_bound:
|
if self.is_bound:
|
||||||
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
|
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
|
||||||
if not form.is_valid():
|
if not form.is_valid():
|
||||||
|
@ -98,7 +101,7 @@ class BaseFormSet:
|
||||||
return form
|
return form
|
||||||
|
|
||||||
def total_form_count(self):
|
def total_form_count(self):
|
||||||
"""Returns the total number of forms in this FormSet."""
|
"""Return the total number of forms in this FormSet."""
|
||||||
if self.is_bound:
|
if self.is_bound:
|
||||||
# return absolute_max if it is lower than the actual total form
|
# return absolute_max if it is lower than the actual total form
|
||||||
# count in the data; this is DoS protection to prevent clients
|
# count in the data; this is DoS protection to prevent clients
|
||||||
|
@ -117,7 +120,7 @@ class BaseFormSet:
|
||||||
return total_forms
|
return total_forms
|
||||||
|
|
||||||
def initial_form_count(self):
|
def initial_form_count(self):
|
||||||
"""Returns the number of forms that are required in this FormSet."""
|
"""Return the number of forms that are required in this FormSet."""
|
||||||
if self.is_bound:
|
if self.is_bound:
|
||||||
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
|
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
|
||||||
else:
|
else:
|
||||||
|
@ -127,9 +130,7 @@ class BaseFormSet:
|
||||||
|
|
||||||
@cached_property
|
@cached_property
|
||||||
def forms(self):
|
def forms(self):
|
||||||
"""
|
"""Instantiate forms at first property access."""
|
||||||
Instantiate forms at first property access.
|
|
||||||
"""
|
|
||||||
# DoS protection is included in total_form_count()
|
# DoS protection is included in total_form_count()
|
||||||
forms = [self._construct_form(i, **self.get_form_kwargs(i))
|
forms = [self._construct_form(i, **self.get_form_kwargs(i))
|
||||||
for i in range(self.total_form_count())]
|
for i in range(self.total_form_count())]
|
||||||
|
@ -145,9 +146,7 @@ class BaseFormSet:
|
||||||
return self.form_kwargs.copy()
|
return self.form_kwargs.copy()
|
||||||
|
|
||||||
def _construct_form(self, i, **kwargs):
|
def _construct_form(self, i, **kwargs):
|
||||||
"""
|
"""Instantiate and return the i-th form instance in a formset."""
|
||||||
Instantiates and returns the i-th form instance in a formset.
|
|
||||||
"""
|
|
||||||
defaults = {
|
defaults = {
|
||||||
'auto_id': self.auto_id,
|
'auto_id': self.auto_id,
|
||||||
'prefix': self.add_prefix(i),
|
'prefix': self.add_prefix(i),
|
||||||
|
@ -199,7 +198,7 @@ class BaseFormSet:
|
||||||
@property
|
@property
|
||||||
def cleaned_data(self):
|
def cleaned_data(self):
|
||||||
"""
|
"""
|
||||||
Returns a list of form.cleaned_data dicts for every form in self.forms.
|
Return a list of form.cleaned_data dicts for every form in self.forms.
|
||||||
"""
|
"""
|
||||||
if not self.is_valid():
|
if not self.is_valid():
|
||||||
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
|
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
|
||||||
|
@ -207,9 +206,7 @@ class BaseFormSet:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def deleted_forms(self):
|
def deleted_forms(self):
|
||||||
"""
|
"""Return a list of forms that have been marked for deletion."""
|
||||||
Returns a list of forms that have been marked for deletion.
|
|
||||||
"""
|
|
||||||
if not self.is_valid() or not self.can_delete:
|
if not self.is_valid() or not self.can_delete:
|
||||||
return []
|
return []
|
||||||
# construct _deleted_form_indexes which is just a list of form indexes
|
# construct _deleted_form_indexes which is just a list of form indexes
|
||||||
|
@ -228,8 +225,8 @@ class BaseFormSet:
|
||||||
@property
|
@property
|
||||||
def ordered_forms(self):
|
def ordered_forms(self):
|
||||||
"""
|
"""
|
||||||
Returns a list of form in the order specified by the incoming data.
|
Return a list of form in the order specified by the incoming data.
|
||||||
Raises an AttributeError if ordering is not allowed.
|
Raise an AttributeError if ordering is not allowed.
|
||||||
"""
|
"""
|
||||||
if not self.is_valid() or not self.can_order:
|
if not self.is_valid() or not self.can_order:
|
||||||
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
|
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
|
||||||
|
@ -269,8 +266,8 @@ class BaseFormSet:
|
||||||
|
|
||||||
def non_form_errors(self):
|
def non_form_errors(self):
|
||||||
"""
|
"""
|
||||||
Returns an ErrorList of errors that aren't associated with a particular
|
Return an ErrorList of errors that aren't associated with a particular
|
||||||
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
|
form -- i.e., from formset.clean(). Return an empty ErrorList if there
|
||||||
are none.
|
are none.
|
||||||
"""
|
"""
|
||||||
if self._non_form_errors is None:
|
if self._non_form_errors is None:
|
||||||
|
@ -279,30 +276,22 @@ class BaseFormSet:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def errors(self):
|
def errors(self):
|
||||||
"""
|
"""Return a list of form.errors for every form in self.forms."""
|
||||||
Returns a list of form.errors for every form in self.forms.
|
|
||||||
"""
|
|
||||||
if self._errors is None:
|
if self._errors is None:
|
||||||
self.full_clean()
|
self.full_clean()
|
||||||
return self._errors
|
return self._errors
|
||||||
|
|
||||||
def total_error_count(self):
|
def total_error_count(self):
|
||||||
"""
|
"""Return the number of errors across all forms in the formset."""
|
||||||
Returns the number of errors across all forms in the formset.
|
|
||||||
"""
|
|
||||||
return len(self.non_form_errors()) +\
|
return len(self.non_form_errors()) +\
|
||||||
sum(len(form_errors) for form_errors in self.errors)
|
sum(len(form_errors) for form_errors in self.errors)
|
||||||
|
|
||||||
def _should_delete_form(self, form):
|
def _should_delete_form(self, form):
|
||||||
"""
|
"""Return whether or not the form was marked for deletion."""
|
||||||
Returns whether or not the form was marked for deletion.
|
|
||||||
"""
|
|
||||||
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
|
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
|
||||||
|
|
||||||
def is_valid(self):
|
def is_valid(self):
|
||||||
"""
|
"""Return True if every form in self.forms is valid."""
|
||||||
Returns True if every form in self.forms is valid.
|
|
||||||
"""
|
|
||||||
if not self.is_bound:
|
if not self.is_bound:
|
||||||
return False
|
return False
|
||||||
# We loop over every form.errors here rather than short circuiting on the
|
# We loop over every form.errors here rather than short circuiting on the
|
||||||
|
@ -322,7 +311,7 @@ class BaseFormSet:
|
||||||
|
|
||||||
def full_clean(self):
|
def full_clean(self):
|
||||||
"""
|
"""
|
||||||
Cleans all of self.data and populates self._errors and
|
Clean all of self.data and populate self._errors and
|
||||||
self._non_form_errors.
|
self._non_form_errors.
|
||||||
"""
|
"""
|
||||||
self._errors = []
|
self._errors = []
|
||||||
|
@ -367,9 +356,7 @@ class BaseFormSet:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def has_changed(self):
|
def has_changed(self):
|
||||||
"""
|
"""Return True if data in any form differs from initial."""
|
||||||
Returns true if data in any form differs from initial.
|
|
||||||
"""
|
|
||||||
return any(form.has_changed() for form in self)
|
return any(form.has_changed() for form in self)
|
||||||
|
|
||||||
def add_fields(self, form, index):
|
def add_fields(self, form, index):
|
||||||
|
@ -388,8 +375,8 @@ class BaseFormSet:
|
||||||
|
|
||||||
def is_multipart(self):
|
def is_multipart(self):
|
||||||
"""
|
"""
|
||||||
Returns True if the formset needs to be multipart, i.e. it
|
Return True if the formset needs to be multipart, i.e. it
|
||||||
has FileInput. Otherwise, False.
|
has FileInput, or False otherwise.
|
||||||
"""
|
"""
|
||||||
if self.forms:
|
if self.forms:
|
||||||
return self.forms[0].is_multipart()
|
return self.forms[0].is_multipart()
|
||||||
|
@ -406,7 +393,7 @@ class BaseFormSet:
|
||||||
return self.empty_form.media
|
return self.empty_form.media
|
||||||
|
|
||||||
def as_table(self):
|
def as_table(self):
|
||||||
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
|
"Return this formset rendered as HTML <tr>s -- excluding the <table></table>."
|
||||||
# XXX: there is no semantic division between forms here, there
|
# XXX: there is no semantic division between forms here, there
|
||||||
# probably should be. It might make sense to render each form as a
|
# probably should be. It might make sense to render each form as a
|
||||||
# table row with each field as a td.
|
# table row with each field as a td.
|
||||||
|
@ -414,12 +401,12 @@ class BaseFormSet:
|
||||||
return mark_safe('\n'.join([str(self.management_form), forms]))
|
return mark_safe('\n'.join([str(self.management_form), forms]))
|
||||||
|
|
||||||
def as_p(self):
|
def as_p(self):
|
||||||
"Returns this formset rendered as HTML <p>s."
|
"Return this formset rendered as HTML <p>s."
|
||||||
forms = ' '.join(form.as_p() for form in self)
|
forms = ' '.join(form.as_p() for form in self)
|
||||||
return mark_safe('\n'.join([str(self.management_form), forms]))
|
return mark_safe('\n'.join([str(self.management_form), forms]))
|
||||||
|
|
||||||
def as_ul(self):
|
def as_ul(self):
|
||||||
"Returns this formset rendered as HTML <li>s."
|
"Return this formset rendered as HTML <li>s."
|
||||||
forms = ' '.join(form.as_ul() for form in self)
|
forms = ' '.join(form.as_ul() for form in self)
|
||||||
return mark_safe('\n'.join([str(self.management_form), forms]))
|
return mark_safe('\n'.join([str(self.management_form), forms]))
|
||||||
|
|
||||||
|
@ -445,7 +432,7 @@ def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
|
||||||
|
|
||||||
|
|
||||||
def all_valid(formsets):
|
def all_valid(formsets):
|
||||||
"""Returns true if every formset in formsets is valid."""
|
"""Return True if every formset in formsets is valid."""
|
||||||
valid = True
|
valid = True
|
||||||
for formset in formsets:
|
for formset in formsets:
|
||||||
if not formset.is_valid():
|
if not formset.is_valid():
|
||||||
|
|
|
@ -32,9 +32,8 @@ ALL_FIELDS = '__all__'
|
||||||
|
|
||||||
def construct_instance(form, instance, fields=None, exclude=None):
|
def construct_instance(form, instance, fields=None, exclude=None):
|
||||||
"""
|
"""
|
||||||
Constructs and returns a model instance from the bound ``form``'s
|
Construct and return a model instance from the bound ``form``'s
|
||||||
``cleaned_data``, but does not save the returned instance to the
|
``cleaned_data``, but do not save the returned instance to the database.
|
||||||
database.
|
|
||||||
"""
|
"""
|
||||||
from django.db import models
|
from django.db import models
|
||||||
opts = instance._meta
|
opts = instance._meta
|
||||||
|
@ -71,15 +70,15 @@ def construct_instance(form, instance, fields=None, exclude=None):
|
||||||
|
|
||||||
def model_to_dict(instance, fields=None, exclude=None):
|
def model_to_dict(instance, fields=None, exclude=None):
|
||||||
"""
|
"""
|
||||||
Returns a dict containing the data in ``instance`` suitable for passing as
|
Return a dict containing the data in ``instance`` suitable for passing as
|
||||||
a Form's ``initial`` keyword argument.
|
a Form's ``initial`` keyword argument.
|
||||||
|
|
||||||
``fields`` is an optional list of field names. If provided, only the named
|
``fields`` is an optional list of field names. If provided, return only the
|
||||||
fields will be included in the returned dict.
|
named.
|
||||||
|
|
||||||
``exclude`` is an optional list of field names. If provided, the named
|
``exclude`` is an optional list of field names. If provided, exclude the
|
||||||
fields will be excluded from the returned dict, even if they are listed in
|
named from the returned dict, even if they are listed in the ``fields``
|
||||||
the ``fields`` argument.
|
argument.
|
||||||
"""
|
"""
|
||||||
opts = instance._meta
|
opts = instance._meta
|
||||||
data = {}
|
data = {}
|
||||||
|
@ -99,14 +98,14 @@ def fields_for_model(model, fields=None, exclude=None, widgets=None,
|
||||||
labels=None, help_texts=None, error_messages=None,
|
labels=None, help_texts=None, error_messages=None,
|
||||||
field_classes=None):
|
field_classes=None):
|
||||||
"""
|
"""
|
||||||
Returns a ``OrderedDict`` containing form fields for the given model.
|
Return an ``OrderedDict`` containing form fields for the given model.
|
||||||
|
|
||||||
``fields`` is an optional list of field names. If provided, only the named
|
``fields`` is an optional list of field names. If provided, return only the
|
||||||
fields will be included in the returned fields.
|
named fields.
|
||||||
|
|
||||||
``exclude`` is an optional list of field names. If provided, the named
|
``exclude`` is an optional list of field names. If provided, exclude the
|
||||||
fields will be excluded from the returned fields, even if they are listed
|
named fields from the returned fields, even if they are listed in the
|
||||||
in the ``fields`` argument.
|
``fields`` argument.
|
||||||
|
|
||||||
``widgets`` is a dictionary of model field names mapped to a widget.
|
``widgets`` is a dictionary of model field names mapped to a widget.
|
||||||
|
|
||||||
|
@ -296,9 +295,8 @@ class BaseModelForm(BaseForm):
|
||||||
|
|
||||||
def _get_validation_exclusions(self):
|
def _get_validation_exclusions(self):
|
||||||
"""
|
"""
|
||||||
For backwards-compatibility, several types of fields need to be
|
For backwards-compatibility, exclude several types of fields from model
|
||||||
excluded from model validation. See the following tickets for
|
validation. See tickets #12507, #12521, #12553.
|
||||||
details: #12507, #12521, #12553
|
|
||||||
"""
|
"""
|
||||||
exclude = []
|
exclude = []
|
||||||
# Build up a list of fields that should be excluded from model field
|
# Build up a list of fields that should be excluded from model field
|
||||||
|
@ -400,7 +398,7 @@ class BaseModelForm(BaseForm):
|
||||||
|
|
||||||
def validate_unique(self):
|
def validate_unique(self):
|
||||||
"""
|
"""
|
||||||
Calls the instance's validate_unique() method and updates the form's
|
Call the instance's validate_unique() method and update the form's
|
||||||
validation errors if any were raised.
|
validation errors if any were raised.
|
||||||
"""
|
"""
|
||||||
exclude = self._get_validation_exclusions()
|
exclude = self._get_validation_exclusions()
|
||||||
|
@ -465,15 +463,15 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
|
||||||
labels=None, help_texts=None, error_messages=None,
|
labels=None, help_texts=None, error_messages=None,
|
||||||
field_classes=None):
|
field_classes=None):
|
||||||
"""
|
"""
|
||||||
Returns a ModelForm containing form fields for the given model.
|
Return a ModelForm containing form fields for the given model.
|
||||||
|
|
||||||
``fields`` is an optional list of field names. If provided, only the named
|
``fields`` is an optional list of field names. If provided, include only
|
||||||
fields will be included in the returned fields. If omitted or '__all__',
|
the named fields in the returned fields. If omitted or '__all__', use all
|
||||||
all fields will be used.
|
fields.
|
||||||
|
|
||||||
``exclude`` is an optional list of field names. If provided, the named
|
``exclude`` is an optional list of field names. If provided, exclude the
|
||||||
fields will be excluded from the returned fields, even if they are listed
|
named fields from the returned fields, even if they are listed in the
|
||||||
in the ``fields`` argument.
|
``fields`` argument.
|
||||||
|
|
||||||
``widgets`` is a dictionary of model field names mapped to a widget.
|
``widgets`` is a dictionary of model field names mapped to a widget.
|
||||||
|
|
||||||
|
@ -561,7 +559,7 @@ class BaseModelFormSet(BaseFormSet):
|
||||||
super().__init__(**defaults)
|
super().__init__(**defaults)
|
||||||
|
|
||||||
def initial_form_count(self):
|
def initial_form_count(self):
|
||||||
"""Returns the number of forms that are required in this FormSet."""
|
"""Return the number of forms that are required in this FormSet."""
|
||||||
if not (self.data or self.files):
|
if not (self.data or self.files):
|
||||||
return len(self.get_queryset())
|
return len(self.get_queryset())
|
||||||
return super().initial_form_count()
|
return super().initial_form_count()
|
||||||
|
@ -618,11 +616,11 @@ class BaseModelFormSet(BaseFormSet):
|
||||||
return self._queryset
|
return self._queryset
|
||||||
|
|
||||||
def save_new(self, form, commit=True):
|
def save_new(self, form, commit=True):
|
||||||
"""Saves and returns a new model instance for the given form."""
|
"""Save and return a new model instance for the given form."""
|
||||||
return form.save(commit=commit)
|
return form.save(commit=commit)
|
||||||
|
|
||||||
def save_existing(self, form, instance, commit=True):
|
def save_existing(self, form, instance, commit=True):
|
||||||
"""Saves and returns an existing model instance for the given form."""
|
"""Save and return an existing model instance for the given form."""
|
||||||
return form.save(commit=commit)
|
return form.save(commit=commit)
|
||||||
|
|
||||||
def delete_existing(self, obj, commit=True):
|
def delete_existing(self, obj, commit=True):
|
||||||
|
@ -631,8 +629,9 @@ class BaseModelFormSet(BaseFormSet):
|
||||||
obj.delete()
|
obj.delete()
|
||||||
|
|
||||||
def save(self, commit=True):
|
def save(self, commit=True):
|
||||||
"""Saves model instances for every form, adding and changing instances
|
"""
|
||||||
as necessary, and returns the list of instances.
|
Save model instances for every form, adding and changing instances
|
||||||
|
as necessary, and return the list of instances.
|
||||||
"""
|
"""
|
||||||
if not commit:
|
if not commit:
|
||||||
self.saved_forms = []
|
self.saved_forms = []
|
||||||
|
@ -830,9 +829,7 @@ def modelformset_factory(model, form=ModelForm, formfield_callback=None,
|
||||||
widgets=None, validate_max=False, localized_fields=None,
|
widgets=None, validate_max=False, localized_fields=None,
|
||||||
labels=None, help_texts=None, error_messages=None,
|
labels=None, help_texts=None, error_messages=None,
|
||||||
min_num=None, validate_min=False, field_classes=None):
|
min_num=None, validate_min=False, field_classes=None):
|
||||||
"""
|
"""Return a FormSet class for the given Django model class."""
|
||||||
Returns a FormSet class for the given Django model class.
|
|
||||||
"""
|
|
||||||
meta = getattr(form, 'Meta', None)
|
meta = getattr(form, 'Meta', None)
|
||||||
if (getattr(meta, 'fields', fields) is None and
|
if (getattr(meta, 'fields', fields) is None and
|
||||||
getattr(meta, 'exclude', exclude) is None):
|
getattr(meta, 'exclude', exclude) is None):
|
||||||
|
@ -958,10 +955,10 @@ class BaseInlineFormSet(BaseModelFormSet):
|
||||||
|
|
||||||
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
|
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
|
||||||
"""
|
"""
|
||||||
Finds and returns the ForeignKey from model to parent if there is one
|
Find and return the ForeignKey from model to parent if there is one
|
||||||
(returns None if can_fail is True and no such field exists). If fk_name is
|
(return None if can_fail is True and no such field exists). If fk_name is
|
||||||
provided, assume it is the name of the ForeignKey field. Unless can_fail is
|
provided, assume it is the name of the ForeignKey field. Unless can_fail is
|
||||||
True, an exception is raised if there is no ForeignKey from model to
|
True, raise an exception if there isn't a ForeignKey from model to
|
||||||
parent_model.
|
parent_model.
|
||||||
"""
|
"""
|
||||||
# avoid circular import
|
# avoid circular import
|
||||||
|
@ -1019,9 +1016,9 @@ def inlineformset_factory(parent_model, model, form=ModelForm,
|
||||||
labels=None, help_texts=None, error_messages=None,
|
labels=None, help_texts=None, error_messages=None,
|
||||||
min_num=None, validate_min=False, field_classes=None):
|
min_num=None, validate_min=False, field_classes=None):
|
||||||
"""
|
"""
|
||||||
Returns an ``InlineFormSet`` for the given kwargs.
|
Return an ``InlineFormSet`` for the given kwargs.
|
||||||
|
|
||||||
You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
|
``fk_name`` must be provided if ``model`` has more than one ``ForeignKey``
|
||||||
to ``parent_model``.
|
to ``parent_model``.
|
||||||
"""
|
"""
|
||||||
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
|
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
|
||||||
|
@ -1147,10 +1144,9 @@ class ModelChoiceField(ChoiceField):
|
||||||
|
|
||||||
def get_limit_choices_to(self):
|
def get_limit_choices_to(self):
|
||||||
"""
|
"""
|
||||||
Returns ``limit_choices_to`` for this form field.
|
Return ``limit_choices_to`` for this form field.
|
||||||
|
|
||||||
If it is a callable, it will be invoked and the result will be
|
If it is a callable, invoke it and return the result.
|
||||||
returned.
|
|
||||||
"""
|
"""
|
||||||
if callable(self.limit_choices_to):
|
if callable(self.limit_choices_to):
|
||||||
return self.limit_choices_to()
|
return self.limit_choices_to()
|
||||||
|
@ -1175,9 +1171,9 @@ class ModelChoiceField(ChoiceField):
|
||||||
# Override it to customize the label.
|
# Override it to customize the label.
|
||||||
def label_from_instance(self, obj):
|
def label_from_instance(self, obj):
|
||||||
"""
|
"""
|
||||||
This method is used to convert objects into strings; it's used to
|
Convert objects into strings and generate the labels for the choices
|
||||||
generate the labels for the choices presented by this object. Subclasses
|
presented by this object. Subclasses can override this method to
|
||||||
can override this method to customize the display of the choices.
|
customize the display of the choices.
|
||||||
"""
|
"""
|
||||||
return force_text(obj)
|
return force_text(obj)
|
||||||
|
|
||||||
|
@ -1264,8 +1260,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
|
||||||
|
|
||||||
def _check_values(self, value):
|
def _check_values(self, value):
|
||||||
"""
|
"""
|
||||||
Given a list of possible PK values, returns a QuerySet of the
|
Given a list of possible PK values, return a QuerySet of the
|
||||||
corresponding objects. Raises a ValidationError if a given value is
|
corresponding objects. Raise a ValidationError if a given value is
|
||||||
invalid (not a valid PK, not in the queryset, etc.)
|
invalid (not a valid PK, not in the queryset, etc.)
|
||||||
"""
|
"""
|
||||||
key = self.to_field_name or 'pk'
|
key = self.to_field_name or 'pk'
|
||||||
|
|
|
@ -10,7 +10,7 @@ from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
|
||||||
def pretty_name(name):
|
def pretty_name(name):
|
||||||
"""Converts 'first_name' to 'First name'"""
|
"""Convert 'first_name' to 'First name'."""
|
||||||
if not name:
|
if not name:
|
||||||
return ''
|
return ''
|
||||||
return name.replace('_', ' ').capitalize()
|
return name.replace('_', ' ').capitalize()
|
||||||
|
|
|
@ -83,7 +83,7 @@ class Media:
|
||||||
return static(path)
|
return static(path)
|
||||||
|
|
||||||
def __getitem__(self, name):
|
def __getitem__(self, name):
|
||||||
"Returns a Media object that only contains media of the given type"
|
"""Return a Media object that only contains media of the given type."""
|
||||||
if name in MEDIA_TYPES:
|
if name in MEDIA_TYPES:
|
||||||
return Media(**{str(name): getattr(self, '_' + name)})
|
return Media(**{str(name): getattr(self, '_' + name)})
|
||||||
raise KeyError('Unknown media type "%s"' % name)
|
raise KeyError('Unknown media type "%s"' % name)
|
||||||
|
@ -209,7 +209,7 @@ class Widget(metaclass=MediaDefiningClass):
|
||||||
return mark_safe(renderer.render(template_name, context))
|
return mark_safe(renderer.render(template_name, context))
|
||||||
|
|
||||||
def build_attrs(self, base_attrs, extra_attrs=None):
|
def build_attrs(self, base_attrs, extra_attrs=None):
|
||||||
"Helper function for building an attribute dictionary."
|
"""Build an attribute dictionary."""
|
||||||
attrs = base_attrs.copy()
|
attrs = base_attrs.copy()
|
||||||
if extra_attrs is not None:
|
if extra_attrs is not None:
|
||||||
attrs.update(extra_attrs)
|
attrs.update(extra_attrs)
|
||||||
|
@ -217,8 +217,8 @@ class Widget(metaclass=MediaDefiningClass):
|
||||||
|
|
||||||
def value_from_datadict(self, data, files, name):
|
def value_from_datadict(self, data, files, name):
|
||||||
"""
|
"""
|
||||||
Given a dictionary of data and this widget's name, returns the value
|
Given a dictionary of data and this widget's name, return the value
|
||||||
of this widget. Returns None if it's not provided.
|
of this widget or None if it's not provided.
|
||||||
"""
|
"""
|
||||||
return data.get(name)
|
return data.get(name)
|
||||||
|
|
||||||
|
@ -227,8 +227,8 @@ class Widget(metaclass=MediaDefiningClass):
|
||||||
|
|
||||||
def id_for_label(self, id_):
|
def id_for_label(self, id_):
|
||||||
"""
|
"""
|
||||||
Returns the HTML ID attribute of this Widget for use by a <label>,
|
Return the HTML ID attribute of this Widget for use by a <label>,
|
||||||
given the ID of the field. Returns None if no ID is available.
|
given the ID of the field. Return None if no ID is available.
|
||||||
|
|
||||||
This hook is necessary because some widgets have multiple HTML
|
This hook is necessary because some widgets have multiple HTML
|
||||||
elements and, thus, multiple IDs. In that case, this method should
|
elements and, thus, multiple IDs. In that case, this method should
|
||||||
|
@ -301,7 +301,7 @@ class HiddenInput(Input):
|
||||||
|
|
||||||
class MultipleHiddenInput(HiddenInput):
|
class MultipleHiddenInput(HiddenInput):
|
||||||
"""
|
"""
|
||||||
A widget that handles <input type="hidden"> for fields that have a list
|
Handle <input type="hidden"> for fields that have a list
|
||||||
of values.
|
of values.
|
||||||
"""
|
"""
|
||||||
template_name = 'django/forms/widgets/multiple_hidden.html'
|
template_name = 'django/forms/widgets/multiple_hidden.html'
|
||||||
|
@ -816,14 +816,17 @@ class MultiWidget(Widget):
|
||||||
|
|
||||||
def decompress(self, value):
|
def decompress(self, value):
|
||||||
"""
|
"""
|
||||||
Returns a list of decompressed values for the given compressed value.
|
Return a list of decompressed values for the given compressed value.
|
||||||
The given value can be assumed to be valid, but not necessarily
|
The given value can be assumed to be valid, but not necessarily
|
||||||
non-empty.
|
non-empty.
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError('Subclasses must implement this method.')
|
raise NotImplementedError('Subclasses must implement this method.')
|
||||||
|
|
||||||
def _get_media(self):
|
def _get_media(self):
|
||||||
"Media for a multiwidget is the combination of all media of the subwidgets"
|
"""
|
||||||
|
Media for a multiwidget is the combination of all media of the
|
||||||
|
subwidgets.
|
||||||
|
"""
|
||||||
media = Media()
|
media = Media()
|
||||||
for w in self.widgets:
|
for w in self.widgets:
|
||||||
media = media + w.media
|
media = media + w.media
|
||||||
|
@ -842,7 +845,7 @@ class MultiWidget(Widget):
|
||||||
|
|
||||||
class SplitDateTimeWidget(MultiWidget):
|
class SplitDateTimeWidget(MultiWidget):
|
||||||
"""
|
"""
|
||||||
A Widget that splits datetime input into two <input type="text"> boxes.
|
A widget that splits datetime input into two <input type="text"> boxes.
|
||||||
"""
|
"""
|
||||||
supports_microseconds = False
|
supports_microseconds = False
|
||||||
template_name = 'django/forms/widgets/splitdatetime.html'
|
template_name = 'django/forms/widgets/splitdatetime.html'
|
||||||
|
@ -869,7 +872,7 @@ class SplitDateTimeWidget(MultiWidget):
|
||||||
|
|
||||||
class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
|
class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
|
||||||
"""
|
"""
|
||||||
A Widget that splits datetime input into two <input type="hidden"> inputs.
|
A widget that splits datetime input into two <input type="hidden"> inputs.
|
||||||
"""
|
"""
|
||||||
template_name = 'django/forms/widgets/splithiddendatetime.html'
|
template_name = 'django/forms/widgets/splithiddendatetime.html'
|
||||||
|
|
||||||
|
@ -881,7 +884,7 @@ class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
|
||||||
|
|
||||||
class SelectDateWidget(Widget):
|
class SelectDateWidget(Widget):
|
||||||
"""
|
"""
|
||||||
A Widget that splits date input into three <select> boxes.
|
A widget that splits date input into three <select> boxes.
|
||||||
|
|
||||||
This also serves as an example of a Widget that has more than one HTML
|
This also serves as an example of a Widget that has more than one HTML
|
||||||
element and hence implements value_from_datadict.
|
element and hence implements value_from_datadict.
|
||||||
|
|
|
@ -366,9 +366,8 @@ class LazyStream:
|
||||||
"""
|
"""
|
||||||
Used when the exact number of bytes to read is unimportant.
|
Used when the exact number of bytes to read is unimportant.
|
||||||
|
|
||||||
This procedure just returns whatever is chunk is conveniently returned
|
Return whatever chunk is conveniently returned from the iterator.
|
||||||
from the iterator instead. Useful to avoid unnecessary bookkeeping if
|
Useful to avoid unnecessary bookkeeping if performance is an issue.
|
||||||
performance is an issue.
|
|
||||||
"""
|
"""
|
||||||
if self._leftover:
|
if self._leftover:
|
||||||
output = self._leftover
|
output = self._leftover
|
||||||
|
@ -383,7 +382,7 @@ class LazyStream:
|
||||||
"""
|
"""
|
||||||
Used to invalidate/disable this lazy stream.
|
Used to invalidate/disable this lazy stream.
|
||||||
|
|
||||||
Replaces the producer with an empty list. Any leftover bytes that have
|
Replace the producer with an empty list. Any leftover bytes that have
|
||||||
already been read will still be reported upon read() and/or next().
|
already been read will still be reported upon read() and/or next().
|
||||||
"""
|
"""
|
||||||
self._producer = []
|
self._producer = []
|
||||||
|
@ -393,7 +392,7 @@ class LazyStream:
|
||||||
|
|
||||||
def unget(self, bytes):
|
def unget(self, bytes):
|
||||||
"""
|
"""
|
||||||
Places bytes back onto the front of the lazy stream.
|
Place bytes back onto the front of the lazy stream.
|
||||||
|
|
||||||
Future calls to read() will return those bytes first. The
|
Future calls to read() will return those bytes first. The
|
||||||
stream position and thus tell() will be rewound.
|
stream position and thus tell() will be rewound.
|
||||||
|
@ -406,7 +405,7 @@ class LazyStream:
|
||||||
|
|
||||||
def _update_unget_history(self, num_bytes):
|
def _update_unget_history(self, num_bytes):
|
||||||
"""
|
"""
|
||||||
Updates the unget history as a sanity check to see if we've pushed
|
Update the unget history as a sanity check to see if we've pushed
|
||||||
back the same number of bytes in one chunk. If we keep ungetting the
|
back the same number of bytes in one chunk. If we keep ungetting the
|
||||||
same number of bytes many times (here, 50), we're mostly likely in an
|
same number of bytes many times (here, 50), we're mostly likely in an
|
||||||
infinite loop of some sort. This is usually caused by a
|
infinite loop of some sort. This is usually caused by a
|
||||||
|
@ -429,8 +428,7 @@ class LazyStream:
|
||||||
class ChunkIter:
|
class ChunkIter:
|
||||||
"""
|
"""
|
||||||
An iterable that will yield chunks of data. Given a file-like object as the
|
An iterable that will yield chunks of data. Given a file-like object as the
|
||||||
constructor, this object will yield chunks of read operations from that
|
constructor, yield chunks of read operations from that object.
|
||||||
object.
|
|
||||||
"""
|
"""
|
||||||
def __init__(self, flo, chunk_size=64 * 1024):
|
def __init__(self, flo, chunk_size=64 * 1024):
|
||||||
self.flo = flo
|
self.flo = flo
|
||||||
|
@ -541,11 +539,10 @@ class BoundaryIter:
|
||||||
|
|
||||||
def _find_boundary(self, data, eof=False):
|
def _find_boundary(self, data, eof=False):
|
||||||
"""
|
"""
|
||||||
Finds a multipart boundary in data.
|
Find a multipart boundary in data.
|
||||||
|
|
||||||
Should no boundary exist in the data None is returned instead. Otherwise
|
|
||||||
a tuple containing the indices of the following are returned:
|
|
||||||
|
|
||||||
|
Should no boundary exist in the data, return None. Otherwise, return
|
||||||
|
a tuple containing the indices of the following:
|
||||||
* the end of current encapsulation
|
* the end of current encapsulation
|
||||||
* the start of the next encapsulation
|
* the start of the next encapsulation
|
||||||
"""
|
"""
|
||||||
|
@ -578,7 +575,7 @@ def exhaust(stream_or_iterable):
|
||||||
|
|
||||||
def parse_boundary_stream(stream, max_header_size):
|
def parse_boundary_stream(stream, max_header_size):
|
||||||
"""
|
"""
|
||||||
Parses one and exactly one stream that encapsulates a boundary.
|
Parse one and exactly one stream that encapsulates a boundary.
|
||||||
"""
|
"""
|
||||||
# Stream at beginning of header, look for end of header
|
# Stream at beginning of header, look for end of header
|
||||||
# and parse it if found. The header must fit within one
|
# and parse it if found. The header must fit within one
|
||||||
|
|
|
@ -121,9 +121,9 @@ class HttpRequest:
|
||||||
|
|
||||||
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
|
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
|
||||||
"""
|
"""
|
||||||
Attempts to return a signed cookie. If the signature fails or the
|
Attempt to return a signed cookie. If the signature fails or the
|
||||||
cookie has expired, raises an exception... unless you provide the
|
cookie has expired, raise an exception, unless the `default` argument
|
||||||
default argument in which case that value will be returned instead.
|
is provided, in which case return that value.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
cookie_value = self.COOKIES[key]
|
cookie_value = self.COOKIES[key]
|
||||||
|
@ -155,13 +155,12 @@ class HttpRequest:
|
||||||
|
|
||||||
def build_absolute_uri(self, location=None):
|
def build_absolute_uri(self, location=None):
|
||||||
"""
|
"""
|
||||||
Builds an absolute URI from the location and the variables available in
|
Build an absolute URI from the location and the variables available in
|
||||||
this request. If no ``location`` is specified, the absolute URI is
|
this request. If no ``location`` is specified, bulid the absolute URI
|
||||||
built on ``request.get_full_path()``. Anyway, if the location is
|
using request.get_full_path(). If the location is absolute, convert it
|
||||||
absolute, it is simply converted to an RFC 3987 compliant URI and
|
to an RFC 3987 compliant URI and return it. If location is relative or
|
||||||
returned and if location is relative or is scheme-relative (i.e.,
|
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
|
||||||
``//example.com/``), it is urljoined to a base URL constructed from the
|
URL constructed from the request variables.
|
||||||
request variables.
|
|
||||||
"""
|
"""
|
||||||
if location is None:
|
if location is None:
|
||||||
# Make it an absolute url (but schemeless and domainless) for the
|
# Make it an absolute url (but schemeless and domainless) for the
|
||||||
|
@ -180,7 +179,7 @@ class HttpRequest:
|
||||||
|
|
||||||
def _get_scheme(self):
|
def _get_scheme(self):
|
||||||
"""
|
"""
|
||||||
Hook for subclasses like WSGIRequest to implement. Returns 'http' by
|
Hook for subclasses like WSGIRequest to implement. Return 'http' by
|
||||||
default.
|
default.
|
||||||
"""
|
"""
|
||||||
return 'http'
|
return 'http'
|
||||||
|
@ -211,8 +210,8 @@ class HttpRequest:
|
||||||
@encoding.setter
|
@encoding.setter
|
||||||
def encoding(self, val):
|
def encoding(self, val):
|
||||||
"""
|
"""
|
||||||
Sets the encoding used for GET/POST accesses. If the GET or POST
|
Set the encoding used for GET/POST accesses. If the GET or POST
|
||||||
dictionary has already been created, it is removed and recreated on the
|
dictionary has already been created, remove and recreate it on the
|
||||||
next access (so that it is decoded correctly).
|
next access (so that it is decoded correctly).
|
||||||
"""
|
"""
|
||||||
self._encoding = val
|
self._encoding = val
|
||||||
|
@ -239,7 +238,7 @@ class HttpRequest:
|
||||||
self._upload_handlers = upload_handlers
|
self._upload_handlers = upload_handlers
|
||||||
|
|
||||||
def parse_file_upload(self, META, post_data):
|
def parse_file_upload(self, META, post_data):
|
||||||
"""Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
|
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
|
||||||
self.upload_handlers = ImmutableList(
|
self.upload_handlers = ImmutableList(
|
||||||
self.upload_handlers,
|
self.upload_handlers,
|
||||||
warning="You cannot alter upload handlers after the upload has been processed."
|
warning="You cannot alter upload handlers after the upload has been processed."
|
||||||
|
@ -469,22 +468,21 @@ class QueryDict(MultiValueDict):
|
||||||
return super().setdefault(key, default)
|
return super().setdefault(key, default)
|
||||||
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
"""Returns a mutable copy of this object."""
|
"""Return a mutable copy of this object."""
|
||||||
return self.__deepcopy__({})
|
return self.__deepcopy__({})
|
||||||
|
|
||||||
def urlencode(self, safe=None):
|
def urlencode(self, safe=None):
|
||||||
"""
|
"""
|
||||||
Returns an encoded string of all query string arguments.
|
Return an encoded string of all query string arguments.
|
||||||
|
|
||||||
:arg safe: Used to specify characters which do not require quoting, for
|
`safe` specifies characters which don't require quoting, for example::
|
||||||
example::
|
|
||||||
|
|
||||||
>>> q = QueryDict(mutable=True)
|
>>> q = QueryDict(mutable=True)
|
||||||
>>> q['next'] = '/a&b/'
|
>>> q['next'] = '/a&b/'
|
||||||
>>> q.urlencode()
|
>>> q.urlencode()
|
||||||
'next=%2Fa%26b%2F'
|
'next=%2Fa%26b%2F'
|
||||||
>>> q.urlencode(safe='/')
|
>>> q.urlencode(safe='/')
|
||||||
'next=/a%26b/'
|
'next=/a%26b/'
|
||||||
"""
|
"""
|
||||||
output = []
|
output = []
|
||||||
if safe:
|
if safe:
|
||||||
|
|
|
@ -104,11 +104,11 @@ class HttpResponseBase:
|
||||||
return ', "%s"' % self['Content-Type'] if 'Content-Type' in self else ''
|
return ', "%s"' % self['Content-Type'] if 'Content-Type' in self else ''
|
||||||
|
|
||||||
def _convert_to_charset(self, value, charset, mime_encode=False):
|
def _convert_to_charset(self, value, charset, mime_encode=False):
|
||||||
"""Converts headers key/value to ascii/latin-1 native strings.
|
"""
|
||||||
|
Convert headers key/value to ascii/latin-1 native strings.
|
||||||
|
|
||||||
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
|
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
|
||||||
`value` can't be represented in the given charset, MIME-encoding
|
`value` can't be represented in the given charset, apply MIME-encoding.
|
||||||
is applied.
|
|
||||||
"""
|
"""
|
||||||
if not isinstance(value, (bytes, str)):
|
if not isinstance(value, (bytes, str)):
|
||||||
value = str(value)
|
value = str(value)
|
||||||
|
@ -159,13 +159,13 @@ class HttpResponseBase:
|
||||||
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
|
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
|
||||||
domain=None, secure=False, httponly=False):
|
domain=None, secure=False, httponly=False):
|
||||||
"""
|
"""
|
||||||
Sets a cookie.
|
Set a cookie.
|
||||||
|
|
||||||
``expires`` can be:
|
``expires`` can be:
|
||||||
- a string in the correct format,
|
- a string in the correct format,
|
||||||
- a naive ``datetime.datetime`` object in UTC,
|
- a naive ``datetime.datetime`` object in UTC,
|
||||||
- an aware ``datetime.datetime`` object in any time zone.
|
- an aware ``datetime.datetime`` object in any time zone.
|
||||||
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
|
If it is a ``datetime.datetime`` object then calculate ``max_age``.
|
||||||
"""
|
"""
|
||||||
self.cookies[key] = value
|
self.cookies[key] = value
|
||||||
if expires is not None:
|
if expires is not None:
|
||||||
|
@ -200,7 +200,7 @@ class HttpResponseBase:
|
||||||
self.cookies[key]['httponly'] = True
|
self.cookies[key]['httponly'] = True
|
||||||
|
|
||||||
def setdefault(self, key, value):
|
def setdefault(self, key, value):
|
||||||
"""Sets a header unless it has already been set."""
|
"""Set a header unless it has already been set."""
|
||||||
if key not in self:
|
if key not in self:
|
||||||
self[key] = value
|
self[key] = value
|
||||||
|
|
||||||
|
@ -274,7 +274,7 @@ class HttpResponse(HttpResponseBase):
|
||||||
"""
|
"""
|
||||||
An HTTP response class with a string as content.
|
An HTTP response class with a string as content.
|
||||||
|
|
||||||
This content that can be read, appended to or replaced.
|
This content that can be read, appended to, or replaced.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
streaming = False
|
streaming = False
|
||||||
|
|
Loading…
Reference in New Issue