1
0
mirror of https://github.com/django/django.git synced 2025-08-20 16:59:12 +00:00

Refs #36500 -- Shortened some long docstrings and comments.

Manually reformatted some long docstrings and comments that would be
damaged by the to-be-applied autofixer script, in cases where editorial
judgment seemed necessary for style or wording changes.
This commit is contained in:
Mike Edmunds 2025-07-22 20:40:48 -07:00 committed by nessita
parent 5527df9192
commit 55b0cc2131
44 changed files with 157 additions and 118 deletions

View File

@ -907,7 +907,7 @@ class ModelAdminChecks(BaseModelAdminChecks):
return inline(obj.model, obj.admin_site).check()
def _check_list_display(self, obj):
"""Check that list_display only contains fields or usable attributes."""
"""Check list_display only contains fields or usable attributes."""
if not isinstance(obj.list_display, (list, tuple)):
return must_be(
@ -1012,7 +1012,7 @@ class ModelAdminChecks(BaseModelAdminChecks):
def _check_list_filter_item(self, obj, item, label):
"""
Check one item of `list_filter`, i.e. check if it is one of three options:
Check one item of `list_filter`, the three valid options are:
1. 'field' -- a basic field filter, possibly w/ relationships (e.g.
'field__rel')
2. ('field', SomeFieldListFilter) - a field-based list filter class

View File

@ -1629,7 +1629,7 @@ class ModelAdmin(BaseModelAdmin):
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
# Something needs to be selected or nothing will happen.
msg = _(
"Items must be selected in order to perform "
"actions on them. No items have been changed."
@ -2399,7 +2399,7 @@ class InlineModelAdmin(BaseModelAdmin):
return self.max_num
def get_formset(self, request, obj=None, **kwargs):
"""Return a BaseInlineFormSet class for use in admin add/change views."""
"""Return a BaseInlineFormSet class for use in add/change views."""
if "fields" in kwargs:
fields = kwargs.pop("fields")
else:

View File

@ -30,7 +30,7 @@ def get_admin_log(parser, token):
Usage::
{% get_admin_log [limit] as [varname] for_user [context_var_with_user_obj] %}
{% get_admin_log [limit] as [varname] for_user [user_id_or_varname] %}
Examples::
@ -38,9 +38,9 @@ def get_admin_log(parser, token):
{% get_admin_log 10 as admin_log for_user user %}
{% get_admin_log 10 as admin_log %}
Note that ``context_var_containing_user_obj`` can be a hard-coded integer
(user ID) or the name of a template context variable containing the user
object whose ID you want.
Note that ``user_id_or_varname`` can be a hard-coded integer (user ID)
or the name of a template context variable containing the user object
whose ID you want.
"""
tokens = token.contents.split()
if len(tokens) < 4:

View File

@ -142,8 +142,8 @@ class AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):
self.wait_until(ec.staleness_of(old_page), timeout=timeout)
except WebDriverException:
# Issue in version 113+ of Chrome driver where a WebDriverException
# error is raised rather than a StaleElementReferenceException, see:
# https://issues.chromium.org/issues/42323468
# error is raised rather than a StaleElementReferenceException.
# See: https://issues.chromium.org/issues/42323468
pass
self.wait_page_ready(timeout=timeout)

View File

@ -279,7 +279,7 @@ class RelatedFieldWidgetWrapper(forms.Widget):
cascade = getattr(rel, "on_delete", None) is CASCADE
self.can_delete_related = not multiple and not cascade and can_delete_related
self.can_view_related = not multiple and can_view_related
# so we can check if the related object is registered with this AdminSite
# To check if the related object is registered with this AdminSite.
self.admin_site = admin_site
def __deepcopy__(self, memo):

View File

@ -106,8 +106,8 @@ def split_explicit_title(text):
"""
Split role content into title and target, if given.
From sphinx.util.nodes.split_explicit_title
See https://github.com/sphinx-doc/sphinx/blob/230ccf2/sphinx/util/nodes.py#L389
From sphinx.util.nodes.split_explicit_title. See:
https://github.com/sphinx-doc/sphinx/blob/230ccf2/sphinx/util/nodes.py#L389
"""
match = explicit_title_re.match(text)
if match:

View File

