Refs #27656 -- Updated django.forms/http docstring verbs according to PEP 257.

This commit is contained in:
Anton Samarchyan 2017-01-24 16:23:56 -05:00 committed by Tim Graham
parent afcf44c101
commit 3eb679a869
11 changed files with 225 additions and 266 deletions

View File

@ -118,7 +118,7 @@ class Signal:
Disconnect receiver from sender for signal.
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:
@ -168,7 +168,7 @@ class Signal:
named
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:
return []
@ -194,12 +194,10 @@ class Signal:
arguments must be a subset of the argument names defined in
providing_args.
Return a list of tuple pairs [(receiver, response), ... ]. May raise
DispatcherKeyError.
Return a list of tuple pairs [(receiver, response), ... ].
If any receiver raises an error (specifically any subclass of
Exception), the error instance is returned as the result for that
receiver.
Exception), return the error instance as the result for that receiver.
"""
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return []

View File

@ -31,7 +31,7 @@ class BoundField:
self.help_text = field.help_text or ''
def __str__(self):
"""Renders this field as an HTML widget."""
"""Render this field as an HTML widget."""
if self.field.show_hidden_initial:
return self.as_widget() + self.as_hidden(only_initial=True)
return self.as_widget()
@ -69,16 +69,15 @@ class BoundField:
@property
def errors(self):
"""
Returns an ErrorList for this field. Returns an empty ErrorList
if there are none.
Return an ErrorList (empty if there are no errors) for this field.
"""
return self.form.errors.get(self.name, self.form.error_class())
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
Render the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If a widget isn't specified, use the
field's default widget.
"""
if not widget:
widget = self.field.widget
@ -119,30 +118,30 @@ class BoundField:
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)
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)
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)
@property
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)
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.
"""
data = self.initial
@ -152,13 +151,13 @@ class BoundField:
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.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.
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
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
if label_suffix is None:
@ -189,7 +188,7 @@ class BoundField:
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'):
extra_classes = extra_classes.split()
@ -202,14 +201,14 @@ class BoundField:
@property
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
@property
def auto_id(self):
"""
Calculates and returns the ID attribute for this BoundField, if the
associated Form has specified auto_id. Returns an empty string otherwise.
Calculate and return the ID attribute for this BoundField, if the
associated Form has specified auto_id. Return an empty string otherwise.
"""
auto_id = self.form.auto_id
if auto_id and '%s' in force_text(auto_id):

View File

@ -142,10 +142,8 @@ class Field:
def clean(self, value):
"""
Validates the given value and returns its "cleaned" value as an
appropriate Python object.
Raises ValidationError for any errors.
Validate the given value and return its "cleaned" value as an
appropriate Python object. Raise ValidationError for any errors.
"""
value = self.to_python(value)
self.validate(value)
@ -167,16 +165,14 @@ class Field:
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
Field.
"""
return {}
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 uses the initial value in this case.
if self.disabled:
@ -222,7 +218,7 @@ class CharField(Field):
self.validators.append(validators.MaxLengthValidator(int(max_length)))
def to_python(self, value):
"Returns a string."
"""Return a string."""
if value in self.empty_values:
return self.empty_value
value = force_text(value)
@ -262,8 +258,8 @@ class IntegerField(Field):
def to_python(self, value):
"""
Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.
Validate that int() can be called on the input. Return the result
of int() or None for empty values.
"""
value = super().to_python(value)
if value in self.empty_values:
@ -294,8 +290,8 @@ class FloatField(IntegerField):
def to_python(self, value):
"""
Validates that float() can be called on the input. Returns the result
of float(). Returns None for empty values.
Validate that float() can be called on the input. Return the result
of float() or None for empty values.
"""
value = super(IntegerField, self).to_python(value)
if value in self.empty_values:
@ -336,9 +332,9 @@ class DecimalField(IntegerField):
def to_python(self, value):
"""
Validates that the input is a decimal number. Returns a Decimal
instance. Returns None for empty values. Ensures that there are no more
than max_digits in the number, and no more than decimal_places digits
Validate that the input is a decimal number. Return a Decimal
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
after the decimal point.
"""
if value in self.empty_values:
@ -405,7 +401,7 @@ class DateField(BaseTemporalField):
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.
"""
if value in self.empty_values:
@ -429,7 +425,7 @@ class TimeField(BaseTemporalField):
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.
"""
if value in self.empty_values:
@ -456,7 +452,7 @@ class DateTimeField(BaseTemporalField):
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.
"""
if value in self.empty_values:
@ -605,8 +601,8 @@ class ImageField(FileField):
def to_python(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Pillow supports).
"""
f = super().to_python(data)
if f is None:
@ -661,8 +657,8 @@ class URLField(CharField):
def split_url(url):
"""
Returns a list of url parts via ``urlparse.urlsplit`` (or raises a
``ValidationError`` exception for certain).
Return a list of url parts via urlparse.urlsplit(), or raise
ValidationError for some malformed URLs.
"""
try:
return list(urlsplit(url))
@ -693,7 +689,7 @@ class BooleanField(Field):
widget = CheckboxInput
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
# will submit for False. Also check for '0', since this is what
# RadioSelect will provide. Because bool("True") == bool('1') == True,
@ -716,19 +712,19 @@ class BooleanField(Field):
class NullBooleanField(BooleanField):
"""
A field whose valid values are None, True and False. Invalid values are
cleaned to None.
A field whose valid values are None, True, and False. Clean invalid values
to None.
"""
widget = NullBooleanSelect
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',
which are likely to be returned by JavaScript serializations of forms,
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
not using the bool() function
the Booleanfield, this field must check for True because it doesn't
use the bool() function.
"""
if value in (True, 'True', 'true', '1'):
return True
@ -786,15 +782,13 @@ class ChoiceField(Field):
choices = property(_get_choices, _set_choices)
def to_python(self, value):
"Return a string."
"""Return a string."""
if value in self.empty_values:
return ''
return force_text(value)
def validate(self, value):
"""
Validates that the input is in self.choices.
"""
"""Validate that the input is in self.choices."""
super().validate(value)
if value and not self.valid_value(value):
raise ValidationError(
@ -804,7 +798,7 @@ class ChoiceField(Field):
)
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)
for k, v in self.choices:
if isinstance(v, (list, tuple)):
@ -861,9 +855,7 @@ class MultipleChoiceField(ChoiceField):
return [force_text(val) for val in value]
def validate(self, value):
"""
Validates that the input is a list or tuple.
"""
"""Validate that the input is a list or tuple."""
if self.required and not value:
raise ValidationError(self.error_messages['required'], code='required')
# Validate that each value in the value list is in self.choices.
@ -895,7 +887,7 @@ class TypedMultipleChoiceField(MultipleChoiceField):
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.
"""
if value == self.empty_value or value in self.empty_values:
@ -938,7 +930,7 @@ class ComboField(Field):
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.
"""
super().clean(value)
@ -949,7 +941,7 @@ class ComboField(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
cleaned into a single value according to self.fields. Each value in
@ -992,7 +984,7 @@ class MultiValueField(Field):
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.
For example, if this MultiValueField was instantiated with
@ -1044,7 +1036,7 @@ class MultiValueField(Field):
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.
For example, if this MultiValueField was instantiated with

View File

@ -24,9 +24,7 @@ __all__ = ('BaseForm', 'Form')
class DeclarativeFieldsMetaclass(MediaDefiningClass):
"""
Metaclass that collects Fields declared on the base classes.
"""
"""Collect Fields declared on the base classes."""
def __new__(mcs, name, bases, attrs):
# Collect fields from current class.
current_fields = []
@ -63,10 +61,12 @@ class DeclarativeFieldsMetaclass(MediaDefiningClass):
@html_safe
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
# information. Any improvements to the form API should be made to *this*
# class, not to the Form class.
"""
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 info. Any
improvements to the form API should be made to this class, not to the Form
class.
"""
default_renderer = None
field_order = None
prefix = None
@ -113,14 +113,14 @@ class BaseForm:
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
included in the list are appended in the default order for backward
compatibility with subclasses not overriding field_order. If field_order
is None, all fields are kept in the order defined in the class.
Unknown fields in field_order are ignored to allow disabling fields in
form subclasses without redefining ordering.
field_order is a list of field names specifying the order. Append fields
not included in the list in the default order for backward compatibility
with subclasses not overriding field_order. If field_order is None,
keep all fields in the order defined in the class. Ignore unknown
fields in field_order to allow disabling fields in form subclasses
without redefining ordering.
"""
if field_order is None:
return
@ -153,7 +153,7 @@ class BaseForm:
yield self[name]
def __getitem__(self, name):
"Returns a BoundField with the given name."
"""Return a BoundField with the given name."""
try:
field = self.fields[name]
except KeyError:
@ -170,21 +170,18 @@ class BaseForm:
@property
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:
self.full_clean()
return self._errors
def is_valid(self):
"""
Returns True if the form has no errors. Otherwise, False. If errors are
being ignored, returns False.
"""
"""Return True if the form has no errors, or False otherwise."""
return self.is_bound and not self.errors
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.
Subclasses may wish to override.
@ -192,13 +189,11 @@ class BaseForm:
return '%s-%s' % (self.prefix, field_name) if self.prefix else 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)
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.
output, hidden_fields = [], []
@ -276,7 +271,7 @@ class BaseForm:
return mark_safe('\n'.join(output))
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(
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>',
@ -285,7 +280,7 @@ class BaseForm:
errors_on_separate_row=False)
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(
normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
error_row='<li>%s</li>',
@ -294,7 +289,7 @@ class BaseForm:
errors_on_separate_row=False)
def as_p(self):
"Returns this form rendered as HTML <p>s."
"Return this form rendered as HTML <p>s."
return self._html_output(
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
error_row='%s',
@ -304,8 +299,8 @@ class BaseForm:
def non_field_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
Return an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Return an empty ErrorList if there
are none.
"""
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`.
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
NON_FIELD_ERRORS.
should be added. If it's None, treat the errors as NON_FIELD_ERRORS.
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
an "error" can be either a simple string or an instance of
ValidationError with its message attribute set and what we define as
list or dictionary can be an actual `list` or `dict` or an instance
of ValidationError with its `error_list` or `error_dict` attribute set.
dictionary that maps field names to lists of errors. An "error" can be
either a simple string or an instance of ValidationError with its
message attribute set and a "list or dictionary" can be an actual
`list` or `dict` or an instance of ValidationError with its
`error_list` or `error_dict` attribute set.
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
@ -369,8 +363,7 @@ class BaseForm:
def full_clean(self):
"""
Cleans all of self.data and populates self._errors and
self.cleaned_data.
Clean all of self.data and populate self._errors and self.cleaned_data.
"""
self._errors = ErrorDict()
if not self.is_bound: # Stop further processing.
@ -433,9 +426,7 @@ class BaseForm:
return self.cleaned_data
def has_changed(self):
"""
Returns True if data differs from initial.
"""
"""Return True if data differs from initial."""
return bool(self.changed_data)
@cached_property
@ -464,9 +455,7 @@ class BaseForm:
@property
def media(self):
"""
Provide a description of all media required to render the widgets on this form
"""
"""Return all media required to render the widgets on this form."""
media = Media()
for field in self.fields.values():
media = media + field.widget.media
@ -474,8 +463,8 @@ class BaseForm:
def is_multipart(self):
"""
Returns True if the form needs to be multipart-encoded, i.e. it has
FileInput. Otherwise, False.
Return True if the form needs to be multipart-encoded, i.e. it has
FileInput, or False otherwise.
"""
for field in self.fields.values():
if field.widget.needs_multipart_form:
@ -484,14 +473,14 @@ class BaseForm:
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.
"""
return [field for field in self if field.is_hidden]
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.
"""
return [field for field in self if not field.is_hidden]

View File

@ -27,9 +27,9 @@ DEFAULT_MAX_NUM = 1000
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
Keep track of how many form instances are displayed on the page. If adding
new forms via JavaScript, you should increment the count field of this form
as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
@ -64,23 +64,26 @@ class BaseFormSet:
return self.as_table()
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)
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]
def __len__(self):
return len(self.forms)
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
@cached_property
def management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
"""Return the ManagementForm instance for this FormSet."""
if self.is_bound:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
@ -98,7 +101,7 @@ class BaseFormSet:
return form
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:
# return absolute_max if it is lower than the actual total form
# count in the data; this is DoS protection to prevent clients
@ -117,7 +120,7 @@ class BaseFormSet:
return total_forms
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:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
@ -127,9 +130,7 @@ class BaseFormSet:
@cached_property
def forms(self):
"""
Instantiate forms at first property access.
"""
"""Instantiate forms at first property access."""
# DoS protection is included in total_form_count()
forms = [self._construct_form(i, **self.get_form_kwargs(i))
for i in range(self.total_form_count())]
@ -145,9 +146,7 @@ class BaseFormSet:
return self.form_kwargs.copy()
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
"""Instantiate and return the i-th form instance in a formset."""
defaults = {
'auto_id': self.auto_id,
'prefix': self.add_prefix(i),
@ -199,7 +198,7 @@ class BaseFormSet:
@property
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():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
@ -207,9 +206,7 @@ class BaseFormSet:
@property
def deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion.
"""
"""Return a list of forms that have been marked for deletion."""
if not self.is_valid() or not self.can_delete:
return []
# construct _deleted_form_indexes which is just a list of form indexes
@ -228,8 +225,8 @@ class BaseFormSet:
@property
def ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
Return a list of form in the order specified by the incoming data.
Raise an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
@ -269,8 +266,8 @@ class BaseFormSet:
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
Return an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Return an empty ErrorList if there
are none.
"""
if self._non_form_errors is None:
@ -279,30 +276,22 @@ class BaseFormSet:
@property
def errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
"""Return a list of form.errors for every form in self.forms."""
if self._errors is None:
self.full_clean()
return self._errors
def total_error_count(self):
"""
Returns the number of errors across all forms in the formset.
"""
"""Return the number of errors across all forms in the formset."""
return len(self.non_form_errors()) +\
sum(len(form_errors) for form_errors in self.errors)
def _should_delete_form(self, form):
"""
Returns whether or not the form was marked for deletion.
"""
"""Return whether or not the form was marked for deletion."""
return form.cleaned_data.get(DELETION_FIELD_NAME, False)
def is_valid(self):
"""
Returns True if every form in self.forms is valid.
"""
"""Return True if every form in self.forms is valid."""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
@ -322,7 +311,7 @@ class BaseFormSet:
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._errors = []
@ -367,9 +356,7 @@ class BaseFormSet:
pass
def has_changed(self):
"""
Returns true if data in any form differs from initial.
"""
"""Return True if data in any form differs from initial."""
return any(form.has_changed() for form in self)
def add_fields(self, form, index):
@ -388,8 +375,8 @@ class BaseFormSet:
def is_multipart(self):
"""
Returns True if the formset needs to be multipart, i.e. it
has FileInput. Otherwise, False.
Return True if the formset needs to be multipart, i.e. it
has FileInput, or False otherwise.
"""
if self.forms:
return self.forms[0].is_multipart()
@ -406,7 +393,7 @@ class BaseFormSet:
return self.empty_form.media
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
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
@ -414,12 +401,12 @@ class BaseFormSet:
return mark_safe('\n'.join([str(self.management_form), forms]))
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)
return mark_safe('\n'.join([str(self.management_form), forms]))
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)
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):
"""Returns true if every formset in formsets is valid."""
"""Return True if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():

View File

@ -32,9 +32,8 @@ ALL_FIELDS = '__all__'
def construct_instance(form, instance, fields=None, exclude=None):
"""
Constructs and returns a model instance from the bound ``form``'s
``cleaned_data``, but does not save the returned instance to the
database.
Construct and return a model instance from the bound ``form``'s
``cleaned_data``, but do not save the returned instance to the database.
"""
from django.db import models
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):
"""
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.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``fields`` is an optional list of field names. If provided, return only the
named.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
``exclude`` is an optional list of field names. If provided, exclude the
named from the returned dict, even if they are listed in the ``fields``
argument.
"""
opts = instance._meta
data = {}
@ -99,14 +98,14 @@ def fields_for_model(model, fields=None, exclude=None, widgets=None,
labels=None, help_texts=None, error_messages=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 will be included in the returned fields.
``fields`` is an optional list of field names. If provided, return only the
named 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.
``exclude`` is an optional list of field names. If provided, exclude the
named fields from the returned fields, even if they are listed in the
``fields`` argument.
``widgets`` is a dictionary of model field names mapped to a widget.
@ -296,9 +295,8 @@ class BaseModelForm(BaseForm):
def _get_validation_exclusions(self):
"""
For backwards-compatibility, several types of fields need to be
excluded from model validation. See the following tickets for
details: #12507, #12521, #12553
For backwards-compatibility, exclude several types of fields from model
validation. See tickets #12507, #12521, #12553.
"""
exclude = []
# Build up a list of fields that should be excluded from model field
@ -400,7 +398,7 @@ class BaseModelForm(BaseForm):
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.
"""
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,
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 will be included in the returned fields. If omitted or '__all__',
all fields will be used.
``fields`` is an optional list of field names. If provided, include only
the named fields in the returned fields. If omitted or '__all__', use all
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.
``exclude`` is an optional list of field names. If provided, exclude the
named fields from the returned fields, even if they are listed in the
``fields`` argument.
``widgets`` is a dictionary of model field names mapped to a widget.
@ -561,7 +559,7 @@ class BaseModelFormSet(BaseFormSet):
super().__init__(**defaults)
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):
return len(self.get_queryset())
return super().initial_form_count()
@ -618,11 +616,11 @@ class BaseModelFormSet(BaseFormSet):
return self._queryset
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)
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)
def delete_existing(self, obj, commit=True):
@ -631,8 +629,9 @@ class BaseModelFormSet(BaseFormSet):
obj.delete()
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:
self.saved_forms = []
@ -830,9 +829,7 @@ def modelformset_factory(model, form=ModelForm, 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):
"""
Returns a FormSet class for the given Django model class.
"""
"""Return a FormSet class for the given Django model class."""
meta = getattr(form, 'Meta', None)
if (getattr(meta, 'fields', fields) is None and
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):
"""
Finds and returns 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
Find and return the ForeignKey from model to parent if there is one
(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
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.
"""
# avoid circular import
@ -1019,9 +1016,9 @@ def inlineformset_factory(parent_model, model, form=ModelForm,
labels=None, help_texts=None, error_messages=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``.
"""
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
@ -1147,10 +1144,9 @@ class ModelChoiceField(ChoiceField):
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
returned.
If it is a callable, invoke it and return the result.
"""
if callable(self.limit_choices_to):
return self.limit_choices_to()
@ -1175,9 +1171,9 @@ class ModelChoiceField(ChoiceField):
# Override it to customize the label.
def label_from_instance(self, obj):
"""
This method is used to convert objects into strings; it's used to
generate the labels for the choices presented by this object. Subclasses
can override this method to customize the display of the choices.
Convert objects into strings and generate the labels for the choices
presented by this object. Subclasses can override this method to
customize the display of the choices.
"""
return force_text(obj)
@ -1264,8 +1260,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
def _check_values(self, value):
"""
Given a list of possible PK values, returns a QuerySet of the
corresponding objects. Raises a ValidationError if a given value is
Given a list of possible PK values, return a QuerySet of the
corresponding objects. Raise a ValidationError if a given value is
invalid (not a valid PK, not in the queryset, etc.)
"""
key = self.to_field_name or 'pk'

View File

@ -10,7 +10,7 @@ from django.utils.translation import gettext_lazy as _
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
"""Convert 'first_name' to 'First name'."""
if not name:
return ''
return name.replace('_', ' ').capitalize()

View File

@ -83,7 +83,7 @@ class Media:
return static(path)
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:
return Media(**{str(name): getattr(self, '_' + name)})
raise KeyError('Unknown media type "%s"' % name)
@ -209,7 +209,7 @@ class Widget(metaclass=MediaDefiningClass):
return mark_safe(renderer.render(template_name, context))
def build_attrs(self, base_attrs, extra_attrs=None):
"Helper function for building an attribute dictionary."
"""Build an attribute dictionary."""
attrs = base_attrs.copy()
if extra_attrs is not None:
attrs.update(extra_attrs)
@ -217,8 +217,8 @@ class Widget(metaclass=MediaDefiningClass):
def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and this widget's name, returns the value
of this widget. Returns None if it's not provided.
Given a dictionary of data and this widget's name, return the value
of this widget or None if it's not provided.
"""
return data.get(name)
@ -227,8 +227,8 @@ class Widget(metaclass=MediaDefiningClass):
def id_for_label(self, id_):
"""
Returns 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.
Return the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Return None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
@ -301,7 +301,7 @@ class HiddenInput(Input):
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.
"""
template_name = 'django/forms/widgets/multiple_hidden.html'
@ -816,14 +816,17 @@ class MultiWidget(Widget):
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
non-empty.
"""
raise NotImplementedError('Subclasses must implement this method.')
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()
for w in self.widgets:
media = media + w.media
@ -842,7 +845,7 @@ class MultiWidget(Widget):
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
template_name = 'django/forms/widgets/splitdatetime.html'
@ -869,7 +872,7 @@ class SplitDateTimeWidget(MultiWidget):
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'
@ -881,7 +884,7 @@ class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
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
element and hence implements value_from_datadict.

View File

@ -366,9 +366,8 @@ class LazyStream:
"""
Used when the exact number of bytes to read is unimportant.
This procedure just returns whatever is chunk is conveniently returned
from the iterator instead. Useful to avoid unnecessary bookkeeping if
performance is an issue.
Return whatever chunk is conveniently returned from the iterator.
Useful to avoid unnecessary bookkeeping if performance is an issue.
"""
if self._leftover:
output = self._leftover
@ -383,7 +382,7 @@ class LazyStream:
"""
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().
"""
self._producer = []
@ -393,7 +392,7 @@ class LazyStream:
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
stream position and thus tell() will be rewound.
@ -406,7 +405,7 @@ class LazyStream:
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
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
@ -429,8 +428,7 @@ class LazyStream:
class ChunkIter:
"""
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
object.
constructor, yield chunks of read operations from that object.
"""
def __init__(self, flo, chunk_size=64 * 1024):
self.flo = flo
@ -541,11 +539,10 @@ class BoundaryIter:
def _find_boundary(self, data, eof=False):
"""
Finds 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:
Find a multipart boundary in data.
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 start of the next encapsulation
"""
@ -578,7 +575,7 @@ def exhaust(stream_or_iterable):
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
# and parse it if found. The header must fit within one

View File

@ -121,9 +121,9 @@ class HttpRequest:
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
cookie has expired, raises an exception... unless you provide the
default argument in which case that value will be returned instead.
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
"""
try:
cookie_value = self.COOKIES[key]
@ -155,13 +155,12 @@ class HttpRequest:
def build_absolute_uri(self, location=None):
"""
Builds an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, the absolute URI is
built on ``request.get_full_path()``. Anyway, if the location is
absolute, it is simply converted to an RFC 3987 compliant URI and
returned and if location is relative or is scheme-relative (i.e.,
``//example.com/``), it is urljoined to a base URL constructed from the
request variables.
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, bulid the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
"""
if location is None:
# Make it an absolute url (but schemeless and domainless) for the
@ -180,7 +179,7 @@ class HttpRequest:
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.
"""
return 'http'
@ -211,8 +210,8 @@ class HttpRequest:
@encoding.setter
def encoding(self, val):
"""
Sets the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, it is removed and recreated on the
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
"""
self._encoding = val
@ -239,7 +238,7 @@ class HttpRequest:
self._upload_handlers = upload_handlers
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,
warning="You cannot alter upload handlers after the upload has been processed."
@ -469,15 +468,14 @@ class QueryDict(MultiValueDict):
return super().setdefault(key, default)
def copy(self):
"""Returns a mutable copy of this object."""
"""Return a mutable copy of this object."""
return self.__deepcopy__({})
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
example::
`safe` specifies characters which don't require quoting, for example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'

View File

@ -104,11 +104,11 @@ class HttpResponseBase:
return ', "%s"' % self['Content-Type'] if 'Content-Type' in self else ''
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
`value` can't be represented in the given charset, MIME-encoding
is applied.
`value` can't be represented in the given charset, apply MIME-encoding.
"""
if not isinstance(value, (bytes, str)):
value = str(value)
@ -159,13 +159,13 @@ class HttpResponseBase:
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
"""
Sets a cookie.
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- 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
if expires is not None:
@ -200,7 +200,7 @@ class HttpResponseBase:
self.cookies[key]['httponly'] = True
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:
self[key] = value
@ -274,7 +274,7 @@ class HttpResponse(HttpResponseBase):
"""
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