@ -260,7 +260,7 @@ async def _auser_get_permissions(user, obj, from_name):
def _user_has_perm(user, perm, obj):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checks.
"""
for backend in auth.get_backends():
if not hasattr(backend, "has_perm"):
@ -288,7 +288,7 @@ async def _auser_has_perm(user, perm, obj):
def _user_has_module_perms(user, app_label):
"""
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checks.
"""
for backend in auth.get_backends():
if not hasattr(backend, "has_module_perms"):

View File

@ -186,8 +186,8 @@ class OFTDateTime(Field):
@property
def value(self):
"Return a Python `datetime` object for this OFTDateTime field."
# TODO: Adapt timezone information.
# See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html
# TODO: Adapt timezone information. See:
# https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html
# The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous),
# 100=GMT, 104=GMT+1, 80=GMT-5, etc.
try:

View File

@ -10,7 +10,9 @@ advantage OGR Geometries have over their GEOS counterparts is support
for spatial reference systems and their transformation.
Example:
>>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference
>>> from django.contrib.gis.gdal import (
... OGRGeometry, OGRGeomType, SpatialReference
... )
>>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)'
>>> pnt = OGRGeometry(wkt1)
>>> print(pnt)
@ -35,7 +37,8 @@ Example:
>>> gt1 = OGRGeomType(3) # Using an integer for the type
>>> gt2 = OGRGeomType('Polygon') # Using a string
>>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
>>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
>>> # Equivalence works w/non-OGRGeomType objects:
>>> print(gt1 == 3, gt1 == 'Polygon')
True True
"""

View File

@ -116,7 +116,11 @@ class SpatialReference(GDALBase):
doesn't exist. Can also take a tuple as a parameter, (target, child),
where child is the index of the attribute in the WKT. For example:
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]'
>>> wkt = (
... 'GEOGCS["WGS 84",'
... ' DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]'
... ']'
... )
>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
>>> print(srs['GEOGCS'])
WGS 84

View File

@ -13,7 +13,7 @@ class LineString(LinearGeometryMixin, GEOSGeometry):
def __init__(self, *args, **kwargs):
"""
Initialize on the given sequence -- may take lists, tuples, NumPy arrays
Initialize on the given sequence: may take lists, tuples, NumPy arrays
of X,Y pairs, or Point objects. If Point objects are used, ownership is
_not_ transferred to the LineString object.
@ -62,7 +62,7 @@ class LineString(LinearGeometryMixin, GEOSGeometry):
self._checkdim(shape[1])
ndim = shape[1]
else:
# Getting the number of coords and the number of dimensions -- which
# Getting the number of coords and the number of dimensions, which
# must stay the same, e.g., no LineString((1, 2), (1, 2, 3)).
ndim = None
# Incrementing through each of the coordinates and verifying

View File

@ -18,7 +18,7 @@ class Point(GEOSGeometry):
For example:
>>> p = Point((5, 23)) # 2D point, passed in as a tuple
>>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters
>>> p = Point(5, 23, 8) # 3D point, passed as individual parameters
"""
if x is None:
coords = []

View File

@ -175,7 +175,7 @@ class LayerMapping:
else:
raise LayerMapError("Unrecognized transaction mode: %s" % transaction_mode)
# #### Checking routines used during initialization ####
# Checking routines used during initialization.
def check_fid_range(self, fid_range):
"Check the `fid_range` keyword."
if fid_range:
@ -339,7 +339,7 @@ class LayerMapping:
"Unique keyword argument must be set with a tuple, list, or string."
)
# Keyword argument retrieval routines ####
# Keyword argument retrieval routines.
def feature_kwargs(self, feat):
"""
Given an OGR Feature, return a dictionary of keyword arguments for
@ -384,7 +384,7 @@ class LayerMapping:
else:
return {fld: kwargs[fld] for fld in self.unique}
# #### Verification routines used in constructing model keyword arguments. ####
# Verification routines used in constructing model keyword arguments.
def verify_ogr_field(self, ogr_field, model_field):
"""
Verify if the OGR Field contents are acceptable to the model field. If
@ -513,7 +513,7 @@ class LayerMapping:
# Returning the WKT of the geometry.
return g.wkt
# #### Other model methods ####
# Other model methods.
def coord_transform(self):
"Return the coordinate transformation object."
SpatialRefSys = self.spatial_backend.spatial_ref_sys()

View File

@ -24,7 +24,7 @@ def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False):
Keyword Arguments:
`geom_name` => The name of the geometry field to use for the model.
`layer_key` => The key for specifying which layer in the DataSource to use;
`layer_key` => The key specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.
@ -90,7 +90,7 @@ def ogrinspect(*args, **kwargs):
`geom_name` => For specifying the model name for the Geometry Field.
Otherwise will default to `geom`
`layer_key` => The key for specifying which layer in the DataSource to use;
`layer_key` => The key specifying which layer in the DataSource to use;
defaults to 0 (the first layer). May be an integer index or a string
identifier for the layer.

View File

@ -41,7 +41,7 @@ class Feed:
response = HttpResponse(content_type=feedgen.content_type)
if hasattr(self, "item_pubdate") or hasattr(self, "item_updateddate"):
# if item_pubdate or item_updateddate is defined for the feed, set
# header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
# header so as ConditionalGetMiddleware can send 304 NOT MODIFIED.
response.headers["Last-Modified"] = http_date(
feedgen.latest_post_date().timestamp()
)

View File

@ -56,7 +56,8 @@ class BaseMemcachedCache(BaseCache):
timeout = -1
if timeout > 2592000: # 60*60*24*30, 30 days
# See https://github.com/memcached/memcached/wiki/Programming#expiration
# See:
# https://github.com/memcached/memcached/wiki/Programming#expiration
# "Expiration times can be set from 0, meaning "never expire", to
# 30 days. Any time higher than 30 days is interpreted as a Unix
# timestamp date. If you want to expire an object on January 1st of

View File

@ -16,8 +16,8 @@ class LimitedStream(IOBase):
"""
Wrap another stream to disallow reading it past a number of bytes.
Based on the implementation from werkzeug.wsgi.LimitedStream
See https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828
Based on the implementation from werkzeug.wsgi.LimitedStream. See:
https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828
"""
def __init__(self, stream, limit):

View File

@ -195,7 +195,8 @@ class BaseDatabaseFeatures:
# Does the backend support introspection of CHECK constraints?
can_introspect_check_constraints = True
# Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value})
# Does the backend support 'pyformat' style:
# ("... %(name)s ...", {'name': value})
# parameter passing? Note this can be provided by the backend even if not
# supported by the Python driver
supports_paramstyle_pyformat = True

View File

@ -1022,11 +1022,12 @@ class BaseDatabaseSchemaEditor:
# will now be used in lieu of an index. The following lines from the
# truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# True | False | False | False
# True | False | False | True
# True | False | True | True
# old_field | new_field
# db_index | unique | db_index | unique
# -------------------------------------
# True | False | False | False
# True | False | False | True
# True | False | True | True
if (
old_field.db_index
and not old_field.unique
@ -1210,11 +1211,12 @@ class BaseDatabaseSchemaEditor:
# constraint will no longer be used in lieu of an index. The following
# lines from the truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# False | False | True | False
# False | True | True | False
# True | True | True | False
# old_field | new_field
# db_index | unique | db_index | unique
# -------------------------------------
# False | False | True | False
# False | True | True | False
# True | True | True | False
if (
(not old_field.db_index or old_field.unique)
and new_field.db_index

View File

@ -760,7 +760,7 @@ class ModelState:
raise ValueError(
'ModelState.fields cannot be bound to a model - "%s" is.' % name
)
# Sanity-check that relation fields are NOT referring to a model class.
# Ensure that relation fields are NOT referring to a model class.
if field.is_relation and hasattr(field.related_model, "_meta"):
raise ValueError(
'Model fields in "ModelState.fields" cannot refer to a model class '

View File

@ -290,7 +290,7 @@ class BaseFormSet(RenderableFormMixin):
if not hasattr(self, "_deleted_form_indexes"):
self._deleted_form_indexes = []
for i, form in enumerate(self.forms):
# if this is an extra form and hasn't changed, don't consider it
# If this is an extra form and hasn't changed, ignore it.
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
@ -314,7 +314,7 @@ class BaseFormSet(RenderableFormMixin):
if not hasattr(self, "_ordering"):
self._ordering = []
for i, form in enumerate(self.forms):
# if this is an extra form and hasn't changed, don't consider it
# If this is an extra form and hasn't changed, ignore it.
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data

View File

@ -405,8 +405,8 @@ class MultiPartParser:
def _close_files(self):
# Free up all file handles.
# FIXME: this currently assumes that upload handlers store the file as 'file'
# We should document that...
# FIXME: this currently assumes that upload handlers store the file as
# 'file'. We should document that...
# (Maybe add handler.free_file to complement new_file)
for handler in self._upload_handlers:
if hasattr(handler, "file"):

View File

@ -764,7 +764,7 @@ def firstof(parser, token):
Or if only some variables should be escaped, you can use::
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
{% firstof var1 var2|safe var3 "<strong>fallback</strong>"|safe %}
"""
bits = token.split_contents()[1:]
asvar = None
@ -825,20 +825,21 @@ def do_for(parser, token):
The for loop sets a number of variables available within the loop:
========================== ================================================
Variable Description
========================== ================================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the
current one
========================== ================================================
======================= ==============================================
Variable Description
======================= ==============================================
``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the
loop (1-indexed)
``forloop.revcounter0`` The number of iterations from the end of the
loop (0-indexed)
``forloop.first`` True if this is the first time through the
loop
``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the
current one
======================= ==============================================
"""
bits = token.split_contents()
if len(bits) < 4:
@ -1417,7 +1418,11 @@ def url(parser, token):
For example, if you have a view ``app_name.views.client_details`` taking
the client's id and the corresponding line in a URLconf looks like this::
path('client/<int:id>/', views.client_details, name='client-detail-view')
path(
'client/<int:id>/',
views.client_details,
name='client-detail-view',
)
and this app's URLconf is included into the project's URLconf under some
path::
@ -1496,7 +1501,8 @@ def widthratio(parser, token):
For example::
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}">
height="10"
width="{% widthratio this_value max_value max_width %}">
If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100,
the image in the above example will be 88 pixels wide

View File

@ -61,8 +61,9 @@ def infix(bp, func):
return func(context, self.first, self.second)
except Exception:
# Templates shouldn't throw exceptions when rendering. We are
# most likely to get exceptions for things like {% if foo in bar
# %} where 'bar' does not support 'in', so default to False
# most likely to get exceptions for things like:
# {% if foo in bar %}
# where 'bar' does not support 'in', so default to False.
return False
return Operator

View File

@ -664,7 +664,7 @@ class RequestFactory:
if query_params:
extra["QUERY_STRING"] = urlencode(query_params, doseq=True)
r.update(extra)
# If QUERY_STRING is absent or empty, we want to extract it from the URL.
# If QUERY_STRING is absent or empty, extract it from the URL.
if not r.get("QUERY_STRING"):
# WSGI requires latin-1 encoded strings. See get_path_info().
r["QUERY_STRING"] = parsed.query.encode().decode("iso-8859-1")

View File

@ -51,7 +51,9 @@ class MultiValueDict(dict):
A subclass of dictionary customized to handle multiple values for the
same key.
>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
>>> d = MultiValueDict(
... {'name': ['Adrian', 'Simon'], 'position': ['Developer']}
... )
>>> d['name']
'Simon'
>>> d.getlist('name')

View File

@ -189,7 +189,8 @@ class TimeFormat(Formatter):
# `offset` is a datetime.timedelta. For negative values (to the west of
# UTC) only days can be negative (days=-1) and seconds are always
# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# positive.
# e.g.: UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# Positive offsets have days=0
return offset.days * 86400 + offset.seconds

View File

@ -167,7 +167,8 @@ class JavaScriptCatalog(View):
if plural is not None:
# This should be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20)
# ? 1 : 2;
plural = [
el.strip()
for el in plural.split(";")

View File

@ -35,7 +35,7 @@ sys.path.append(abspath(join(dirname(__file__), "_ext")))
# it lives in has been added to sys.path.
import github_links # NOQA
# -- General configuration -----------------------------------------------------
# -- General configuration --
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "4.5.0"
@ -196,7 +196,7 @@ intersphinx_cache_limit = 90 # days
# The 'versionadded' and 'versionchanged' directives are overridden.
suppress_warnings = ["app.add_directive", "epub.duplicated_toc_entry"]
# -- Options for HTML output ---------------------------------------------------
# -- Options for HTML output --
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
@ -284,7 +284,7 @@ rst_epilog = """
.. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>`
""" # NOQA
# -- Options for LaTeX output --------------------------------------------------
# -- Options for LaTeX output --
# Use XeLaTeX for Unicode support.
latex_engine = "xelatex"
@ -310,7 +310,7 @@ latex_elements = {
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
# (source start file, target name, title, author, document class).
# latex_documents = []
latex_documents = [
(
@ -343,7 +343,7 @@ latex_documents = [
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# -- Options for manual page output --
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
@ -358,7 +358,7 @@ man_pages = [
]
# -- Options for Texinfo output ------------------------------------------------
# -- Options for Texinfo output --
# List of tuples (startdocname, targetname, title, author, dir_entry,
# description, category, toctree_only)
@ -376,7 +376,7 @@ texinfo_documents = [
]
# -- Options for Epub output ---------------------------------------------------
# -- Options for Epub output --
# Bibliographic Dublin Core info.
epub_title = project

View File

@ -16,7 +16,7 @@
# operation to the specified language or resource. For example, to get stats
# for Spanish in contrib.admin, run:
#
# $ python scripts/manage_translations.py lang_stats --language=es --resources=admin
# $ python scripts/manage_translations.py lang_stats -l es -r admin
#
# Also each command supports a --verbosity option to get progress feedback.

View File

@ -1558,7 +1558,7 @@ class ManageCheck(AdminScriptTestCase):
args = ["check"]
out, err = self.run_manage(args)
expected_err = (
"System check identified some issues:\n" # No "CommandError: " part
"System check identified some issues:\n" # No "CommandError: "
"\n"
"WARNINGS:\n"
"?: A warning\n"

View File

@ -1160,8 +1160,8 @@ class NonAggregateAnnotationTestCase(TestCase):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
# "Column aliases cannot contain whitespace characters, quotation marks, "
# "semicolons, percent signs, or SQL comments."
# "Column aliases cannot contain whitespace characters, quotation "
# "marks, semicolons, percent signs, or SQL comments."
# )
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
@ -1182,7 +1182,7 @@ class NonAggregateAnnotationTestCase(TestCase):
"ali/*as",
"alias*/",
"alias;",
# RemovedInDjango70Warning: When the deprecation ends, add this case.
# RemovedInDjango70Warning: When the deprecation ends, add this:
# "alias%",
# [] are used by MSSQL.
"alias[",
@ -1190,8 +1190,8 @@ class NonAggregateAnnotationTestCase(TestCase):
]
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
# "Column aliases cannot contain whitespace characters, quotation marks, "
# "semicolons, percent signs, or SQL comments."
# "Column aliases cannot contain whitespace characters, quotation "
# "marks, semicolons, percent signs, or SQL comments."
# )
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "
@ -1496,8 +1496,8 @@ class AliasTests(TestCase):
crafted_alias = """injected_name" from "annotations_book"; --"""
# RemovedInDjango70Warning: When the deprecation ends, replace with:
# msg = (
# "Column aliases cannot contain whitespace characters, quotation marks, "
# "semicolons, percent signs, or SQL comments."
# "Column aliases cannot contain whitespace characters, quotation "
# "marks, semicolons, percent signs, or SQL comments."
# )
msg = (
"Column aliases cannot contain whitespace characters, quotation marks, "

View File

@ -493,7 +493,7 @@ class DeletionTests(TestCase):
# and there are no more cascades.
# 1 query to find the users for the avatar.
# 1 query to delete the user
# 1 query to null out user.avatar, because we can't defer the constraint
# 1 query to null out user.avatar, since we can't defer the constraint
# 1 query to delete the avatar
self.assertNumQueries(4, a.delete)
self.assertFalse(User.objects.exists())
@ -536,7 +536,7 @@ class DeletionTests(TestCase):
# TEST_SIZE / batch_size (select related `T` instances)
# + 1 (select related `U` instances)
# + TEST_SIZE / GET_ITERATOR_CHUNK_SIZE (delete `T` instances in batches)
# + TEST_SIZE / GET_ITERATOR_CHUNK_SIZE (delete `T` matches in batches)
# + 1 (delete `s`)
expected_num_queries = ceil(TEST_SIZE / batch_size)
expected_num_queries += ceil(TEST_SIZE / GET_ITERATOR_CHUNK_SIZE) + 2

View File

@ -247,7 +247,7 @@ class ModelFormCallableModelDefault(TestCase):
class FormsModelTestCase(TestCase):
def test_unicode_filename(self):
# FileModel with Unicode filename and data #########################
# FileModel with Unicode filename and data.
file1 = SimpleUploadedFile(
"我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode()
)
@ -263,7 +263,7 @@ class FormsModelTestCase(TestCase):
m.delete()
def test_boundary_conditions(self):
# Boundary conditions on a PositiveIntegerField #########################
# Boundary conditions on a PositiveIntegerField.
class BoundaryForm(ModelForm):
class Meta:
model = BoundaryModel

View File

@ -442,7 +442,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
# using the provided raw SQL statements.
# SELECT ST_Distance(
# point,
# ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)
# ST_Transform(
# ST_GeomFromText('POINT(-96.876369 29.905320)', 4326),
# 32140
# )
# )
# FROM distapp_southtexascity;
m_distances = [
@ -458,7 +461,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
]
# SELECT ST_Distance(
# point,
# ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)
# ST_Transform(
# ST_GeomFromText('POINT(-96.876369 29.905320)', 4326),
# 2278
# )
# )
# FROM distapp_southtexascityft;
ft_distances = [
@ -502,7 +508,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
# Reference query:
# SELECT ST_distance_sphere(
# point,
# ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)
# ST_GeomFromText(
# 'LINESTRING(150.9020 -34.4245,150.8700 -34.5789)',
# 4326
# )
# )
# FROM distapp_australiacity ORDER BY name;
distances = [
@ -542,7 +551,8 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
# point,
# ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)
# )
# FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
# FROM distapp_australiacity
# WHERE (NOT (id = 11)); st_distance_sphere
spheroid_distances = [
60504.0628957201,
77023.9489850262,
@ -662,7 +672,8 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
z = SouthTexasZipcode.objects.get(name="77005")
# Reference query:
# SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
# SELECT ST_Distance(
# ST_Transform("distapp_censuszipcode"."poly", 32140),
# ST_GeomFromText('<buffer_wkt>', 32140))
# FROM "distapp_censuszipcode";
dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
@ -706,7 +717,8 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
# Reference query (should use `length_spheroid`).
# SELECT ST_length_spheroid(
# ST_GeomFromText('<wkt>', 4326)
# 'SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]]'
# 'SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]]'
# );
len_m1 = 473504.769553813
len_m2 = 4617.668

View File

@ -283,7 +283,8 @@ class Geo3DFunctionsTests(FuncTestMixin, Geo3DLoadingHelper, TestCase):
name="Houston"
)
# GeoJSON should be 3D
# `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';`
# `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d
# WHERE name='Houston';`
ref_json_regex = re.compile(
r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$'
)
@ -295,7 +296,8 @@ class Geo3DFunctionsTests(FuncTestMixin, Geo3DLoadingHelper, TestCase):
"""
self._load_polygon_data()
# Reference query for values below:
# `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) FROM geo3d_polygon3d;`
# `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly)
# FROM geo3d_polygon3d;`
ref_perim_3d = 76859.2620451
ref_perim_2d = 76859.2577803
tol = 6
@ -314,7 +316,8 @@ class Geo3DFunctionsTests(FuncTestMixin, Geo3DLoadingHelper, TestCase):
"""
# ST_Length_Spheroid Z-aware, and thus does not need to use
# a separate function internally.
# `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]')
# `SELECT ST_Length_Spheroid(
# line, 'SPHEROID["GRS 1980",6378137,298.257222101]')
# FROM geo3d_interstate[2d|3d];`
self._load_interstate_data()
tol = 3

View File

@ -207,7 +207,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
def test_assvg(self):
with self.assertRaises(TypeError):
City.objects.annotate(svg=functions.AsSVG("point", precision="foo"))
# SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
# SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city
# WHERE name = 'Pueblo';
svg1 = 'cx="-104.609252" cy="-38.255001"'
# Even though relative, only one point so it's practically the same except for
# the 'c' letter prefix on the x,y values.
@ -737,7 +738,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
)
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
# SELECT AsText(
# ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
# FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(

View File

@ -86,9 +86,9 @@ class SpatialRefSysTest(TestCase):
srs = self.SpatialRefSys.objects.get(srid=sd["srid"])
self.assertEqual(sd["srid"], srs.srid)
# Some of the authority names are borked on Oracle, e.g., SRID=32140.
# also, Oracle Spatial seems to add extraneous info to fields, hence the
# the testing with the 'startswith' flag.
# Some of the authority names are borked on Oracle, e.g.,
# SRID=32140. Also, Oracle Spatial seems to add extraneous info to
# fields, hence the testing with the 'startswith' flag.
auth_name, oracle_flag = sd["auth_name"]
# Compare case-insensitively because srs.auth_name is lowercase
# ("epsg") on Spatialite.

View File

@ -319,10 +319,10 @@ class IntrospectionTests(TransactionTestCase):
foreign_key=None,
):
# Different backends have different values for same constraints:
# PRIMARY KEY UNIQUE CONSTRAINT UNIQUE INDEX
# MySQL pk=1 uniq=1 idx=1 pk=0 uniq=1 idx=1 pk=0 uniq=1 idx=1
# PostgreSQL pk=1 uniq=1 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
# SQLite pk=1 uniq=0 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
# PRIMARY KEY UNIQUE CONSTRAINT UNIQUE INDEX
# MySQL pk=1 uniq=1 idx=1 pk=0 uniq=1 idx=1 pk=0 uniq=1 idx=1
# Postgres pk=1 uniq=1 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
# SQLite pk=1 uniq=0 idx=0 pk=0 uniq=1 idx=0 pk=0 uniq=1 idx=1
if details["primary_key"]:
details["unique"] = True
if details["unique"]:

View File

@ -331,7 +331,7 @@ class LookupTests(TestCase):
Author.objects.values_list().in_bulk()
def test_values(self):
# values() returns a list of dictionaries instead of object instances --
# values() returns a list of dictionaries instead of object instances,
# and you can specify which fields you want to retrieve.
self.assertSequenceEqual(
Article.objects.values("headline"),

View File

@ -30,7 +30,7 @@ class Mixin:
class OperationTests(OperationTestBase):
"""
Tests running the operations and making sure they do what they say they do.
Each test looks at their state changing, and then their database operation -
Each test looks at their state changing, and then their database operation,
both forwards and backwards.
"""
@ -1539,7 +1539,7 @@ class OperationTests(OperationTestBase):
"digits",
models.CharField(max_length=10, default="42"),
),
# Manual quoting is fragile and could trip on quotes. Refs #xyz.
# Manual quoting is fragile and could trip on quotes.
migrations.AddField(
"Pony",
"quotes",
@ -1584,7 +1584,7 @@ class OperationTests(OperationTestBase):
"digits",
models.TextField(default="42"),
),
# Manual quoting is fragile and could trip on quotes. Refs #xyz.
# Manual quoting is fragile and could trip on quotes.
migrations.AddField(
"Pony",
"quotes",
@ -1629,7 +1629,7 @@ class OperationTests(OperationTestBase):
"digits",
models.BinaryField(default=b"42"),
),
# Manual quoting is fragile and could trip on quotes. Refs #xyz.
# Manual quoting is fragile and could trip on quotes.
migrations.AddField(
"Pony",
"quotes",

View File

@ -3067,7 +3067,7 @@ class OtherModelFormTests(TestCase):
'<label for="id_url">The URL:</label><input type="text" name="url" '
'maxlength="40" required id="id_url"></div>',
)
# to_field_name should also work on ModelMultipleChoiceField ##################
# to_field_name should also work on ModelMultipleChoiceField.
field = forms.ModelMultipleChoiceField(
Inventory.objects.all(), to_field_name="barcode"

View File

@ -1160,7 +1160,7 @@ class ModelFormsetTest(TestCase):
'maxlength="100"></p>',
)
# Custom primary keys with ForeignKey, OneToOneField and AutoField ############
# Custom primary keys with ForeignKey, OneToOneField and AutoField.
place = Place.objects.create(pk=1, name="Giordanos", city="Chicago")

View File

@ -208,7 +208,7 @@ class PaginationTests(SimpleTestCase):
self.assertEqual(paginator.validate_number(1.0), 1)
def test_no_content_allow_empty_first_page(self):
# With no content and allow_empty_first_page=True, 1 is a valid page number
# With no content and allow_empty_first_page=True, 1 is a valid page.
paginator = Paginator([], 2)
self.assertEqual(paginator.validate_number(1), 1)