From f81e6e3a53ee36e3f730a71aa55a5744982dd016 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 25 Jul 2025 10:24:17 +0100 Subject: [PATCH] Refs #36485 -- Rewrapped docs to 79 columns line length. Lines in the docs files were manually adjusted to conform to the 79 columns limit per line (plus newline), improving readability and consistency across the content. --- docs/faq/admin.txt | 8 +- docs/faq/general.txt | 12 +- docs/faq/install.txt | 4 +- docs/faq/models.txt | 4 +- docs/glossary.txt | 3 +- docs/howto/csrf.txt | 34 +-- docs/howto/custom-file-storage.txt | 25 +-- docs/howto/custom-lookups.txt | 44 ++-- docs/howto/custom-management-commands.txt | 23 +- docs/howto/custom-model-fields.txt | 56 ++--- docs/howto/custom-template-tags.txt | 33 +-- docs/howto/deployment/asgi/uvicorn.txt | 5 +- docs/howto/deployment/wsgi/apache-auth.txt | 8 +- docs/howto/deployment/wsgi/index.txt | 6 +- docs/howto/deployment/wsgi/modwsgi.txt | 4 +- docs/howto/error-reporting.txt | 19 +- docs/howto/initial-data.txt | 4 +- docs/howto/legacy-databases.txt | 4 +- docs/howto/outputting-csv.txt | 11 +- docs/howto/outputting-pdf.txt | 8 +- docs/howto/overriding-templates.txt | 3 +- docs/howto/static-files/index.txt | 8 +- docs/howto/upgrade-version.txt | 7 +- docs/howto/writing-migrations.txt | 16 +- .../contributing/committing-code.txt | 3 +- .../contributing/triaging-tickets.txt | 8 +- .../writing-code/coding-style.txt | 20 +- .../contributing/writing-code/javascript.txt | 8 +- .../writing-code/submitting-patches.txt | 42 ++-- .../contributing/writing-code/unit-tests.txt | 6 +- .../contributing/writing-documentation.txt | 32 +-- docs/internals/deprecation.txt | 49 +++-- docs/internals/git.txt | 10 +- docs/internals/howto-release-django.txt | 3 +- docs/internals/organization.txt | 39 ++-- docs/internals/release-process.txt | 8 +- docs/internals/security.txt | 7 +- docs/intro/contributing.txt | 45 ++-- docs/intro/index.txt | 4 +- docs/intro/install.txt | 6 +- docs/intro/overview.txt | 42 ++-- docs/intro/reusable-apps.txt | 4 +- docs/intro/tutorial01.txt | 11 +- docs/intro/tutorial02.txt | 61 +++--- docs/intro/tutorial03.txt | 42 ++-- docs/intro/tutorial04.txt | 26 +-- docs/intro/tutorial05.txt | 51 ++--- docs/intro/tutorial07.txt | 52 ++--- docs/intro/tutorial08.txt | 13 +- docs/intro/whatsnext.txt | 21 +- docs/lint.py | 2 +- docs/misc/design-philosophies.txt | 6 +- docs/misc/distributions.txt | 15 +- docs/misc/index.txt | 4 +- docs/ref/applications.txt | 12 +- docs/ref/checks.txt | 48 +++-- docs/ref/class-based-views/base.txt | 10 +- .../class-based-views/generic-date-based.txt | 6 +- .../mixins-multiple-object.txt | 25 +-- .../mixins-single-object.txt | 7 +- docs/ref/class-based-views/mixins.txt | 3 +- docs/ref/clickjacking.txt | 19 +- docs/ref/contrib/admin/actions.txt | 28 +-- docs/ref/contrib/admin/index.txt | 199 +++++++++--------- docs/ref/contrib/auth.txt | 46 ++-- docs/ref/contrib/contenttypes.txt | 13 +- docs/ref/contrib/flatpages.txt | 3 +- docs/ref/contrib/gis/commands.txt | 3 +- docs/ref/contrib/gis/db-api.txt | 43 ++-- docs/ref/contrib/gis/feeds.txt | 8 +- docs/ref/contrib/gis/forms-api.txt | 4 +- docs/ref/contrib/gis/functions.txt | 58 ++--- docs/ref/contrib/gis/gdal.txt | 110 +++++----- docs/ref/contrib/gis/geoquerysets.txt | 62 +++--- docs/ref/contrib/gis/geos.txt | 69 +++--- docs/ref/contrib/gis/install/geolibs.txt | 14 +- docs/ref/contrib/gis/install/index.txt | 37 ++-- docs/ref/contrib/gis/install/spatialite.txt | 9 +- docs/ref/contrib/gis/layermapping.txt | 15 +- docs/ref/contrib/gis/measure.txt | 7 +- docs/ref/contrib/gis/model-api.txt | 18 +- docs/ref/contrib/gis/serializers.txt | 7 +- docs/ref/contrib/gis/testing.txt | 3 +- docs/ref/contrib/gis/tutorial.txt | 33 +-- docs/ref/contrib/index.txt | 6 +- docs/ref/contrib/messages.txt | 12 +- docs/ref/contrib/postgres/fields.txt | 12 +- docs/ref/contrib/postgres/lookups.txt | 11 +- docs/ref/contrib/postgres/search.txt | 3 +- docs/ref/contrib/redirects.txt | 16 +- docs/ref/contrib/sitemaps.txt | 12 +- docs/ref/contrib/sites.txt | 20 +- docs/ref/contrib/staticfiles.txt | 30 +-- docs/ref/contrib/syndication.txt | 38 ++-- docs/ref/csp.txt | 3 +- docs/ref/csrf.txt | 21 +- docs/ref/databases.txt | 51 ++--- docs/ref/django-admin.txt | 68 +++--- docs/ref/files/file.txt | 10 +- docs/ref/files/uploads.txt | 4 +- docs/ref/forms/api.txt | 39 ++-- docs/ref/forms/fields.txt | 109 +++++----- docs/ref/forms/models.txt | 13 +- docs/ref/forms/validation.txt | 4 +- docs/ref/forms/widgets.txt | 56 ++--- docs/ref/logging.txt | 11 +- docs/ref/middleware.txt | 44 ++-- docs/ref/migration-operations.txt | 34 +-- docs/ref/models/class.txt | 4 +- docs/ref/models/constraints.txt | 16 +- docs/ref/models/database-functions.txt | 13 +- docs/ref/models/expressions.txt | 26 ++- docs/ref/models/fields.txt | 142 +++++++------ docs/ref/models/instances.txt | 30 +-- docs/ref/models/lookups.txt | 43 ++-- docs/ref/models/meta.txt | 18 +- docs/ref/models/options.txt | 65 +++--- docs/ref/models/querysets.txt | 136 ++++++------ docs/ref/request-response.txt | 53 ++--- docs/ref/schema-editor.txt | 4 +- docs/ref/settings.txt | 92 ++++---- docs/ref/signals.txt | 11 +- docs/ref/templates/api.txt | 28 +-- docs/ref/templates/builtins.txt | 62 +++--- docs/ref/templates/language.txt | 59 +++--- docs/ref/unicode.txt | 33 +-- docs/ref/urlresolvers.txt | 12 +- docs/ref/urls.txt | 14 +- docs/ref/utils.txt | 35 +-- docs/ref/validators.txt | 6 +- docs/releases/0.96.txt | 12 +- docs/releases/1.0-porting-guide.txt | 52 ++--- docs/releases/1.0.2.txt | 4 +- docs/releases/1.0.txt | 96 +++++---- docs/releases/1.1.2.txt | 4 +- docs/releases/1.1.txt | 79 +++---- docs/releases/1.10.3.txt | 2 +- docs/releases/1.10.txt | 34 +-- docs/releases/1.11.13.txt | 4 +- docs/releases/1.11.5.txt | 3 +- docs/releases/1.11.9.txt | 4 +- docs/releases/1.11.txt | 38 ++-- docs/releases/1.2.txt | 63 +++--- docs/releases/1.3.6.txt | 14 +- docs/releases/1.3.txt | 20 +- docs/releases/1.4.13.txt | 12 +- docs/releases/1.4.14.txt | 22 +- docs/releases/1.4.2.txt | 6 +- docs/releases/1.4.4.txt | 16 +- docs/releases/1.4.txt | 91 ++++---- docs/releases/1.5.1.txt | 4 +- docs/releases/1.5.8.txt | 12 +- docs/releases/1.5.9.txt | 22 +- docs/releases/1.5.txt | 84 ++++---- docs/releases/1.6.1.txt | 9 +- docs/releases/1.6.3.txt | 4 +- docs/releases/1.6.5.txt | 16 +- docs/releases/1.6.6.txt | 21 +- docs/releases/1.6.txt | 117 +++++----- docs/releases/1.7.1.txt | 3 +- docs/releases/1.7.2.txt | 26 +-- docs/releases/1.7.9.txt | 8 +- docs/releases/1.7.txt | 173 ++++++++------- docs/releases/1.8.1.txt | 7 +- docs/releases/1.8.3.txt | 12 +- docs/releases/1.8.txt | 137 ++++++------ docs/releases/1.9.2.txt | 4 +- docs/releases/1.9.5.txt | 4 +- docs/releases/1.9.txt | 31 +-- docs/releases/2.0.1.txt | 4 +- docs/releases/2.0.5.txt | 4 +- docs/releases/2.0.txt | 13 +- docs/releases/2.1.txt | 28 +-- docs/releases/2.2.3.txt | 6 +- docs/releases/3.0.txt | 6 +- docs/releases/4.1.txt | 4 +- docs/releases/5.0.2.txt | 6 +- docs/releases/5.1.txt | 5 +- docs/releases/5.2.4.txt | 7 +- docs/releases/security.txt | 57 +++-- docs/topics/async.txt | 4 +- docs/topics/auth/customizing.txt | 40 ++-- docs/topics/auth/default.txt | 12 +- docs/topics/auth/passwords.txt | 4 +- docs/topics/cache.txt | 73 +++---- docs/topics/checks.txt | 20 +- .../class-based-views/generic-display.txt | 16 +- .../class-based-views/generic-editing.txt | 8 +- docs/topics/class-based-views/index.txt | 7 +- docs/topics/class-based-views/intro.txt | 3 +- docs/topics/class-based-views/mixins.txt | 49 ++--- docs/topics/conditional-view-processing.txt | 5 +- docs/topics/db/aggregation.txt | 26 ++- docs/topics/db/examples/many_to_many.txt | 4 +- docs/topics/db/examples/many_to_one.txt | 7 +- docs/topics/db/examples/one_to_one.txt | 3 +- docs/topics/db/instrumentation.txt | 3 +- docs/topics/db/managers.txt | 24 ++- docs/topics/db/models.txt | 115 +++++----- docs/topics/db/multi-db.txt | 3 +- docs/topics/db/optimization.txt | 14 +- docs/topics/db/queries.txt | 33 +-- docs/topics/db/sql.txt | 21 +- docs/topics/db/tablespaces.txt | 8 +- docs/topics/db/transactions.txt | 8 +- docs/topics/email.txt | 8 +- docs/topics/files.txt | 32 +-- docs/topics/forms/formsets.txt | 9 +- docs/topics/forms/index.txt | 27 +-- docs/topics/forms/media.txt | 3 +- docs/topics/forms/modelforms.txt | 58 ++--- docs/topics/http/decorators.txt | 4 +- docs/topics/http/file-uploads.txt | 13 +- docs/topics/http/sessions.txt | 26 +-- docs/topics/http/urls.txt | 77 +++---- docs/topics/http/views.txt | 31 +-- docs/topics/i18n/formatting.txt | 17 +- docs/topics/i18n/index.txt | 11 +- docs/topics/i18n/timezones.txt | 11 +- docs/topics/i18n/translation.txt | 152 ++++++------- docs/topics/install.txt | 12 +- docs/topics/migrations.txt | 40 ++-- docs/topics/performance.txt | 10 +- docs/topics/security.txt | 73 +++---- docs/topics/serialization.txt | 17 +- docs/topics/settings.txt | 3 +- docs/topics/signals.txt | 18 +- docs/topics/templates.txt | 27 +-- docs/topics/testing/overview.txt | 19 +- docs/topics/testing/tools.txt | 109 +++++----- 230 files changed, 3250 insertions(+), 2914 deletions(-) diff --git a/docs/faq/admin.txt b/docs/faq/admin.txt index 2c75070ad0..fd82b9b03b 100644 --- a/docs/faq/admin.txt +++ b/docs/faq/admin.txt @@ -22,8 +22,8 @@ only allows access to users with those two fields both set to True. How do I automatically set a field's value to the user who last edited the object in the admin? =============================================================================================== -The :class:`~django.contrib.admin.ModelAdmin` class provides customization hooks -that allow you to transform an object as it saved, using details from the +The :class:`~django.contrib.admin.ModelAdmin` class provides customization +hooks that allow you to transform an object as it saved, using details from the request. By extracting the current user from the request, and customizing the :meth:`~django.contrib.admin.ModelAdmin.save_model` hook, you can update an object to reflect the user that edited it. See :ref:`the documentation on @@ -33,8 +33,8 @@ How do I limit admin access so that objects can only be edited by the users who ============================================================================================= The :class:`~django.contrib.admin.ModelAdmin` class also provides customization -hooks that allow you to control the visibility and editability of objects in the -admin. Using the same trick of extracting the user from the request, the +hooks that allow you to control the visibility and editability of objects in +the admin. Using the same trick of extracting the user from the request, the :meth:`~django.contrib.admin.ModelAdmin.get_queryset` and :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` can be used to control the visibility and editability of objects in the admin. diff --git a/docs/faq/general.txt b/docs/faq/general.txt index 3748d41295..203ea6f1e3 100644 --- a/docs/faq/general.txt +++ b/docs/faq/general.txt @@ -32,8 +32,9 @@ thrilled to be able to give something back to the open-source community. What does "Django" mean, and how do you pronounce it? ===================================================== -Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the 1930s -to early 1950s. To this day, he's considered one of the best guitarists of all time. +Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the +1930s to early 1950s. To this day, he's considered one of the best guitarists +of all time. Listen to his music. You'll like it. @@ -185,9 +186,10 @@ corresponds to a web page on the official Django site. Because the documentation is :source:`stored in revision control `, you can browse documentation changes just like you can browse code changes. -Technically, the docs on Django's site are generated from the latest development -versions of those reST documents, so the docs on the Django site may offer more -information than the docs that come with the latest Django release. +Technically, the docs on Django's site are generated from the latest +development versions of those reST documents, so the docs on the Django site +may offer more information than the docs that come with the latest Django +release. How do I cite Django? ===================== diff --git a/docs/faq/install.txt b/docs/faq/install.txt index 8b2aceab74..1cdf40fd78 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -8,8 +8,8 @@ How do I get started? #. `Download the code`_. #. Install Django (read the :doc:`installation guide `). #. Walk through the :doc:`tutorial `. -#. Check out the rest of the :doc:`documentation `, and `ask questions`_ if you - run into trouble. +#. Check out the rest of the :doc:`documentation `, and + `ask questions`_ if you run into trouble. .. _`Download the code`: https://www.djangoproject.com/download/ .. _ask questions: https://www.djangoproject.com/community/ diff --git a/docs/faq/models.txt b/docs/faq/models.txt index 0cfbfd638a..92d2c69cf8 100644 --- a/docs/faq/models.txt +++ b/docs/faq/models.txt @@ -27,8 +27,8 @@ the following: ``connection.queries`` includes all SQL statements -- INSERTs, UPDATES, SELECTs, etc. Each time your app hits the database, the query will be recorded. -If you are using :doc:`multiple databases`, you can use the -same interface on each member of the ``connections`` dictionary: +If you are using :doc:`multiple databases`, you can use +the same interface on each member of the ``connections`` dictionary: .. code-block:: pycon diff --git a/docs/glossary.txt b/docs/glossary.txt index f24a33e81d..cefef84bba 100644 --- a/docs/glossary.txt +++ b/docs/glossary.txt @@ -51,7 +51,8 @@ Glossary See :class:`property`. queryset - An object representing some set of rows to be fetched from the database. + An object representing some set of rows to be fetched from the + database. See :doc:`/topics/db/queries`. diff --git a/docs/howto/csrf.txt b/docs/howto/csrf.txt index d40f4b4cb4..ef9ed41a44 100644 --- a/docs/howto/csrf.txt +++ b/docs/howto/csrf.txt @@ -37,9 +37,9 @@ Using CSRF protection with AJAX =============================== While the above method can be used for AJAX POST requests, it has some -inconveniences: you have to remember to pass the CSRF token in as POST data with -every POST request. For this reason, there is an alternative method: on each -XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the +inconveniences: you have to remember to pass the CSRF token in as POST data +with every POST request. For this reason, there is an alternative method: on +each XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the :setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is often easier because many JavaScript frameworks provide hooks that allow headers to be set on every request. @@ -217,11 +217,11 @@ Testing and CSRF protection =========================== The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view -functions, due to the need for the CSRF token which must be sent with every POST -request. For this reason, Django's HTTP client for tests has been modified to -set a flag on requests which relaxes the middleware and the ``csrf_protect`` -decorator so that they no longer rejects requests. In every other respect -(e.g. sending cookies etc.), they behave the same. +functions, due to the need for the CSRF token which must be sent with every +POST request. For this reason, Django's HTTP client for tests has been modified +to set a flag on requests which relaxes the middleware and the ``csrf_protect`` +decorator so that they no longer rejects requests. In every other respect (e.g. +sending cookies etc.), they behave the same. If, for some reason, you *want* the test client to perform CSRF checks, you can create an instance of the test client that enforces @@ -237,8 +237,8 @@ Edge cases Certain views can have unusual requirements that mean they don't fit the normal pattern envisaged here. A number of utilities can be useful in these -situations. The scenarios they might be needed in are described in the following -section. +situations. The scenarios they might be needed in are described in the +following section. Disabling CSRF protection for just a few views ---------------------------------------------- @@ -265,8 +265,8 @@ There may be some views that are unprotected and have been exempted by ``csrf_exempt``, but still need to include the CSRF token. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by -:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token`` -should be the innermost decorator). +:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. +``requires_csrf_token`` should be the innermost decorator). Protecting a view for only one path ----------------------------------- @@ -304,8 +304,8 @@ view that sends the page. CSRF protection in reusable applications ======================================== -Because it is possible for the developer to turn off the ``CsrfViewMiddleware``, -all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure -the security of these applications against CSRF. It is recommended that the -developers of other reusable apps that want the same guarantees also use the -``csrf_protect`` decorator on their views. +Because it is possible for the developer to turn off the +``CsrfViewMiddleware``, all relevant views in contrib apps use the +``csrf_protect`` decorator to ensure the security of these applications against +CSRF. It is recommended that the developers of other reusable apps that want +the same guarantees also use the ``csrf_protect`` decorator on their views. diff --git a/docs/howto/custom-file-storage.txt b/docs/howto/custom-file-storage.txt index 3f9f732e0b..c69b20ba52 100644 --- a/docs/howto/custom-file-storage.txt +++ b/docs/howto/custom-file-storage.txt @@ -16,8 +16,9 @@ You'll need to follow these steps: class MyStorage(Storage): ... -#. Django must be able to instantiate your storage system without any arguments. - This means that any settings should be taken from ``django.conf.settings``:: +#. Django must be able to instantiate your storage system without any + arguments. This means that any settings should be taken from + ``django.conf.settings``:: from django.conf import settings from django.core.files.storage import Storage @@ -36,10 +37,10 @@ You'll need to follow these steps: In addition, if your class provides local file storage, it must override the ``path()`` method. -#. Your storage class must be :ref:`deconstructible ` - so it can be serialized when it's used on a field in a migration. As long - as your field has arguments that are themselves - :ref:`serializable `, you can use the +#. Your storage class must be :ref:`deconstructible + ` so it can be serialized when it's used on a + field in a migration. As long as your field has arguments that are + themselves :ref:`serializable `, you can use the ``django.utils.deconstruct.deconstructible`` class decorator for this (that's what Django uses on FileSystemStorage). @@ -73,16 +74,16 @@ objects. These are: **Required**. Called by ``Storage.open()``, this is the actual mechanism the storage class -uses to open the file. This must return a ``File`` object, though in most cases, -you'll want to return some subclass here that implements logic specific to the -backend storage system. The :exc:`FileNotFoundError` exception should be raised -when a file doesn't exist. +uses to open the file. This must return a ``File`` object, though in most +cases, you'll want to return some subclass here that implements logic specific +to the backend storage system. The :exc:`FileNotFoundError` exception should be +raised when a file doesn't exist. .. method:: _save(name, content) Called by ``Storage.save()``. The ``name`` will already have gone through -``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a -``File`` object itself. +``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be +a ``File`` object itself. Should return the actual name of the file saved (usually the ``name`` passed in, but if the storage needs to change the file name return the new name diff --git a/docs/howto/custom-lookups.txt b/docs/howto/custom-lookups.txt index fc8e928890..e287561834 100644 --- a/docs/howto/custom-lookups.txt +++ b/docs/howto/custom-lookups.txt @@ -39,9 +39,9 @@ lookup, then we need to tell Django about it:: return "%s <> %s" % (lhs, rhs), params To register the ``NotEqual`` lookup we will need to call ``register_lookup`` on -the field class we want the lookup to be available for. In this case, the lookup -makes sense on all ``Field`` subclasses, so we register it with ``Field`` -directly:: +the field class we want the lookup to be available for. In this case, the +lookup makes sense on all ``Field`` subclasses, so we register it with +``Field`` directly:: from django.db.models import Field @@ -61,10 +61,10 @@ could place the implementation in a ``models.py`` file, or register the lookup in the ``ready()`` method of an ``AppConfig``. Taking a closer look at the implementation, the first required attribute is -``lookup_name``. This allows the ORM to understand how to interpret ``name__ne`` -and use ``NotEqual`` to generate the SQL. By convention, these names are always -lowercase strings containing only letters, but the only hard requirement is -that it must not contain the string ``__``. +``lookup_name``. This allows the ORM to understand how to interpret +``name__ne`` and use ``NotEqual`` to generate the SQL. By convention, these +names are always lowercase strings containing only letters, but the only hard +requirement is that it must not contain the string ``__``. We then need to define the ``as_sql`` method. This takes a ``SQLCompiler`` object, called ``compiler``, and the active database connection. @@ -112,8 +112,8 @@ or where it did not exceed a certain amount functionality which is possible in a database backend independent manner, and without duplicating functionality already in Django. -We will start by writing an ``AbsoluteValue`` transformer. This will use the SQL -function ``ABS()`` to transform the value before comparison:: +We will start by writing an ``AbsoluteValue`` transformer. This will use the +SQL function ``ABS()`` to transform the value before comparison:: from django.db.models import Transform @@ -227,16 +227,16 @@ Notice also that as both sides are used multiple times in the query the params need to contain ``lhs_params`` and ``rhs_params`` multiple times. The final query does the inversion (``27`` to ``-27``) directly in the -database. The reason for doing this is that if the ``self.rhs`` is something else -than a plain integer value (for example an ``F()`` reference) we can't do the -transformations in Python. +database. The reason for doing this is that if the ``self.rhs`` is something +else than a plain integer value (for example an ``F()`` reference) we can't do +the transformations in Python. .. note:: In fact, most lookups with ``__abs`` could be implemented as range queries - like this, and on most database backends it is likely to be more sensible to - do so as you can make use of the indexes. However with PostgreSQL you may - want to add an index on ``abs(change)`` which would allow these queries to - be very efficient. + like this, and on most database backends it is likely to be more sensible + to do so as you can make use of the indexes. However with PostgreSQL you + may want to add an index on ``abs(change)`` which would allow these queries + to be very efficient. A bilateral transformer example =============================== @@ -252,10 +252,10 @@ very useful in practice as Django already comes with a bunch of built-in case-insensitive lookups, but it will be a nice demonstration of bilateral transformations in a database-agnostic way. -We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to -transform the values before comparison. We define -:attr:`bilateral = True ` to indicate that -this transformation should apply to both ``lhs`` and ``rhs``:: +We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` +to transform the values before comparison. We define :attr:`bilateral = True +` to indicate that this transformation +should apply to both ``lhs`` and ``rhs``:: from django.db.models import Transform @@ -272,8 +272,8 @@ Next, let's register it:: CharField.register_lookup(UpperCase) TextField.register_lookup(UpperCase) -Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a case -insensitive query like this: +Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a +case insensitive query like this: .. code-block:: sql diff --git a/docs/howto/custom-management-commands.txt b/docs/howto/custom-management-commands.txt index ce8c85276c..5ee82b3774 100644 --- a/docs/howto/custom-management-commands.txt +++ b/docs/howto/custom-management-commands.txt @@ -28,8 +28,8 @@ whose name doesn't begin with an underscore. For example: tests.py views.py -In this example, the ``closepoll`` command will be made available to any project -that includes the ``polls`` application in :setting:`INSTALLED_APPS`. +In this example, the ``closepoll`` command will be made available to any +project that includes the ``polls`` application in :setting:`INSTALLED_APPS`. The ``_private.py`` module will not be available as a management command. @@ -73,13 +73,12 @@ look like this:: .. _management-commands-output: .. note:: - When you are using management commands and wish to provide console - output, you should write to ``self.stdout`` and ``self.stderr``, - instead of printing to ``stdout`` and ``stderr`` directly. By - using these proxies, it becomes much easier to test your custom - command. Note also that you don't need to end messages with a newline - character, it will be added automatically, unless you specify the ``ending`` - parameter:: + When you are using management commands and wish to provide console output, + you should write to ``self.stdout`` and ``self.stderr``, instead of + printing to ``stdout`` and ``stderr`` directly. By using these proxies, it + becomes much easier to test your custom command. Note also that you don't + need to end messages with a newline character, it will be added + automatically, unless you specify the ``ending`` parameter:: self.stdout.write("Unterminated line", ending="") @@ -99,7 +98,8 @@ Accepting optional arguments The same ``closepoll`` could be easily modified to delete a given poll instead of closing it by accepting additional command line options. These custom -options can be added in the :meth:`~BaseCommand.add_arguments` method like this:: +options can be added in the :meth:`~BaseCommand.add_arguments` method like +this:: class Command(BaseCommand): def add_arguments(self, parser): @@ -273,7 +273,8 @@ the :meth:`~BaseCommand.handle` method must be implemented. Django. You can customize the instance by overriding this method and calling - ``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters. + ``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` + parameters. .. method:: BaseCommand.add_arguments(parser) diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 908c937151..4813211e04 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -7,17 +7,18 @@ How to create custom model fields Introduction ============ -The :doc:`model reference ` documentation explains how to use -Django's standard field classes -- :class:`~django.db.models.CharField`, +The :doc:`model reference ` documentation explains how to +use Django's standard field classes -- :class:`~django.db.models.CharField`, :class:`~django.db.models.DateField`, etc. For many purposes, those classes are all you'll need. Sometimes, though, the Django version won't meet your precise requirements, or you'll want to use a field that is entirely different from those shipped with Django. -Django's built-in field types don't cover every possible database column type -- -only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure +Django's built-in field types don't cover every possible database column type +-- only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure column types, such as geographic polygons or even user-created types such as -`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses. +`PostgreSQL custom types`_, you can define your own Django ``Field`` +subclasses. .. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html @@ -106,13 +107,13 @@ What does a field class do? --------------------------- All of Django's fields (and when we say *fields* in this document, we always -mean model fields and not :doc:`form fields `) are subclasses -of :class:`django.db.models.Field`. Most of the information that Django records -about a field is common to all fields -- name, help text, uniqueness and so -forth. Storing all that information is handled by ``Field``. We'll get into the -precise details of what ``Field`` can do later on; for now, suffice it to say -that everything descends from ``Field`` and then customizes key pieces of the -class behavior. +mean model fields and not :doc:`form fields `) are +subclasses of :class:`django.db.models.Field`. Most of the information that +Django records about a field is common to all fields -- name, help text, +uniqueness and so forth. Storing all that information is handled by ``Field``. +We'll get into the precise details of what ``Field`` can do later on; for now, +suffice it to say that everything descends from ``Field`` and then customizes +key pieces of the class behavior. It's important to realize that a Django field class is not what is stored in your model attributes. The model attributes contain normal Python objects. The @@ -149,9 +150,9 @@ is most similar to. Can you subclass an existing Django field and save yourself some work? If not, you should subclass the :class:`~django.db.models.Field` class, from which everything is descended. -Initializing your new field is a matter of separating out any arguments that are -specific to your case from the common arguments and passing the latter to the -``__init__()`` method of :class:`~django.db.models.Field` (or your parent +Initializing your new field is a matter of separating out any arguments that +are specific to your case from the common arguments and passing the latter to +the ``__init__()`` method of :class:`~django.db.models.Field` (or your parent class). In our example, we'll call our field ``HandField``. (It's a good idea to call @@ -214,9 +215,9 @@ The ``Field.__init__()`` method takes the following parameters: * :attr:`~django.db.models.Field.choices` * :attr:`~django.db.models.Field.help_text` * :attr:`~django.db.models.Field.db_column` -* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the - backend supports :doc:`tablespaces `. You can usually - ignore this option. +* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if + the backend supports :doc:`tablespaces `. You can + usually ignore this option. * :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was automatically created, as for the :class:`~django.db.models.OneToOneField` used by model inheritance. For advanced use only. @@ -253,9 +254,9 @@ name and import path. You do, however, have to care about the positional and keyword arguments, as these are likely the things you are changing. For example, in our ``HandField`` class we're always forcibly setting -max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field`` -class will see this and try to return it in the keyword arguments; thus, -we can drop it from the keyword arguments for readability:: +max_length in ``__init__()``. The ``deconstruct()`` method on the base +``Field`` class will see this and try to return it in the keyword arguments; +thus, we can drop it from the keyword arguments for readability:: from django.db import models @@ -471,10 +472,11 @@ over this field. You are then responsible for creating the column in the right table in some other way, but this gives you a way to tell Django to get out of the way. -The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey`` -and ``OneToOneField`` that point to another field to determine their database -column data types. For example, if you have an ``UnsignedAutoField``, you also -need the foreign keys that point to that field to use the same data type:: +The :meth:`~Field.rel_db_type` method is called by fields such as +``ForeignKey`` and ``OneToOneField`` that point to another field to determine +their database column data types. For example, if you have an +``UnsignedAutoField``, you also need the foreign keys that point to that field +to use the same data type:: # MySQL unsigned integer (range 0 to 4294967295). class UnsignedAutoField(models.AutoField): @@ -648,8 +650,8 @@ a custom form field (and even a form widget). See the :doc:`forms documentation If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you can override the :meth:`~Field.formfield` method to return ``None``. -Continuing our ongoing example, we can write the :meth:`~Field.formfield` method -as:: +Continuing our ongoing example, we can write the :meth:`~Field.formfield` +method as:: class HandField(models.Field): # ... diff --git a/docs/howto/custom-template-tags.txt b/docs/howto/custom-template-tags.txt index 1154e45515..b0f59ef981 100644 --- a/docs/howto/custom-template-tags.txt +++ b/docs/howto/custom-template-tags.txt @@ -285,13 +285,13 @@ Template filter code falls into one of two situations: order to make things easier for your template authors. In order for your filter to know the current auto-escaping state, set the - ``needs_autoescape`` flag to ``True`` when you register your filter function. - (If you don't specify this flag, it defaults to ``False``). This flag tells - Django that your filter function wants to be passed an extra keyword - argument, called ``autoescape``, that is ``True`` if auto-escaping is in - effect and ``False`` otherwise. It is recommended to set the default of the - ``autoescape`` parameter to ``True``, so that if you call the function - from Python code it will have escaping enabled by default. + ``needs_autoescape`` flag to ``True`` when you register your filter + function. (If you don't specify this flag, it defaults to ``False``). This + flag tells Django that your filter function wants to be passed an extra + keyword argument, called ``autoescape``, that is ``True`` if auto-escaping + is in effect and ``False`` otherwise. It is recommended to set the default + of the ``autoescape`` parameter to ``True``, so that if you call the + function from Python code it will have escaping enabled by default. For example, let's write a filter that emphasizes the first character of a string:: @@ -827,8 +827,8 @@ Advanced custom template tags ----------------------------- Sometimes the basic features for custom template tag creation aren't enough. -Don't worry, Django gives you complete access to the internals required to build -a template tag from the ground up. +Don't worry, Django gives you complete access to the internals required to +build a template tag from the ground up. A quick overview ---------------- @@ -856,10 +856,10 @@ function with the tag contents and the parser object itself. This function is responsible for returning a ``Node`` instance based on the contents of the tag. For example, let's write a full implementation of our template tag, -``{% current_time %}``, that displays the current date/time, formatted according -to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good -idea to decide the tag syntax before anything else. In our case, let's say the -tag should be used like this: +``{% current_time %}``, that displays the current date/time, formatted +according to a parameter given in the tag, in :func:`~time.strftime` syntax. +It's a good idea to decide the tag syntax before anything else. In our case, +let's say the tag should be used like this: .. code-block:: html+django @@ -1300,9 +1300,10 @@ Here's how a simplified ``{% comment %}`` tag might be implemented:: The actual implementation of :ttag:`{% comment %}` is slightly different in that it allows broken template tags to appear between ``{% comment %}`` and ``{% endcomment %}``. It does so by calling - ``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))`` - followed by ``parser.delete_first_token()``, thus avoiding the generation of a - node list. + ``parser.skip_past('endcomment')`` instead of + ``parser.parse(('endcomment',))`` followed by + ``parser.delete_first_token()``, thus avoiding the generation of a node + list. ``parser.parse()`` takes a tuple of names of block tags *to parse until*. It returns an instance of ``django.template.NodeList``, which is a list of diff --git a/docs/howto/deployment/asgi/uvicorn.txt b/docs/howto/deployment/asgi/uvicorn.txt index cd7cacd72f..b02d6c20ee 100644 --- a/docs/howto/deployment/asgi/uvicorn.txt +++ b/docs/howto/deployment/asgi/uvicorn.txt @@ -40,8 +40,9 @@ For more advanced usage, please read the `Uvicorn documentation `_. Deploying Django using Uvicorn and Gunicorn =========================================== -Gunicorn_ is a robust web server that implements process monitoring and automatic -restarts. This can be useful when running Uvicorn in a production environment. +Gunicorn_ is a robust web server that implements process monitoring and +automatic restarts. This can be useful when running Uvicorn in a production +environment. To install Uvicorn and Gunicorn, use the following: diff --git a/docs/howto/deployment/wsgi/apache-auth.txt b/docs/howto/deployment/wsgi/apache-auth.txt index 0629b785c5..454abf232c 100644 --- a/docs/howto/deployment/wsgi/apache-auth.txt +++ b/docs/howto/deployment/wsgi/apache-auth.txt @@ -2,10 +2,10 @@ How to authenticate against Django's user database from Apache ============================================================== -Since keeping multiple authentication databases in sync is a common problem when -dealing with Apache, you can configure Apache to authenticate against Django's -:doc:`authentication system ` directly. This requires Apache -version >= 2.2 and mod_wsgi >= 2.0. For example, you could: +Since keeping multiple authentication databases in sync is a common problem +when dealing with Apache, you can configure Apache to authenticate against +Django's :doc:`authentication system ` directly. This +requires Apache version >= 2.2 and mod_wsgi >= 2.0. For example, you could: * Serve static/media files directly from Apache only to authenticated users. diff --git a/docs/howto/deployment/wsgi/index.txt b/docs/howto/deployment/wsgi/index.txt index 502a253866..0d3b0cd220 100644 --- a/docs/howto/deployment/wsgi/index.txt +++ b/docs/howto/deployment/wsgi/index.txt @@ -37,9 +37,9 @@ deployments. WSGI servers obtain the path to the ``application`` callable from their configuration. Django's built-in server, namely the :djadmin:`runserver` -command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's -set to ``.wsgi.application``, which points to the ``application`` -callable in :file:`/wsgi.py`. +command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, +it's set to ``.wsgi.application``, which points to the +``application`` callable in :file:`/wsgi.py`. Configuring the settings module =============================== diff --git a/docs/howto/deployment/wsgi/modwsgi.txt b/docs/howto/deployment/wsgi/modwsgi.txt index c81b3df48a..a5699002ec 100644 --- a/docs/howto/deployment/wsgi/modwsgi.txt +++ b/docs/howto/deployment/wsgi/modwsgi.txt @@ -124,8 +124,8 @@ use ``WSGIPythonPath``; instead you should use the ``python-path`` option to WSGIProcessGroup example.com If you want to serve your project in a subdirectory -(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias`` -to the configuration above: +(``https://example.com/mysite`` in this example), you can add +``WSGIScriptAlias`` to the configuration above: .. code-block:: apache diff --git a/docs/howto/error-reporting.txt b/docs/howto/error-reporting.txt index 17ba14c35c..7670c3cac9 100644 --- a/docs/howto/error-reporting.txt +++ b/docs/howto/error-reporting.txt @@ -4,8 +4,8 @@ How to manage error reporting When you're running a public site you should always turn off the :setting:`DEBUG` setting. That will make your server run much faster, and will -also prevent malicious users from seeing details of your application that can be -revealed by the error pages. +also prevent malicious users from seeing details of your application that can +be revealed by the error pages. However, running with :setting:`DEBUG` set to ``False`` means you'll never see errors generated by your site -- everyone will instead see your public error @@ -87,11 +87,11 @@ regular expression objects. For example:: re.compile(r"^/phpmyadmin/"), ] -In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be -reported. Neither will any URL starting with ``/phpmyadmin/``. +In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* +be reported. Neither will any URL starting with ``/phpmyadmin/``. -The following example shows how to exclude some conventional URLs that browsers and -crawlers often request:: +The following example shows how to exclude some conventional URLs that browsers +and crawlers often request:: import re @@ -220,7 +220,8 @@ filtered out of error reports in a production environment (that is, where disclosed. To systematically hide all POST parameters of a request in error reports, - do not provide any argument to the ``sensitive_post_parameters`` decorator:: + do not provide any argument to the ``sensitive_post_parameters`` + decorator:: @sensitive_post_parameters() def my_view(request): ... @@ -379,5 +380,5 @@ within any given view by setting the ``HttpRequest``’s You can also set up custom error reporting by writing a custom piece of :ref:`exception middleware `. If you do write custom - error handling, it's a good idea to emulate Django's built-in error handling - and only report/log errors if :setting:`DEBUG` is ``False``. + error handling, it's a good idea to emulate Django's built-in error + handling and only report/log errors if :setting:`DEBUG` is ``False``. diff --git a/docs/howto/initial-data.txt b/docs/howto/initial-data.txt index d0d94ffd12..e517745cdd 100644 --- a/docs/howto/initial-data.txt +++ b/docs/howto/initial-data.txt @@ -26,8 +26,8 @@ however, this data isn't loaded automatically, except if you use A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the :djadmin:`manage.py dumpdata ` command. -Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML -(with PyYAML_ installed) documents. The :doc:`serialization documentation +Or, you can write fixtures by hand; fixtures can be written as JSON, XML or +YAML (with PyYAML_ installed) documents. The :doc:`serialization documentation ` has more details about each of these supported :ref:`serialization formats `. diff --git a/docs/howto/legacy-databases.txt b/docs/howto/legacy-databases.txt index 5730a8a059..f7be8c7d77 100644 --- a/docs/howto/legacy-databases.txt +++ b/docs/howto/legacy-databases.txt @@ -44,8 +44,8 @@ Save this as a file by using standard Unix output redirection: $ python manage.py inspectdb > models.py -This feature is meant as a shortcut, not as definitive model generation. See the -:djadmin:`documentation of inspectdb ` for more information. +This feature is meant as a shortcut, not as definitive model generation. See +the :djadmin:`documentation of inspectdb ` for more information. Once you've cleaned up your models, name the file ``models.py`` and put it in the Python package that holds your app. Then add the app to your diff --git a/docs/howto/outputting-csv.txt b/docs/howto/outputting-csv.txt index 6f2eedf3ba..c5ae7094d2 100644 --- a/docs/howto/outputting-csv.txt +++ b/docs/howto/outputting-csv.txt @@ -3,8 +3,8 @@ How to create CSV output ======================== This document explains how to output CSV (Comma Separated Values) dynamically -using Django views. To do this, you can either use the Python CSV library or the -Django template system. +using Django views. To do this, you can either use the Python CSV library or +the Django template system. Using the Python CSV library ============================ @@ -101,9 +101,10 @@ the assembly and transmission of a large CSV file:: Using the template system ========================= -Alternatively, you can use the :doc:`Django template system ` -to generate CSV. This is lower-level than using the convenient Python :mod:`csv` -module, but the solution is presented here for completeness. +Alternatively, you can use the :doc:`Django template system +` to generate CSV. This is lower-level than using the +convenient Python :mod:`csv` module, but the solution is presented here for +completeness. The idea here is to pass a list of items to your template, and have the template output the commas in a :ttag:`for` loop. diff --git a/docs/howto/outputting-pdf.txt b/docs/howto/outputting-pdf.txt index bb23affff4..67aedffb10 100644 --- a/docs/howto/outputting-pdf.txt +++ b/docs/howto/outputting-pdf.txt @@ -87,8 +87,8 @@ mention: browsers will handle the PDF using whatever program/plugin they've been configured to use for PDFs. -* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers - in the "Save as..." dialog. +* You can provide an arbitrary ``filename`` parameter. It'll be used by + browsers in the "Save as..." dialog. * You can hook into the ReportLab API: The same buffer passed as the first argument to ``canvas.Canvas`` can be fed to the @@ -112,8 +112,8 @@ Other formats Notice that there isn't a lot in these examples that's PDF-specific -- just the bits using ``reportlab``. You can use a similar technique to generate any arbitrary format that you can find a Python library for. Also see -:doc:`/howto/outputting-csv` for another example and some techniques you can use -when generated text-based formats. +:doc:`/howto/outputting-csv` for another example and some techniques you can +use when generated text-based formats. .. seealso:: diff --git a/docs/howto/overriding-templates.txt b/docs/howto/overriding-templates.txt index f99a1203a8..bbeb1e34c5 100644 --- a/docs/howto/overriding-templates.txt +++ b/docs/howto/overriding-templates.txt @@ -63,7 +63,8 @@ in the ``templates`` directory, and add the template files to that folder: The template loader first looks for templates in the ``DIRS`` directory. When the views in the ``blog`` app ask for the ``blog/post.html`` and -``blog/list.html`` templates, the loader will return the files you just created. +``blog/list.html`` templates, the loader will return the files you just +created. Overriding from an app's template directory =========================================== diff --git a/docs/howto/static-files/index.txt b/docs/howto/static-files/index.txt index 930e933f0e..d7be92ade6 100644 --- a/docs/howto/static-files/index.txt +++ b/docs/howto/static-files/index.txt @@ -155,10 +155,10 @@ file-serving functionality: It doesn't know about the finders feature of the collected under :setting:`STATIC_ROOT`. Because of this, ``staticfiles`` ships its own -:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass -of the built-in one that has the ability to transparently serve all the assets -during execution of these tests in a way very similar to what we get at -development time with ``DEBUG = True``, i.e. without having to collect them +:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a +subclass of the built-in one that has the ability to transparently serve all +the assets during execution of these tests in a way very similar to what we get +at development time with ``DEBUG = True``, i.e. without having to collect them using :djadmin:`collectstatic` first. Deployment diff --git a/docs/howto/upgrade-version.txt b/docs/howto/upgrade-version.txt index 02e0cbf9a0..f8e54152e0 100644 --- a/docs/howto/upgrade-version.txt +++ b/docs/howto/upgrade-version.txt @@ -91,7 +91,8 @@ Once you're ready, it is time to :doc:`install the new Django version is a major upgrade, you might want to set up a new environment with all the dependencies first. -If you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` flag: +If you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` +flag: .. console:: @@ -127,6 +128,6 @@ If you are using caching provided by Django, you should consider clearing your cache after upgrading. Otherwise you may run into problems, for example, if you are caching pickled objects as these objects are not guaranteed to be pickle-compatible across Django versions. A past instance of incompatibility -was caching pickled :class:`~django.http.HttpResponse` objects, either -directly or indirectly via the :func:`~django.views.decorators.cache.cache_page` +was caching pickled :class:`~django.http.HttpResponse` objects, either directly +or indirectly via the :func:`~django.views.decorators.cache.cache_page` decorator. diff --git a/docs/howto/writing-migrations.txt b/docs/howto/writing-migrations.txt index dee42ac14e..d092aec6e8 100644 --- a/docs/howto/writing-migrations.txt +++ b/docs/howto/writing-migrations.txt @@ -173,7 +173,8 @@ the respective field according to your needs. migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop), ] -* Now you can apply the migrations as usual with the :djadmin:`migrate` command. +* Now you can apply the migrations as usual with the :djadmin:`migrate` + command. Note there is a race condition if you allow objects to be created while this migration is running. Objects created after the ``AddField`` and before @@ -277,12 +278,13 @@ Migrating data between third-party apps You can use a data migration to move data from one third-party application to another. -If you plan to remove the old app later, you'll need to set the ``dependencies`` -property based on whether or not the old app is installed. Otherwise, you'll -have missing dependencies once you uninstall the old app. Similarly, you'll -need to catch :exc:`LookupError` in the ``apps.get_model()`` call that -retrieves models from the old app. This approach allows you to deploy your -project anywhere without first installing and then uninstalling the old app. +If you plan to remove the old app later, you'll need to set the +``dependencies`` property based on whether or not the old app is installed. +Otherwise, you'll have missing dependencies once you uninstall the old app. +Similarly, you'll need to catch :exc:`LookupError` in the ``apps.get_model()`` +call that retrieves models from the old app. This approach allows you to deploy +your project anywhere without first installing and then uninstalling the old +app. Here's a sample migration: diff --git a/docs/internals/contributing/committing-code.txt b/docs/internals/contributing/committing-code.txt index 2dc42d8853..c2dc0eee48 100644 --- a/docs/internals/contributing/committing-code.txt +++ b/docs/internals/contributing/committing-code.txt @@ -4,7 +4,8 @@ Committing code This section is addressed to the mergers and to anyone interested in knowing how code gets committed into Django. If you're a community member who wants to -contribute code to Django, look at :doc:`writing-code/working-with-git` instead. +contribute code to Django, look at :doc:`writing-code/working-with-git` +instead. .. _handling-pull-requests: diff --git a/docs/internals/contributing/triaging-tickets.txt b/docs/internals/contributing/triaging-tickets.txt index c0d87dcb7c..aac1354e5e 100644 --- a/docs/internals/contributing/triaging-tickets.txt +++ b/docs/internals/contributing/triaging-tickets.txt @@ -438,10 +438,10 @@ Next, we mark the current point in history as being "bad" since the test fails: Now, we need to find a point in git history before the regression was introduced (i.e. a point where the test passes). Use something like -``git checkout HEAD~100`` to check out an earlier revision (100 commits earlier, -in this case). Check if the test fails. If so, mark that point as "bad" -(``git bisect bad``), then check out an earlier revision and recheck. Once you -find a revision where your test passes, mark it as "good": +``git checkout HEAD~100`` to check out an earlier revision (100 commits +earlier, in this case). Check if the test fails. If so, mark that point as +"bad" (``git bisect bad``), then check out an earlier revision and recheck. +Once you find a revision where your test passes, mark it as "good": .. code-block:: shell diff --git a/docs/internals/contributing/writing-code/coding-style.txt b/docs/internals/contributing/writing-code/coding-style.txt index 125525c737..64ef6c5a51 100644 --- a/docs/internals/contributing/writing-code/coding-style.txt +++ b/docs/internals/contributing/writing-code/coding-style.txt @@ -96,13 +96,12 @@ Python style * In docstrings, follow the style of existing docstrings and :pep:`257`. -* In tests, use - :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and - :meth:`~django.test.SimpleTestCase.assertWarnsMessage` - instead of :meth:`~unittest.TestCase.assertRaises` and - :meth:`~unittest.TestCase.assertWarns` so you can check the - exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` - and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular +* In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and + :meth:`~django.test.SimpleTestCase.assertWarnsMessage` instead of + :meth:`~unittest.TestCase.assertRaises` and + :meth:`~unittest.TestCase.assertWarns` so you can check the exception or + warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` and + :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular expression matching. Use :meth:`assertIs(…, True/False)` for testing @@ -149,9 +148,10 @@ Imports * Put imports in these groups: future, standard library, third-party libraries, other Django components, local Django component, try/excepts. Sort lines in - each group alphabetically by the full module name. Place all ``import module`` - statements before ``from module import objects`` in each section. Use absolute - imports for other Django components and relative imports for local components. + each group alphabetically by the full module name. Place all + ``import module`` statements before ``from module import objects`` in each + section. Use absolute imports for other Django components and relative + imports for local components. * On each line, alphabetize the items with the upper case items grouped before the lowercase items. diff --git a/docs/internals/contributing/writing-code/javascript.txt b/docs/internals/contributing/writing-code/javascript.txt index 25165206f0..b61fc009b7 100644 --- a/docs/internals/contributing/writing-code/javascript.txt +++ b/docs/internals/contributing/writing-code/javascript.txt @@ -17,8 +17,8 @@ Code style for indentation, but there are some exceptions. * When naming variables, use ``camelCase`` instead of ``underscore_case``. - Different JavaScript files sometimes use a different code style. Please try to - conform to the code style of each file. + Different JavaScript files sometimes use a different code style. Please try + to conform to the code style of each file. * Use the `ESLint`_ code linter to check your code for bugs and style errors. ESLint will be run when you run the JavaScript tests. We also recommended @@ -89,8 +89,8 @@ The JavaScript tests may be run from a web browser or from the command line. Testing from a web browser ~~~~~~~~~~~~~~~~~~~~~~~~~~ -To run the tests from a web browser, open up :source:`js_tests/tests.html` in your -browser. +To run the tests from a web browser, open up :source:`js_tests/tests.html` in +your browser. To measure code coverage when running the tests, you need to view that file over HTTP. To view code coverage: diff --git a/docs/internals/contributing/writing-code/submitting-patches.txt b/docs/internals/contributing/writing-code/submitting-patches.txt index 75186111dd..d1d5a8a32d 100644 --- a/docs/internals/contributing/writing-code/submitting-patches.txt +++ b/docs/internals/contributing/writing-code/submitting-patches.txt @@ -204,9 +204,12 @@ whether to accept it. Some examples of DEPs that have been approved and fully implemented: -* `DEP 181: ORM Expressions `_ -* `DEP 182: Multiple Template Engines `_ -* `DEP 201: Simplified routing syntax `_ +* `DEP 181: ORM Expressions + `_ +* `DEP 182: Multiple Template Engines + `_ +* `DEP 201: Simplified routing syntax + `_ .. _Django Forum: https://forum.djangoproject.com/ .. _Django Enhancement Proposals: https://github.com/django/deps @@ -226,19 +229,19 @@ There are a couple of reasons that code in Django might be deprecated: no longer needs to support the older version of Python that doesn't include the library, the library will be deprecated in Django. -As the :ref:`deprecation policy` describes, -the first release of Django that deprecates a feature (``A.B``) should raise a -``RemovedInDjangoXXWarning`` (where XX is the Django version where the feature -will be removed) when the deprecated feature is invoked. Assuming we have good -test coverage, these warnings are converted to errors when :ref:`running the -test suite ` with warnings enabled: +As the :ref:`deprecation policy` +describes, the first release of Django that deprecates a feature (``A.B``) +should raise a ``RemovedInDjangoXXWarning`` (where XX is the Django version +where the feature will be removed) when the deprecated feature is invoked. +Assuming we have good test coverage, these warnings are converted to errors +when :ref:`running the test suite ` with warnings enabled: ``python -Wa runtests.py``. Thus, when adding a ``RemovedInDjangoXXWarning`` you need to eliminate or silence any warnings generated when running the tests. -The first step is to remove any use of the deprecated behavior by Django itself. -Next you can silence warnings in tests that actually test the deprecated -behavior by using the ``ignore_warnings`` decorator, either at the test or class -level: +The first step is to remove any use of the deprecated behavior by Django +itself. Next you can silence warnings in tests that actually test the +deprecated behavior by using the ``ignore_warnings`` decorator, either at the +test or class level: #) In a particular test:: @@ -305,8 +308,9 @@ Finally, there are a couple of updates to Django's documentation to make: applicable, to the current release notes (``docs/releases/A.B.txt``) under the "Features deprecated in A.B" heading. -#) Add an entry in the deprecation timeline (``docs/internals/deprecation.txt``) - under the appropriate version describing what code will be removed. +#) Add an entry in the deprecation timeline + (``docs/internals/deprecation.txt``) under the appropriate version + describing what code will be removed. Once you have completed these steps, you are finished with the deprecation. In each :term:`feature release `, all @@ -402,10 +406,10 @@ Bugs * Is there a proper regression test (the test should fail before the fix is applied)? -* If it's a bug that :ref:`qualifies for a backport ` - to the stable version of Django, is there a release note in - ``docs/releases/A.B.C.txt``? Bug fixes that will be applied only to the main - branch don't need a release note. +* If it's a bug that :ref:`qualifies for a backport + ` to the stable version of Django, is there a + release note in ``docs/releases/A.B.C.txt``? Bug fixes that will be applied + only to the main branch don't need a release note. New Features ------------ diff --git a/docs/internals/contributing/writing-code/unit-tests.txt b/docs/internals/contributing/writing-code/unit-tests.txt index 1c993f5fc6..05b2bf09c6 100644 --- a/docs/internals/contributing/writing-code/unit-tests.txt +++ b/docs/internals/contributing/writing-code/unit-tests.txt @@ -398,9 +398,9 @@ and also excludes several directories not relevant to the results Contrib apps ============ -Tests for contrib apps can be found in the :source:`tests/` directory, typically -under ``_tests``. For example, tests for ``contrib.auth`` are located -in :source:`tests/auth_tests`. +Tests for contrib apps can be found in the :source:`tests/` directory, +typically under ``_tests``. For example, tests for ``contrib.auth`` +are located in :source:`tests/auth_tests`. .. _troubleshooting-unit-tests: diff --git a/docs/internals/contributing/writing-documentation.txt b/docs/internals/contributing/writing-documentation.txt index 2654cce06e..ff9bf5da47 100644 --- a/docs/internals/contributing/writing-documentation.txt +++ b/docs/internals/contributing/writing-documentation.txt @@ -205,8 +205,8 @@ All Python code blocks should be formatted using the :pypi:`blacken-docs` auto-formatter. This is automatically run by the :ref:`pre-commit hook ` if configured. -The check can also be run manually: provided that ``blacken-docs`` is installed, -run the following command from the ``docs`` directory: +The check can also be run manually: provided that ``blacken-docs`` is +installed, run the following command from the ``docs`` directory: .. console:: @@ -245,8 +245,8 @@ Entries that have a status of "broken" need to be fixed. Those that have a status of "redirected" may need to be updated to point to the canonical location, e.g. the scheme has changed ``http://`` → ``https://``. In certain cases, we do not want to update a "redirected" link, e.g. a rewrite to always -point to the latest or stable version of the documentation, e.g. ``/en/stable/`` → -``/en/3.2/``. +point to the latest or stable version of the documentation, e.g. +``/en/stable/`` → ``/en/3.2/``. Writing style ============= @@ -523,12 +523,12 @@ General improvements or other changes to the APIs that should be emphasized should use the "``.. versionchanged:: X.Y``" directive (with the same format as the ``versionadded`` mentioned above. -These ``versionadded`` and ``versionchanged`` blocks should be "self-contained." -In other words, since we only keep these annotations around for two releases, -it's nice to be able to remove the annotation and its contents without having -to reflow, reindent, or edit the surrounding text. For example, instead of -putting the entire description of a new or changed feature in a block, do -something like this: +These ``versionadded`` and ``versionchanged`` blocks should be +"self-contained." In other words, since we only keep these annotations around +for two releases, it's nice to be able to remove the annotation and its +contents without having to reflow, reindent, or edit the surrounding text. For +example, instead of putting the entire description of a new or changed feature +in a block, do something like this: .. code-block:: rst @@ -659,12 +659,12 @@ you'd like to help translate the documentation into another language. ``django-admin`` man page ========================= -Sphinx can generate a manual page for the -:doc:`django-admin ` command. This is configured in -``docs/conf.py``. Unlike other documentation output, this man page should be -included in the Django repository and the releases as -``docs/man/django-admin.1``. There isn't a need to update this file when -updating the documentation, as it's updated once as part of the release process. +Sphinx can generate a manual page for the :doc:`django-admin +` command. This is configured in ``docs/conf.py``. Unlike +other documentation output, this man page should be included in the Django +repository and the releases as ``docs/man/django-admin.1``. There isn't a need +to update this file when updating the documentation, as it's updated once as +part of the release process. To generate an updated version of the man page, in the ``docs`` directory, run: diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index b5dc17fd6a..5337800d67 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -748,8 +748,8 @@ details on these changes. (replaced by :py:mod:`argparse`). * The class ``django.core.management.NoArgsCommand`` will be removed. Use - :class:`~django.core.management.BaseCommand` instead, which takes no arguments - by default. + :class:`~django.core.management.BaseCommand` instead, which takes no + arguments by default. * ``django.core.context_processors`` module will be removed. @@ -779,7 +779,8 @@ details on these changes. * ``get_all_related_many_to_many_objects()`` * ``get_all_related_m2m_objects_with_model()`` -* The ``error_message`` argument of ``django.forms.RegexField`` will be removed. +* The ``error_message`` argument of ``django.forms.RegexField`` will be + removed. * The ``unordered_list`` filter will no longer support old style lists. @@ -805,7 +806,8 @@ details on these changes. ``django.contrib.admin.helpers.InlineAdminForm`` will be removed. * The backwards compatibility shim to allow ``FormMixin.get_form()`` to be - defined with no default value for its ``form_class`` argument will be removed. + defined with no default value for its ``form_class`` argument will be + removed. * The following settings will be removed: @@ -872,14 +874,14 @@ details on these changes. * Support for the legacy ``%()s`` syntax in ``ModelFormMixin.success_url`` will be removed. -* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``, ``extent3d()``, - ``make_line()``, and ``unionagg()`` will be removed. +* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``, + ``extent3d()``, ``make_line()``, and ``unionagg()`` will be removed. * Ability to specify ``ContentType.name`` when creating a content type instance will be removed. -* Support for the old signature of ``allow_migrate`` will be removed. It changed - from ``allow_migrate(self, db, model)`` to +* Support for the old signature of ``allow_migrate`` will be removed. It + changed from ``allow_migrate(self, db, model)`` to ``allow_migrate(self, db, app_label, model_name=None, **hints)``. * Support for the syntax of ``{% cycle %}`` that uses comma-separated arguments @@ -1002,8 +1004,8 @@ details on these changes. * ``django.utils.module_loading.import_by_path`` will be removed in favor of ``django.utils.module_loading.import_string``. -* ``ssi`` and ``url`` template tags will be removed from the ``future`` template - tag library (used during the 1.3/1.4 deprecation period). +* ``ssi`` and ``url`` template tags will be removed from the ``future`` + template tag library (used during the 1.3/1.4 deprecation period). * ``django.utils.text.javascript_quote`` will be removed. @@ -1013,9 +1015,9 @@ details on these changes. * The ``cache_choices`` option to :class:`~django.forms.ModelChoiceField` and :class:`~django.forms.ModelMultipleChoiceField` will be removed. -* The default value of the - :attr:`RedirectView.permanent ` - attribute will change from ``True`` to ``False``. +* The default value of the :attr:`RedirectView.permanent + ` attribute will change + from ``True`` to ``False``. * ``django.contrib.sitemaps.FlatPageSitemap`` will be removed in favor of ``django.contrib.flatpages.sitemaps.FlatPageSitemap``. @@ -1098,8 +1100,8 @@ details on these changes. * The ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting will be removed. * Usage of the hardcoded *Hold down "Control", or "Command" on a Mac, to select - more than one.* string to override or append to user-provided ``help_text`` in - forms for ManyToMany model fields will not be performed by Django anymore + more than one.* string to override or append to user-provided ``help_text`` + in forms for ManyToMany model fields will not be performed by Django anymore either at the model or forms layer. * The ``Model._meta.get_(add|change|delete)_permission`` methods will @@ -1112,8 +1114,9 @@ details on these changes. (``django.contrib.gis.sitemaps.views.index`` and ``django.contrib.gis.sitemaps.views.sitemap``). -* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter and - ``django.utils.html.clean_html`` will be removed following an accelerated deprecation. +* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter + and ``django.utils.html.clean_html`` will be removed following an accelerated + deprecation. .. _deprecation-removed-in-1.7: @@ -1251,8 +1254,8 @@ details on these changes. * Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of template filter functions will no longer be supported. -* The attribute ``HttpRequest.raw_post_data`` was renamed to ``HttpRequest.body`` - in 1.4. The backward compatibility will be removed -- +* The attribute ``HttpRequest.raw_post_data`` was renamed to + ``HttpRequest.body`` in 1.4. The backward compatibility will be removed -- ``HttpRequest.raw_post_data`` will no longer work. * The value for the ``post_url_continue`` parameter in @@ -1337,10 +1340,10 @@ details on these changes. performance issues and will follow a slightly accelerated deprecation timeframe. -* Translations located under the so-called *project path* will be ignored during - the translation building process performed at runtime. The - :setting:`LOCALE_PATHS` setting can be used for the same task by including the - filesystem path to a ``locale`` directory containing non-app-specific +* Translations located under the so-called *project path* will be ignored + during the translation building process performed at runtime. The + :setting:`LOCALE_PATHS` setting can be used for the same task by including + the filesystem path to a ``locale`` directory containing non-app-specific translations in its value. * The Markup contrib app will no longer support versions of Python-Markdown diff --git a/docs/internals/git.txt b/docs/internals/git.txt index 7329fe0bbc..8b6ce3d453 100644 --- a/docs/internals/git.txt +++ b/docs/internals/git.txt @@ -115,11 +115,11 @@ updates. committed until the final release happened. For example, shortly after the release of Django 1.3 the branch - ``stable/1.3.x`` was created. Official support for that release has expired, - and so it no longer receives direct maintenance from the Django project. - However, that and all other similarly named branches continue to exist, and - interested community members have occasionally used them to provide - unofficial support for old Django releases. + ``stable/1.3.x`` was created. Official support for that release has + expired, and so it no longer receives direct maintenance from the Django + project. However, that and all other similarly named branches continue to + exist, and interested community members have occasionally used them to + provide unofficial support for old Django releases. Tags ==== diff --git a/docs/internals/howto-release-django.txt b/docs/internals/howto-release-django.txt index 5e0f8469d2..de5e076702 100644 --- a/docs/internals/howto-release-django.txt +++ b/docs/internals/howto-release-django.txt @@ -471,7 +471,8 @@ Building the artifacts .. admonition:: Optionally use helper scripts - You can streamline some of the steps below using helper scripts from the Wiki: + You can streamline some of the steps below using helper scripts from the + Wiki: * `Release script `_ diff --git a/docs/internals/organization.txt b/docs/internals/organization.txt index 907c4185cc..a213794ad3 100644 --- a/docs/internals/organization.txt +++ b/docs/internals/organization.txt @@ -72,9 +72,9 @@ to make the role of Merger sustainable. The following restrictions apply to the role of Merger: -- A person must not simultaneously serve as a member of the steering council. If - a Merger is elected to the steering council, they shall cease to be a Merger - immediately upon taking up membership in the steering council. +- A person must not simultaneously serve as a member of the steering council. + If a Merger is elected to the steering council, they shall cease to be a + Merger immediately upon taking up membership in the steering council. - A person may serve in the roles of Releaser and Merger simultaneously. The selection process, when a vacancy occurs or when the steering council deems @@ -122,10 +122,10 @@ upload them to the :pypi:`Python Package Index ` and to the Membership ---------- -`The steering council`_ selects Releasers_ as necessary to maintain their number -at a minimum of three, in order to spread the workload and avoid over-burdening -or burning out any individual Releaser. There is no upper limit to the number -of Releasers. +`The steering council`_ selects Releasers_ as necessary to maintain their +number at a minimum of three, in order to spread the workload and avoid +over-burdening or burning out any individual Releaser. There is no upper limit +to the number of Releasers. It's not a requirement that a Releaser is also a Django Fellow, but the Django Software Foundation has the power to use funding of Fellow positions as a way @@ -223,13 +223,14 @@ who demonstrate: years must still demonstrate an understanding of Django's changes and direction within those three years. -A new council is elected after each release cycle of Django. The election process -works as follows: +A new council is elected after each release cycle of Django. The election +process works as follows: -#. The steering council directs one of its members to notify the Secretary of the - Django Software Foundation, in writing, of the triggering of the election, - and the condition which triggered it. The Secretary post to the appropriate - venue -- the `Django Forum`_ to announce the election and its timeline. +#. The steering council directs one of its members to notify the Secretary of + the Django Software Foundation, in writing, of the triggering of the + election, and the condition which triggered it. The Secretary post to the + appropriate venue -- the `Django Forum`_ to announce the election and its + timeline. #. As soon as the election is announced, the `DSF Board`_ begin a period of voter registration. All `individual members of the DSF`_ are automatically registered and need not explicitly register. All other persons who believe @@ -267,12 +268,12 @@ A member of the steering council may be removed by: - Becoming disqualified due to actions taken by the Code of Conduct committee of the Django Software Foundation. - Determining that they did not possess the qualifications of a member of the - steering council. This determination must be made jointly by the other members - of the steering council, and the `DSF Board`_. A valid determination of - ineligibility requires that all other members of the steering council and all - members of the DSF Board vote who can vote on the issue (the affected person, - if a DSF Board member, must not vote) vote "yes" on a motion that the person - in question is ineligible. + steering council. This determination must be made jointly by the other + members of the steering council, and the `DSF Board`_. A valid determination + of ineligibility requires that all other members of the steering council and + all members of the DSF Board vote who can vote on the issue (the affected + person, if a DSF Board member, must not vote) vote "yes" on a motion that the + person in question is ineligible. .. _`Django Forum`: https://forum.djangoproject.com/ .. _`Django Git repository`: https://github.com/django/django/ diff --git a/docs/internals/release-process.txt b/docs/internals/release-process.txt index ec5bdd3c7a..53c60d50db 100644 --- a/docs/internals/release-process.txt +++ b/docs/internals/release-process.txt @@ -45,8 +45,8 @@ security purposes, please see :doc:`our security policies `. bugs and/or security issues. These releases will be 100% compatible with the associated feature release, - unless this is impossible for security reasons or to prevent data loss. - So the answer to "should I upgrade to the latest patch release?" will always + unless this is impossible for security reasons or to prevent data loss. So + the answer to "should I upgrade to the latest patch release?" will always be "yes." Long-term support release @@ -123,8 +123,8 @@ See also the :ref:`deprecating-a-feature` guide. Supported versions ================== -At any moment in time, Django's developer team will support a set of releases to -varying levels. See `the supported versions section +At any moment in time, Django's developer team will support a set of releases +to varying levels. See `the supported versions section `_ of the download page for the current state of support for each version. diff --git a/docs/internals/security.txt b/docs/internals/security.txt index 567446c30e..745f26f5f5 100644 --- a/docs/internals/security.txt +++ b/docs/internals/security.txt @@ -292,7 +292,8 @@ requires a security release: * Exploits which fail to follow security best practices, such as failure to sanitize user input. For other examples, see our :ref:`security documentation `. - * Exploits in AI generated code that do not adhere to security best practices. + * Exploits in AI generated code that do not adhere to security best + practices. The security team may conclude that the source of the vulnerability is within the Python standard library, in which case the reporter will be asked to report @@ -303,8 +304,8 @@ On occasion, a security release may be issued to help resolve a security vulnerability within a popular third-party package. These reports should come from the package maintainers. -If you are unsure whether your finding meets these criteria, please still report -it :ref:`privately by emailing security@djangoproject.com +If you are unsure whether your finding meets these criteria, please still +report it :ref:`privately by emailing security@djangoproject.com `. The security team will review your report and recommend the correct course of action. diff --git a/docs/intro/contributing.txt b/docs/intro/contributing.txt index 0b93d61b7a..0342f3e816 100644 --- a/docs/intro/contributing.txt +++ b/docs/intro/contributing.txt @@ -32,9 +32,9 @@ don't, `Dive Into Python`_ is a fantastic (and free) online book for beginning Python programmers. Those of you who are unfamiliar with version control systems and Trac will find -that this tutorial and its links include just enough information to get started. -However, you'll probably want to read some more about these different tools if -you plan on contributing to Django regularly. +that this tutorial and its links include just enough information to get +started. However, you'll probably want to read some more about these different +tools if you plan on contributing to Django regularly. For the most part though, this tutorial tries to explain as much as possible, so that it can be of use to the widest audience. @@ -52,9 +52,9 @@ so that it can be of use to the widest audience. What does this tutorial cover? ------------------------------ -We'll be walking you through contributing to Django for the first time. -By the end of this tutorial, you should have a basic understanding of both the -tools and the processes involved. Specifically, we'll be covering the following: +We'll be walking you through contributing to Django for the first time. By the +end of this tutorial, you should have a basic understanding of both the tools +and the processes involved. Specifically, we'll be covering the following: * Installing Git. * Downloading a copy of Django's development version. @@ -85,7 +85,8 @@ Code of Conduct =============== As a contributor, you can help us keep the Django community open and inclusive. -Please read and follow our `Code of Conduct `_. +Please read and follow our `Code of Conduct +`_. Installing Git ============== @@ -123,11 +124,11 @@ Download the Django source code repository using the following command: all of Django's commit history, which reduces data transfer from ~250 MB to ~70 MB. -Now that you have a local copy of Django, you can install it just like you would -install any package using ``pip``. The most convenient way to do so is by using -a *virtual environment*, which is a feature built into Python that allows you -to keep a separate directory of installed packages for each of your projects so -that they don't interfere with each other. +Now that you have a local copy of Django, you can install it just like you +would install any package using ``pip``. The most convenient way to do so is by +using a *virtual environment*, which is a feature built into Python that allows +you to keep a separate directory of installed packages for each of your +projects so that they don't interfere with each other. It's a good idea to keep all your virtual environments in one place, for example in ``.virtualenvs/`` in your home directory. @@ -176,20 +177,20 @@ Go ahead and install the previously cloned copy of Django: $ python -m pip install -e /path/to/your/local/clone/django/ -The installed version of Django is now pointing at your local copy by installing -in editable mode. You will immediately see any changes you make to it, which is -of great help when testing your first contribution. +The installed version of Django is now pointing at your local copy by +installing in editable mode. You will immediately see any changes you make to +it, which is of great help when testing your first contribution. Running Django's test suite for the first time ============================================== When contributing to Django it's very important that your code changes don't introduce bugs into other areas of Django. One way to check that Django still -works after you make your changes is by running Django's test suite. If all -the tests still pass, then you can be reasonably sure that your changes -work and haven't broken other parts of Django. If you've never run Django's test -suite before, it's a good idea to run it once beforehand to get familiar with -its output. +works after you make your changes is by running Django's test suite. If all the +tests still pass, then you can be reasonably sure that your changes work and +haven't broken other parts of Django. If you've never run Django's test suite +before, it's a good idea to run it once beforehand to get familiar with its +output. Before running the test suite, enter the Django ``tests/`` directory using the ``cd tests`` command, and install test dependencies by running: @@ -348,8 +349,8 @@ that's really what happens. ``cd`` to the Django ``tests/`` directory and run: $ ./runtests.py shortcuts -If the tests ran correctly, you should see one failure corresponding to the test -method we added, with this error: +If the tests ran correctly, you should see one failure corresponding to the +test method we added, with this error: .. code-block:: pytb diff --git a/docs/intro/index.txt b/docs/intro/index.txt index a68d4876b7..d049718b4c 100644 --- a/docs/intro/index.txt +++ b/docs/intro/index.txt @@ -24,8 +24,8 @@ place: read this material to quickly get up and running. .. seealso:: - If you're new to Python_, you might want to start by getting an idea of what - the language is like. Django is 100% Python, so if you've got minimal + If you're new to Python_, you might want to start by getting an idea of + what the language is like. Django is 100% Python, so if you've got minimal comfort with Python you'll probably get a lot more out of Django. If you're new to programming entirely, you might want to start with this diff --git a/docs/intro/install.txt b/docs/intro/install.txt index b590df951b..2da37537b8 100644 --- a/docs/intro/install.txt +++ b/docs/intro/install.txt @@ -32,9 +32,9 @@ you should see something like: Set up a database ================= -This step is only necessary if you'd like to work with a "large" database engine -like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult -the :ref:`database installation information `. +This step is only necessary if you'd like to work with a "large" database +engine like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, +consult the :ref:`database installation information `. Install Django ============== diff --git a/docs/intro/overview.txt b/docs/intro/overview.txt index af87a01bb4..cad611a829 100644 --- a/docs/intro/overview.txt +++ b/docs/intro/overview.txt @@ -9,15 +9,15 @@ overview of how to write a database-driven web app with Django. The goal of this document is to give you enough technical specifics to understand how Django works, but this isn't intended to be a tutorial or reference -- but we've got both! When you're ready to start a project, you can -:doc:`start with the tutorial ` or :doc:`dive right into more -detailed documentation `. +:doc:`start with the tutorial ` or :doc:`dive right into +more detailed documentation `. Design your model ================= Although you can use Django without a database, it comes with an -`object-relational mapper`_ in which you describe your database layout in Python -code. +`object-relational mapper`_ in which you describe your database layout in +Python code. .. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping @@ -247,19 +247,19 @@ and renders the template with the retrieved data. Here's an example view for context = {"year": year, "article_list": a_list} return render(request, "news/year_archive.html", context) -This example uses Django's :doc:`template system `, which has -several powerful features but strives to stay simple enough for non-programmers -to use. +This example uses Django's :doc:`template system `, which +has several powerful features but strives to stay simple enough for +non-programmers to use. Design your templates ===================== The code above loads the ``news/year_archive.html`` template. -Django has a template search path, which allows you to minimize redundancy among -templates. In your Django settings, you specify a list of directories to check -for templates with :setting:`DIRS `. If a template doesn't exist -in the first directory, it checks the second, and so on. +Django has a template search path, which allows you to minimize redundancy +among templates. In your Django settings, you specify a list of directories to +check for templates with :setting:`DIRS `. If a template +doesn't exist in the first directory, it checks the second, and so on. Let's say the ``news/year_archive.html`` template was found. Here's what that might look like: @@ -287,14 +287,14 @@ used only for attribute lookup. They also can do dictionary-key lookup, index lookup and function calls. Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|" -character). This is called a template filter, and it's a way to filter the value -of a variable. In this case, the date filter formats a Python datetime object in -the given format (as found in PHP's date function). +character). This is called a template filter, and it's a way to filter the +value of a variable. In this case, the date filter formats a Python datetime +object in the given format (as found in PHP's date function). -You can chain together as many filters as you'd like. You can write :ref:`custom -template filters `. You can write -:doc:`custom template tags `, which run custom -Python code behind the scenes. +You can chain together as many filters as you'd like. You can write +:ref:`custom template filters `. You can +write :doc:`custom template tags `, which run +custom Python code behind the scenes. Finally, Django uses the concept of "template inheritance". That's what the ``{% extends "base.html" %}`` does. It means "First load the template called @@ -319,9 +319,9 @@ Here's what the "base.html" template, including the use of :doc:`static files -Simplistically, it defines the look-and-feel of the site (with the site's logo), -and provides "holes" for child templates to fill. This means that a site redesign -can be done by changing a single file -- the base template. +Simplistically, it defines the look-and-feel of the site (with the site's +logo), and provides "holes" for child templates to fill. This means that a site +redesign can be done by changing a single file -- the base template. It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django's creators have used this diff --git a/docs/intro/reusable-apps.txt b/docs/intro/reusable-apps.txt index 2afc3f2ddd..723f752cc5 100644 --- a/docs/intro/reusable-apps.txt +++ b/docs/intro/reusable-apps.txt @@ -344,8 +344,8 @@ the world! If this wasn't just an example, you could now: * Upload the package on your website. * Post the package on a public repository, such as `the Python Package Index - (PyPI)`_. `packaging.python.org `_ has `a good - tutorial `_ + (PyPI)`_. There is `a good tutorial + `_ for doing this. Installing Python packages with a virtual environment diff --git a/docs/intro/tutorial01.txt b/docs/intro/tutorial01.txt index fc968ebf8f..db6150a3e8 100644 --- a/docs/intro/tutorial01.txt +++ b/docs/intro/tutorial01.txt @@ -39,8 +39,8 @@ Creating a project ================== If this is your first time using Django, you'll have to take care of some -initial setup. Namely, you'll need to auto-generate some code that establishes a -Django :term:`project` -- a collection of settings for an instance of Django, +initial setup. Namely, you'll need to auto-generate some code that establishes +a Django :term:`project` -- a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings. @@ -122,8 +122,8 @@ You'll see the following output on the command line: System check identified no issues (0 silenced). - You have unapplied migrations; your app may not work properly until they are applied. - Run 'python manage.py migrate' to apply them. + You have unapplied migrations; your app may not work properly until they are + applied. Run 'python manage.py migrate' to apply them. |today| - 15:50:53 Django version |version|, using settings 'mysite.settings' @@ -150,7 +150,8 @@ Now's a good time to note: **don't** use this server in anything resembling a production environment. It's intended only for use while developing. (We're in the business of making web frameworks, not web servers.) -(To serve the site on a different port, see the :djadmin:`runserver` reference.) +(To serve the site on a different port, see the :djadmin:`runserver` +reference.) .. admonition:: Automatic reloading of :djadmin:`runserver` diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt index f78a83d1bd..af9f717225 100644 --- a/docs/intro/tutorial02.txt +++ b/docs/intro/tutorial02.txt @@ -51,7 +51,8 @@ come with Django: * :mod:`django.contrib.staticfiles` -- A framework for managing static files. -These applications are included by default as a convenience for the common case. +These applications are included by default as a convenience for the common +case. Some of these applications make use of at least one database table, though, so we need to create the tables in the database before we can use them. To do @@ -62,13 +63,13 @@ that, run the following command: $ python manage.py migrate The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting -and creates any necessary database tables according to the database settings -in your :file:`mysite/settings.py` file and the database migrations shipped -with the app (we'll cover those later). You'll see a message for each -migration it applies. If you're interested, run the command-line client for your -database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), -``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to -display the tables Django created. +and creates any necessary database tables according to the database settings in +your :file:`mysite/settings.py` file and the database migrations shipped with +the app (we'll cover those later). You'll see a message for each migration it +applies. If you're interested, run the command-line client for your database +and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), ``.tables`` +(SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to display the +tables Django created. .. admonition:: For the minimalists @@ -94,8 +95,8 @@ additional metadata. Django follows the :ref:`DRY Principle `. The goal is to define your data model in one place and automatically derive things from it. - This includes the migrations - unlike in Ruby On Rails, for example, migrations - are entirely derived from your models file, and are essentially a + This includes the migrations - unlike in Ruby On Rails, for example, + migrations are entirely derived from your models file, and are essentially a history that Django can roll through to update your database schema to match your current models. @@ -138,12 +139,12 @@ format. You'll use this value in your Python code, and your database will use it as the column name. You can use an optional first positional argument to a -:class:`~django.db.models.Field` to designate a human-readable name. That's used -in a couple of introspective parts of Django, and it doubles as documentation. -If this field isn't provided, Django will use the machine-readable name. In this -example, we've only defined a human-readable name for ``Question.pub_date``. -For all other fields in this model, the field's machine-readable name will -suffice as its human-readable name. +:class:`~django.db.models.Field` to designate a human-readable name. That's +used in a couple of introspective parts of Django, and it doubles as +documentation. If this field isn't provided, Django will use the +machine-readable name. In this example, we've only defined a human-readable +name for ``Question.pub_date``. For all other fields in this model, the field's +machine-readable name will suffice as its human-readable name. Some :class:`~django.db.models.Field` classes have required arguments. :class:`~django.db.models.CharField`, for example, requires that you give it a @@ -166,7 +167,8 @@ That small bit of model code gives Django a lot of information. With it, Django is able to: * Create a database schema (``CREATE TABLE`` statements) for this app. -* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects. +* Create a Python database-access API for accessing ``Question`` and ``Choice`` + objects. But first we need to tell our project that the ``polls`` app is installed. @@ -223,8 +225,8 @@ they're designed to be human-editable in case you want to manually tweak how Django changes things. There's a command that will run the migrations for you and manage your database -schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a -moment - but first, let's see what SQL that migration would run. The +schema automatically - that's called :djadmin:`migrate`, and we'll come to it +in a moment - but first, let's see what SQL that migration would run. The :djadmin:`sqlmigrate` command takes migration names and returns their SQL: .. console:: @@ -297,7 +299,8 @@ If you're interested, you can also run :djadmin:`python manage.py check `; this checks for any problems in your project without making migrations or touching the database. -Now, run :djadmin:`migrate` again to create those model tables in your database: +Now, run :djadmin:`migrate` again to create those model tables in your +database: .. console:: @@ -534,8 +537,8 @@ Introducing the Django Admin Django was written in a newsroom environment, with a very clear separation between "content publishers" and the "public" site. Site managers use the - system to add news stories, events, sports scores, etc., and that content is - displayed on the public site. Django solves the problem of creating a + system to add news stories, events, sports scores, etc., and that content + is displayed on the public site. Django solves the problem of creating a unified interface for site administrators to edit content. The admin isn't intended to be used by site visitors. It's for site @@ -597,8 +600,8 @@ given language (if Django has appropriate translations). Enter the admin site -------------------- -Now, try logging in with the superuser account you created in the previous step. -You should see the Django admin index page: +Now, try logging in with the superuser account you created in the previous +step. You should see the Django admin index page: .. image:: _images/admin02.png :alt: Django admin index page @@ -628,15 +631,15 @@ edit it to look like this: Explore the free admin functionality ------------------------------------ -Now that we've registered ``Question``, Django knows that it should be displayed on -the admin index page: +Now that we've registered ``Question``, Django knows that it should be +displayed on the admin index page: .. image:: _images/admin03t.png :alt: Django admin index page, now with polls displayed -Click "Questions". Now you're at the "change list" page for questions. This page -displays all the questions in the database and lets you choose one to change it. -There's the "What's up?" question we created earlier: +Click "Questions". Now you're at the "change list" page for questions. This +page displays all the questions in the database and lets you choose one to +change it. There's the "What's up?" question we created earlier: .. image:: _images/admin04t.png :alt: Polls change list page diff --git a/docs/intro/tutorial03.txt b/docs/intro/tutorial03.txt index be6251f5f2..c7f466dc52 100644 --- a/docs/intro/tutorial03.txt +++ b/docs/intro/tutorial03.txt @@ -2,8 +2,8 @@ Writing your first Django app, part 3 ===================================== -This tutorial begins where :doc:`Tutorial 2 ` left off. We're -continuing the web-poll application and will focus on creating the public +This tutorial begins where :doc:`Tutorial 2 ` left off. +We're continuing the web-poll application and will focus on creating the public interface -- "views." .. admonition:: Where to get help: @@ -51,8 +51,8 @@ the part of the URL after the domain name). Now in your time on the web you may have come across such beauties as ``ME2/Sites/dirmod.htm?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B``. -You will be pleased to know that Django allows us much more elegant -*URL patterns* than that. +You will be pleased to know that Django allows us much more elegant *URL +patterns* than that. A URL pattern is the general form of a URL - for example: ``/newsarchive///``. @@ -135,8 +135,8 @@ Write views that actually do something Each view is responsible for doing one of two things: returning an :class:`~django.http.HttpResponse` object containing the content for the -requested page, or raising an exception such as :exc:`~django.http.Http404`. The -rest is up to you. +requested page, or raising an exception such as :exc:`~django.http.Http404`. +The rest is up to you. Your view can read records from a database, or not. It can use a template system such as Django's -- or a third-party Python template system -- or not. @@ -167,9 +167,9 @@ commas, according to publication date: # Leave the rest of the views (detail, results, vote) unchanged There's a problem here, though: the page's design is hardcoded in the view. If -you want to change the way the page looks, you'll have to edit this Python code. -So let's use Django's template system to separate the design from Python by -creating a template that the view can use. +you want to change the way the page looks, you'll have to edit this Python +code. So let's use Django's template system to separate the design from Python +by creating a template that the view can use. First, create a directory called ``templates`` in your ``polls`` directory. Django will look for templates in there. @@ -268,8 +268,8 @@ rewritten: Note that once we've done this in all these views, we no longer need to import :mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll -want to keep ``HttpResponse`` if you still have the stub methods for ``detail``, -``results``, and ``vote``). +want to keep ``HttpResponse`` if you still have the stub methods for +``detail``, ``results``, and ``vote``). The :func:`~django.shortcuts.render` function takes the request object as its first argument, a template name as its second argument and a dictionary as its @@ -279,8 +279,8 @@ object of the given template rendered with the given context. Raising a 404 error =================== -Now, let's tackle the question detail view -- the page that displays the question text -for a given poll. Here's the view: +Now, let's tackle the question detail view -- the page that displays the +question text for a given poll. Here's the view: .. code-block:: python :caption: ``polls/views.py`` @@ -361,8 +361,8 @@ Use the template system ======================= Back to the ``detail()`` view for our poll application. Given the context -variable ``question``, here's what the ``polls/detail.html`` template might look -like: +variable ``question``, here's what the ``polls/detail.html`` template might +look like: .. code-block:: html+django :caption: ``polls/templates/polls/detail.html`` @@ -375,15 +375,15 @@ like: The template system uses dot-lookup syntax to access variable attributes. In -the example of ``{{ question.question_text }}``, first Django does a dictionary lookup -on the object ``question``. Failing that, it tries an attribute lookup -- which -works, in this case. If attribute lookup had failed, it would've tried a -list-index lookup. +the example of ``{{ question.question_text }}``, first Django does a dictionary +lookup on the object ``question``. Failing that, it tries an attribute lookup +-- which works, in this case. If attribute lookup had failed, it would've tried +a list-index lookup. Method-calling happens in the :ttag:`{% for %}` loop: ``question.choice_set.all`` is interpreted as the Python code -``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is -suitable for use in the :ttag:`{% for %}` tag. +``question.choice_set.all()``, which returns an iterable of ``Choice`` objects +and is suitable for use in the :ttag:`{% for %}` tag. See the :doc:`template guide ` for more about templates. diff --git a/docs/intro/tutorial04.txt b/docs/intro/tutorial04.txt index 149b01f338..4ea5f9294e 100644 --- a/docs/intro/tutorial04.txt +++ b/docs/intro/tutorial04.txt @@ -2,8 +2,8 @@ Writing your first Django app, part 4 ===================================== -This tutorial begins where :doc:`Tutorial 3 ` left off. We're -continuing the web-poll application and will focus on form processing and +This tutorial begins where :doc:`Tutorial 3 ` left off. +We're continuing the web-poll application and will focus on form processing and cutting down our code. .. admonition:: Where to get help: @@ -42,8 +42,8 @@ A quick rundown: POST data ``choice=#`` where # is the ID of the selected choice. This is the basic concept of HTML forms. -* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we - set ``method="post"``. Using ``method="post"`` (as opposed to +* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and + we set ``method="post"``. Using ``method="post"`` (as opposed to ``method="get"``) is very important, because the act of submitting this form will alter data server-side. Whenever you create a form that alters data server-side, use ``method="post"``. This tip isn't specific to @@ -158,8 +158,8 @@ As mentioned in :doc:`Tutorial 3 `, ``request`` is an :class:`~django.http.HttpRequest` objects, see the :doc:`request and response documentation `. -After somebody votes in a question, the ``vote()`` view redirects to the results -page for the question. Let's write that view: +After somebody votes in a question, the ``vote()`` view redirects to the +results page for the question. Let's write that view: .. code-block:: python :caption: ``polls/views.py`` @@ -190,8 +190,8 @@ Now, create a ``polls/results.html`` template: Vote again? -Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a -results page that gets updated each time you vote. If you submit the form +Now, go to ``/polls/1/`` in your browser and vote in the question. You should +see a results page that gets updated each time you vote. If you submit the form without having chosen a choice, you should see the error message. Use generic views: Less code is better @@ -206,12 +206,12 @@ the database according to a parameter passed in the URL, loading a template and returning the rendered template. Because this is so common, Django provides a shortcut, called the "generic views" system. -Generic views abstract common patterns to the point where you don't even need to -write Python code to write an app. For example, the +Generic views abstract common patterns to the point where you don't even need +to write Python code to write an app. For example, the :class:`~django.views.generic.list.ListView` and -:class:`~django.views.generic.detail.DetailView` generic views -abstract the concepts of "display a list of objects" and -"display a detail page for a particular type of object" respectively. +:class:`~django.views.generic.detail.DetailView` generic views abstract the +concepts of "display a list of objects" and "display a detail page for a +particular type of object" respectively. Let's convert our poll app to use the generic views system, so we can delete a bunch of our own code. We'll have to take a few steps to make the conversion. diff --git a/docs/intro/tutorial05.txt b/docs/intro/tutorial05.txt index 80804ac9b2..3bac45b680 100644 --- a/docs/intro/tutorial05.txt +++ b/docs/intro/tutorial05.txt @@ -122,7 +122,8 @@ tests earlier, but it's never too late to get started. Sometimes it's difficult to figure out where to get started with writing tests. If you have written several thousand lines of Python, choosing something to test might not be easy. In such a case, it's fruitful to write your first test -the next time you make a change, either when you add a new feature or fix a bug. +the next time you make a change, either when you add a new feature or fix a +bug. So let's do that right away. @@ -135,9 +136,10 @@ We identify a bug ----------------- Fortunately, there's a little bug in the ``polls`` application for us to fix -right away: the ``Question.was_published_recently()`` method returns ``True`` if -the ``Question`` was published within the last day (which is correct) but also if -the ``Question``’s ``pub_date`` field is in the future (which certainly isn't). +right away: the ``Question.was_published_recently()`` method returns ``True`` +if the ``Question`` was published within the last day (which is correct) but +also if the ``Question``’s ``pub_date`` field is in the future (which certainly +isn't). Confirm the bug by using the :djadmin:`shell` to check the method on a question whose date lies in the future: @@ -191,9 +193,9 @@ Put the following in the ``tests.py`` file in the ``polls`` application: future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) -Here we have created a :class:`django.test.TestCase` subclass with a method that -creates a ``Question`` instance with a ``pub_date`` in the future. We then check -the output of ``was_published_recently()`` - which *ought* to be False. +Here we have created a :class:`django.test.TestCase` subclass with a method +that creates a ``Question`` instance with a ``pub_date`` in the future. We then +check the output of ``was_published_recently()`` - which *ought* to be False. Running tests ------------- @@ -242,8 +244,8 @@ What happened is this: * it looked for test methods - ones whose names begin with ``test`` -* in ``test_was_published_recently_with_future_question`` it created a ``Question`` - instance whose ``pub_date`` field is 30 days in the future +* in ``test_was_published_recently_with_future_question`` it created a + ``Question`` instance whose ``pub_date`` field is 30 days in the future * ... and using the ``assertIs()`` method, it discovered that its ``was_published_recently()`` returns ``True``, though we wanted it to return @@ -255,10 +257,10 @@ occurred. Fixing the bug -------------- -We already know what the problem is: ``Question.was_published_recently()`` should -return ``False`` if its ``pub_date`` is in the future. Amend the method in -``models.py``, so that it will only return ``True`` if the date is also in the -past: +We already know what the problem is: ``Question.was_published_recently()`` +should return ``False`` if its ``pub_date`` is in the future. Amend the method +in ``models.py``, so that it will only return ``True`` if the date is also in +the past: .. code-block:: python :caption: ``polls/models.py`` @@ -292,8 +294,8 @@ More comprehensive tests ------------------------ While we're here, we can further pin down the ``was_published_recently()`` -method; in fact, it would be positively embarrassing if in fixing one bug we had -introduced another. +method; in fact, it would be positively embarrassing if in fixing one bug we +had introduced another. Add two more test methods to the same class, to test the behavior of the method more comprehensively: @@ -320,8 +322,9 @@ more comprehensively: recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) -And now we have three tests that confirm that ``Question.was_published_recently()`` -returns sensible values for past, recent, and future questions. +And now we have three tests that confirm that +``Question.was_published_recently()`` returns sensible values for past, recent, +and future questions. Again, ``polls`` is a minimal application, but however complex it grows in the future and whatever other code it interacts with, we now have some guarantee @@ -644,19 +647,19 @@ code is suffering from test bloat, which brings us to: When testing, more is better ============================ -It might seem that our tests are growing out of control. At this rate there will -soon be more code in our tests than in our application, and the repetition +It might seem that our tests are growing out of control. At this rate there +will soon be more code in our tests than in our application, and the repetition is unaesthetic, compared to the elegant conciseness of the rest of our code. **It doesn't matter**. Let them grow. For the most part, you can write a test once and then forget about it. It will continue performing its useful function as you continue to develop your program. -Sometimes tests will need to be updated. Suppose that we amend our views so that -only ``Question`` entries with associated ``Choice`` instances are published. -In that case, many of our existing tests will fail - *telling us exactly which -tests need to be amended to bring them up to date*, so to that extent tests -help look after themselves. +Sometimes tests will need to be updated. Suppose that we amend our views so +that only ``Question`` entries with associated ``Choice`` instances are +published. In that case, many of our existing tests will fail - *telling us +exactly which tests need to be amended to bring them up to date*, so to that +extent tests help look after themselves. At worst, as you continue developing, you might find that you have some tests that are now redundant. Even that's not a problem; in testing redundancy is diff --git a/docs/intro/tutorial07.txt b/docs/intro/tutorial07.txt index 14752e3285..b7638e365c 100644 --- a/docs/intro/tutorial07.txt +++ b/docs/intro/tutorial07.txt @@ -2,10 +2,10 @@ Writing your first Django app, part 7 ===================================== -This tutorial begins where :doc:`Tutorial 6 ` left off. We're -continuing the web-poll application and will focus on customizing Django's -automatically-generated admin site that we first explored in :doc:`Tutorial 2 -`. +This tutorial begins where :doc:`Tutorial 6 ` left off. +We're continuing the web-poll application and will focus on customizing +Django's automatically-generated admin site that we first explored in +:doc:`Tutorial 2 `. .. admonition:: Where to get help: @@ -71,8 +71,8 @@ up into fieldsets: admin.site.register(Question, QuestionAdmin) The first element of each tuple in -:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset. -Here's what our form looks like now: +:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the +fieldset. Here's what our form looks like now: .. image:: _images/admin08t.png :alt: Form has fieldsets now @@ -104,10 +104,10 @@ looks like this: .. image:: _images/admin09.png :alt: Choice admin page -In that form, the "Question" field is a select box containing every question in the -database. Django knows that a :class:`~django.db.models.ForeignKey` should be -represented in the admin as a ```` box. In our case, only one +question exists at this point. Also note the "Add another question" link next to "Question." Every object with a ``ForeignKey`` relationship to another gets this for free. When you click @@ -116,12 +116,12 @@ If you add a question in that window and click "Save", Django will save the question to the database and dynamically add it as the selected choice on the "Add choice" form you're looking at. -But, really, this is an inefficient way of adding ``Choice`` objects to the system. -It'd be better if you could add a bunch of Choices directly when you create the -``Question`` object. Let's make that happen. +But, really, this is an inefficient way of adding ``Choice`` objects to the +system. It'd be better if you could add a bunch of Choices directly when you +create the ``Question`` object. Let's make that happen. -Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question`` -registration code to read: +Remove the ``register()`` call for the ``Choice`` model. Then, edit the +``Question`` registration code to read: .. code-block:: python :caption: ``polls/admin.py`` @@ -146,8 +146,8 @@ registration code to read: admin.site.register(Question, QuestionAdmin) -This tells Django: "``Choice`` objects are edited on the ``Question`` admin page. By -default, provide enough fields for 3 choices." +This tells Django: "``Choice`` objects are edited on the ``Question`` admin +page. By default, provide enough fields for 3 choices." Load the "Add question" page to see how that looks: @@ -167,8 +167,8 @@ image shows an added slot: :alt: Additional slot added dynamically One small problem, though. It takes a lot of screen space to display all the -fields for entering related ``Choice`` objects. For that reason, Django offers a -tabular way of displaying inline related objects. To use it, change the +fields for entering related ``Choice`` objects. For that reason, Django offers +a tabular way of displaying inline related objects. To use it, change the ``ChoiceInline`` declaration to read: .. code-block:: python @@ -278,10 +278,10 @@ This is shaping up well. Let's add some search capability:: search_fields = ["question_text"] That adds a search box at the top of the change list. When somebody enters -search terms, Django will search the ``question_text`` field. You can use as many -fields as you'd like -- although because it uses a ``LIKE`` query behind the -scenes, limiting the number of search fields to a reasonable number will make -it easier for your database to do the search. +search terms, Django will search the ``question_text`` field. You can use as +many fields as you'd like -- although because it uses a ``LIKE`` query behind +the scenes, limiting the number of search fields to a reasonable number will +make it easier for your database to do the search. Now's also a good time to note that change lists give you free pagination. The default is to display 100 items per page. :attr:`Change list pagination @@ -413,9 +413,9 @@ Customize the admin index page On a similar note, you might want to customize the look and feel of the Django admin index page. -By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been -registered with the admin application, in alphabetical order. You may want to -make significant changes to the layout. After all, the index is probably the +By default, it displays all the apps in :setting:`INSTALLED_APPS` that have +been registered with the admin application, in alphabetical order. You may want +to make significant changes to the layout. After all, the index is probably the most important page of the admin, and it should be easy to use. The template to customize is ``admin/index.html``. (Do the same as with diff --git a/docs/intro/tutorial08.txt b/docs/intro/tutorial08.txt index d0c55c32e4..e837efbf26 100644 --- a/docs/intro/tutorial08.txt +++ b/docs/intro/tutorial08.txt @@ -2,11 +2,11 @@ Writing your first Django app, part 8 ===================================== -This tutorial begins where :doc:`Tutorial 7 ` left off. We've -built our web-poll application and will now look at third-party packages. One of -Django's strengths is the rich ecosystem of third-party packages. They're -community developed packages that can be used to quickly improve the feature set -of an application. +This tutorial begins where :doc:`Tutorial 7 ` left off. +We've built our web-poll application and will now look at third-party packages. +One of Django's strengths is the rich ecosystem of third-party packages. +They're community developed packages that can be used to quickly improve the +feature set of an application. This tutorial will show how to add :pypi:`Django Debug Toolbar `, a commonly used third-party package. The Django Debug @@ -68,7 +68,8 @@ resolve the issue yourself, there are options available to you. `_ that outlines troubleshooting options. #. Search for similar issues on the package's issue tracker. Django Debug - Toolbar’s is `on GitHub `_. + Toolbar’s is `on GitHub + `_. #. Consult the `Django Forum `_. #. Join the `Django Discord server `_. diff --git a/docs/intro/whatsnext.txt b/docs/intro/whatsnext.txt index 22207c217e..23cd8e57fe 100644 --- a/docs/intro/whatsnext.txt +++ b/docs/intro/whatsnext.txt @@ -10,8 +10,8 @@ with this intro (in fact, if you've read every single word, you've read about So what's next? Well, we've always been big fans of learning by doing. At this point you should -know enough to start a project of your own and start fooling around. As you need -to learn new tricks, come back to the documentation. There's also a bigger +know enough to start a project of your own and start fooling around. As you +need to learn new tricks, come back to the documentation. There's also a bigger `Django ecosystem`_ out there for you to explore that the community has created. @@ -100,8 +100,8 @@ reasons: * To add documentation for new features as new features get added, or as Django APIs or behaviors change. -Django's documentation is kept in the same source control system as its code. It -lives in the :source:`docs` directory of our Git repository. Each document +Django's documentation is kept in the same source control system as its code. +It lives in the :source:`docs` directory of our Git repository. Each document online is a separate text file in the repository. Where to get it @@ -115,15 +115,16 @@ On the web The most recent version of the Django documentation lives at https://docs.djangoproject.com/en/dev/. These HTML pages are generated -automatically from the text files in source control. That means they reflect the -"latest and greatest" in Django -- they include the very latest corrections and -additions, and they discuss the latest Django features, which may only be +automatically from the text files in source control. That means they reflect +the "latest and greatest" in Django -- they include the very latest corrections +and additions, and they discuss the latest Django features, which may only be available to users of the Django development version. (See :ref:`differences-between-doc-versions` below.) -We encourage you to help improve the docs by submitting changes, corrections and -suggestions in the `ticket system`_. The Django developers actively monitor the -ticket system and use your feedback to improve the documentation for everybody. +We encourage you to help improve the docs by submitting changes, corrections +and suggestions in the `ticket system`_. The Django developers actively monitor +the ticket system and use your feedback to improve the documentation for +everybody. Note, however, that tickets should explicitly relate to the documentation, rather than asking broad tech-support questions. If you need help with your diff --git a/docs/lint.py b/docs/lint.py index ccd0c7138b..cb129997b2 100644 --- a/docs/lint.py +++ b/docs/lint.py @@ -145,7 +145,7 @@ if __name__ == "__main__": "--disable", "line-too-long", # Disable sphinx-lint version "--max-line-length", - "80", + "79", *params, ] ) diff --git a/docs/misc/design-philosophies.txt b/docs/misc/design-philosophies.txt index af27bf02d7..0b989d760e 100644 --- a/docs/misc/design-philosophies.txt +++ b/docs/misc/design-philosophies.txt @@ -34,9 +34,9 @@ stack are independent of another wherever possible. Less code --------- -Django apps should use as little code as possible; they should lack boilerplate. -Django should take full advantage of Python's dynamic capabilities, such as -introspection. +Django apps should use as little code as possible; they should lack +boilerplate. Django should take full advantage of Python's dynamic +capabilities, such as introspection. .. _quick-development: diff --git a/docs/misc/distributions.txt b/docs/misc/distributions.txt index 64b4f3d88e..fbf0de6344 100644 --- a/docs/misc/distributions.txt +++ b/docs/misc/distributions.txt @@ -3,10 +3,10 @@ Third-party distributions of Django =================================== Many third-party distributors are now providing versions of Django integrated -with their package-management systems. These can make installation and upgrading -much easier for users of Django since the integration includes the ability to -automatically install dependencies (like database adapters) that Django -requires. +with their package-management systems. These can make installation and +upgrading much easier for users of Django since the integration includes the +ability to automatically install dependencies (like database adapters) that +Django requires. Typically, these packages are based on the latest stable release of Django, so if you want to use the development version of Django you'll need to follow the @@ -21,15 +21,14 @@ a list of `Third Party Distributions`_ to help you out. .. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions - For distributors ================ If you'd like to package Django for distribution, we'd be happy to help out! Please introduce yourself on the `Django Forum`_. -We also encourage all distributors to subscribe to the |django-announce| mailing -list, which is a (very) low-traffic list for announcing new releases of Django -and important bugfixes. +We also encourage all distributors to subscribe to the |django-announce| +mailing list, which is a (very) low-traffic list for announcing new releases of +Django and important bugfixes. .. _Django Forum: https://forum.djangoproject.com/ diff --git a/docs/misc/index.txt b/docs/misc/index.txt index 6232a26e37..4ad67a3426 100644 --- a/docs/misc/index.txt +++ b/docs/misc/index.txt @@ -2,8 +2,8 @@ Meta-documentation and miscellany ================================= -Documentation that we can't find a more organized place for. Like that drawer in -your kitchen with the scissors, batteries, duct tape, and other junk. +Documentation that we can't find a more organized place for. Like that drawer +in your kitchen with the scissors, batteries, duct tape, and other junk. .. toctree:: :maxdepth: 2 diff --git a/docs/ref/applications.txt b/docs/ref/applications.txt index 22ea204801..7801e8f438 100644 --- a/docs/ref/applications.txt +++ b/docs/ref/applications.txt @@ -321,12 +321,12 @@ Methods .. note:: - In the usual initialization process, the ``ready`` method is only called - once by Django. But in some corner cases, particularly in tests which - are fiddling with installed applications, ``ready`` might be called more - than once. In that case, either write idempotent methods, or put a flag - on your ``AppConfig`` classes to prevent rerunning code which should - be executed exactly one time. + In the usual initialization process, the ``ready`` method is only + called once by Django. But in some corner cases, particularly in tests + which are fiddling with installed applications, ``ready`` might be + called more than once. In that case, either write idempotent methods, + or put a flag on your ``AppConfig`` classes to prevent rerunning code + which should be executed exactly one time. .. _namespace package: diff --git a/docs/ref/checks.txt b/docs/ref/checks.txt index 51f6c282c6..36e6fe1d85 100644 --- a/docs/ref/checks.txt +++ b/docs/ref/checks.txt @@ -189,11 +189,13 @@ Model fields * **fields.E121**: ``max_length`` must be a positive integer. * **fields.W122**: ``max_length`` is ignored when used with ````. -* **fields.E130**: ``DecimalField``\s must define a ``decimal_places`` attribute. +* **fields.E130**: ``DecimalField``\s must define a ``decimal_places`` + attribute. * **fields.E131**: ``decimal_places`` must be a non-negative integer. * **fields.E132**: ``DecimalField``\s must define a ``max_digits`` attribute. * **fields.E133**: ``max_digits`` must be a positive integer. -* **fields.E134**: ``max_digits`` must be greater or equal to ``decimal_places``. +* **fields.E134**: ``max_digits`` must be greater or equal to + ``decimal_places``. * **fields.E140**: ``FilePathField``\s must have either ``allow_files`` or ``allow_folders`` set to True. * **fields.E150**: ``GenericIPAddressField``\s cannot have ``blank=True`` if @@ -324,7 +326,8 @@ Related fields ````. * **fields.E338**: The intermediary model ```` has no field ````. -* **fields.E339**: ``.`` is not a foreign key to ````. +* **fields.E339**: ``.`` is not a foreign key to + ````. * **fields.E340**: The field's intermediary table ```` clashes with the table name of ````/``.``. * **fields.W340**: ``null`` has no effect on ``ManyToManyField``. @@ -382,7 +385,8 @@ Models * **models.E019**: Autogenerated column name too long for M2M field ````. Maximum length is ```` for database ````. -* **models.E020**: The ``.check()`` class method is currently overridden. +* **models.E020**: The ``.check()`` class method is currently + overridden. * **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used together. * **models.E022**: ```` contains a lazy reference to @@ -442,7 +446,8 @@ Models Management Commands ------------------- -The following checks verify custom management commands are correctly configured: +The following checks verify custom management commands are correctly +configured: * **commands.E001**: The ``migrate`` and ``makemigrations`` commands must have the same ``autodetector``. @@ -489,12 +494,13 @@ The following checks are run if you use the :option:`check --deploy` option: * **security.W005**: You have not set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this, your site is potentially vulnerable to attack via an insecure connection to a - subdomain. Only set this to ``True`` if you are certain that all subdomains of - your domain should be served exclusively via SSL. + subdomain. Only set this to ``True`` if you are certain that all subdomains + of your domain should be served exclusively via SSL. * **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not set to ``True``, so your pages will not be served with an ``'X-Content-Type-Options: nosniff'`` header. You should consider enabling - this header to prevent the browser from identifying content types incorrectly. + this header to prevent the browser from identifying content types + incorrectly. * **security.W007**: Your ``SECURE_BROWSER_XSS_FILTER`` setting is not set to ``True``, so your pages will not be served with an ``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling @@ -504,7 +510,8 @@ The following checks are run if you use the :option:`check --deploy` option: * **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to ``True``. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting to ``True`` or configure - a load balancer or reverse-proxy server to redirect all connections to HTTPS. + a load balancer or reverse-proxy server to redirect all connections to + HTTPS. * **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters, less than 5 unique characters, or it's prefixed with ``'django-insecure-'`` indicating that it was generated automatically by Django. Please generate a @@ -521,18 +528,19 @@ The following checks are run if you use the :option:`check --deploy` option: to ``True``. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions. * **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``. - Using a secure-only session cookie makes it more difficult for network traffic - sniffers to hijack user sessions. + Using a secure-only session cookie makes it more difficult for network + traffic sniffers to hijack user sessions. * **security.W013**: You have :mod:`django.contrib.sessions` in your :setting:`INSTALLED_APPS`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session - cookie makes it more difficult for cross-site scripting attacks to hijack user - sessions. + cookie makes it more difficult for cross-site scripting attacks to hijack + user sessions. * **security.W014**: You have :class:`django.contrib.sessions.middleware.SessionMiddleware` in your - :setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY` - to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for - cross-site scripting attacks to hijack user sessions. + :setting:`MIDDLEWARE`, but you have not set + :setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session + cookie makes it more difficult for cross-site scripting attacks to hijack + user sessions. * **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for cross-site scripting attacks to hijack user sessions. @@ -585,8 +593,8 @@ Signals ------- * **signals.E001**: ```` was connected to the ```` signal with - a lazy reference to the sender ``.``, but app ```` - isn't installed or doesn't provide model ````. + a lazy reference to the sender ``.``, but app + ```` isn't installed or doesn't provide model ````. Templates --------- @@ -871,8 +879,8 @@ The following checks are performed on the default unique. * **auth.E005**: The permission codenamed ```` clashes with a builtin permission for model ````. -* **auth.E006**: The permission codenamed ```` is duplicated for model - ````. +* **auth.E006**: The permission codenamed ```` is duplicated for + model ````. * **auth.E007**: The :attr:`verbose_name ` of model ```` must be at most 244 characters for its builtin permission names diff --git a/docs/ref/class-based-views/base.txt b/docs/ref/class-based-views/base.txt index 9dc939606d..c1b302ea6a 100644 --- a/docs/ref/class-based-views/base.txt +++ b/docs/ref/class-based-views/base.txt @@ -10,8 +10,8 @@ views. Many of Django's built-in class-based views inherit from other class-based views or various mixins. Because this inheritance chain is very important, the -ancestor classes are documented under the section title of **Ancestors (MRO)**. -MRO is an acronym for Method Resolution Order. +ancestor classes are documented under the section title of **Ancestors +(MRO)**. MRO is an acronym for Method Resolution Order. ``View`` ======== @@ -103,9 +103,9 @@ MRO is an acronym for Method Resolution Order. delegate to a method that matches the HTTP method; a ``GET`` will be delegated to ``get()``, a ``POST`` to ``post()``, and so on. - By default, a ``HEAD`` request will be delegated to ``get()``. - If you need to handle ``HEAD`` requests in a different way than ``GET``, - you can override the ``head()`` method. See + By default, a ``HEAD`` request will be delegated to ``get()``. If you + need to handle ``HEAD`` requests in a different way than ``GET``, you + can override the ``head()`` method. See :ref:`supporting-other-http-methods` for an example. .. method:: http_method_not_allowed(request, *args, **kwargs) diff --git a/docs/ref/class-based-views/generic-date-based.txt b/docs/ref/class-based-views/generic-date-based.txt index 7f6bc5630d..8896d018f3 100644 --- a/docs/ref/class-based-views/generic-date-based.txt +++ b/docs/ref/class-based-views/generic-date-based.txt @@ -222,9 +222,9 @@ views for displaying drilldown pages for date-based data. context will be: * ``date_list``: A :meth:`QuerySet ` - object containing all days that have objects available in the given month, - according to ``queryset``, represented as :class:`datetime.datetime` - objects, in ascending order. + object containing all days that have objects available in the given + month, according to ``queryset``, represented as + :class:`datetime.datetime` objects, in ascending order. * ``month``: A :class:`~datetime.date` object representing the given month. diff --git a/docs/ref/class-based-views/mixins-multiple-object.txt b/docs/ref/class-based-views/mixins-multiple-object.txt index 4c6a1c5caa..9c343f8503 100644 --- a/docs/ref/class-based-views/mixins-multiple-object.txt +++ b/docs/ref/class-based-views/mixins-multiple-object.txt @@ -78,8 +78,9 @@ Multiple object mixins .. attribute:: ordering - A string or list of strings specifying the ordering to apply to the ``queryset``. - Valid values are the same as those for :meth:`~django.db.models.query.QuerySet.order_by`. + A string or list of strings specifying the ordering to apply to the + ``queryset``. Valid values are the same as those for + :meth:`~django.db.models.query.QuerySet.order_by`. .. attribute:: paginate_by @@ -106,10 +107,10 @@ Multiple object mixins .. attribute:: paginator_class The paginator class to be used for pagination. By default, - :class:`django.core.paginator.Paginator` is used. If the custom paginator - class doesn't have the same constructor interface as - :class:`django.core.paginator.Paginator`, you will also need to - provide an implementation for :meth:`get_paginator`. + :class:`django.core.paginator.Paginator` is used. If the custom + paginator class doesn't have the same constructor interface as + :class:`django.core.paginator.Paginator`, you will also need to provide + an implementation for :meth:`get_paginator`. .. attribute:: context_object_name @@ -122,8 +123,8 @@ Multiple object mixins .. method:: get_ordering() - Returns a string (or iterable of strings) that defines the ordering that - will be applied to the ``queryset``. + Returns a string (or iterable of strings) that defines the ordering + that will be applied to the ``queryset``. Returns :attr:`ordering` by default. @@ -132,10 +133,10 @@ Multiple object mixins Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``, ``is_paginated``). - Constructed by paginating ``queryset`` into pages of size ``page_size``. - If the request contains a ``page`` argument, either as a captured URL - argument or as a GET argument, ``object_list`` will correspond to the - objects from that page. + Constructed by paginating ``queryset`` into pages of size + ``page_size``. If the request contains a ``page`` argument, either as a + captured URL argument or as a GET argument, ``object_list`` will + correspond to the objects from that page. .. method:: get_paginate_by(queryset) diff --git a/docs/ref/class-based-views/mixins-single-object.txt b/docs/ref/class-based-views/mixins-single-object.txt index d4cbc70fbd..9582098106 100644 --- a/docs/ref/class-based-views/mixins-single-object.txt +++ b/docs/ref/class-based-views/mixins-single-object.txt @@ -102,9 +102,10 @@ Single object mixins Returns context data for displaying the object. - The base implementation of this method requires that the ``self.object`` - attribute be set by the view (even if ``None``). Be sure to do this if - you are using this mixin without one of the built-in views that does so. + The base implementation of this method requires that the + ``self.object`` attribute be set by the view (even if ``None``). Be + sure to do this if you are using this mixin without one of the built-in + views that does so. It returns a dictionary with these contents: diff --git a/docs/ref/class-based-views/mixins.txt b/docs/ref/class-based-views/mixins.txt index 661454f74d..390c8427e1 100644 --- a/docs/ref/class-based-views/mixins.txt +++ b/docs/ref/class-based-views/mixins.txt @@ -2,7 +2,8 @@ Class-based views mixins ======================== -Class-based views API reference. For introductory material, see :doc:`/topics/class-based-views/mixins`. +Class-based views API reference. For introductory material, see +:doc:`/topics/class-based-views/mixins`. .. toctree:: :maxdepth: 1 diff --git a/docs/ref/clickjacking.txt b/docs/ref/clickjacking.txt index 8e98bac5ee..8120dd16e9 100644 --- a/docs/ref/clickjacking.txt +++ b/docs/ref/clickjacking.txt @@ -15,13 +15,14 @@ have loaded in a hidden frame or iframe. An example of clickjacking ========================== -Suppose an online store has a page where a logged-in user can click "Buy Now" to -purchase an item. A user has chosen to stay logged into the store all the time -for convenience. An attacker site might create an "I Like Ponies" button on one -of their own pages, and load the store's page in a transparent iframe such that -the "Buy Now" button is invisibly overlaid on the "I Like Ponies" button. If the -user visits the attacker's site, clicking "I Like Ponies" will cause an -inadvertent click on the "Buy Now" button and an unknowing purchase of the item. +Suppose an online store has a page where a logged-in user can click "Buy Now" +to purchase an item. A user has chosen to stay logged into the store all the +time for convenience. An attacker site might create an "I Like Ponies" button +on one of their own pages, and load the store's page in a transparent iframe +such that the "Buy Now" button is invisibly overlaid on the "I Like Ponies" +button. If the user visits the attacker's site, clicking "I Like Ponies" will +cause an inadvertent click on the "Buy Now" button and an unknowing purchase of +the item. .. _clickjacking-prevention: @@ -93,8 +94,8 @@ that tells the middleware not to set the header:: Setting ``X-Frame-Options`` per view ------------------------------------ -To set the ``X-Frame-Options`` header on a per view basis, Django provides these -decorators:: +To set the ``X-Frame-Options`` header on a per view basis, Django provides +these decorators:: from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_deny diff --git a/docs/ref/contrib/admin/actions.txt b/docs/ref/contrib/admin/actions.txt index 738f64f70b..4b92b7654a 100644 --- a/docs/ref/contrib/admin/actions.txt +++ b/docs/ref/contrib/admin/actions.txt @@ -189,8 +189,8 @@ You can do it like this:: Notice first that we've moved ``make_published`` into a method and renamed the ``modeladmin`` parameter to ``self``, and second that we've now put the string -``'make_published'`` in ``actions`` instead of a direct function reference. This -tells the :class:`ModelAdmin` to look up the action as a method. +``'make_published'`` in ``actions`` instead of a direct function reference. +This tells the :class:`ModelAdmin` to look up the action as a method. Defining actions as methods gives the action more idiomatic access to the :class:`ModelAdmin` itself, allowing the action to call any of the methods @@ -286,10 +286,10 @@ Making actions available site-wide .. method:: AdminSite.add_action(action, name=None) - Some actions are best if they're made available to *any* object in the admin - site -- the export action defined above would be a good candidate. You can - make an action globally available using :meth:`AdminSite.add_action`. For - example:: + Some actions are best if they're made available to *any* object in the + admin site -- the export action defined above would be a good candidate. + You can make an action globally available using + :meth:`AdminSite.add_action`. For example:: from django.contrib import admin @@ -297,8 +297,8 @@ Making actions available site-wide This makes the ``export_selected_objects`` action globally available as an action named "export_selected_objects". You can explicitly give the action - a name -- good if you later want to programmatically :ref:`remove the action - ` -- by passing a second argument to + a name -- good if you later want to programmatically :ref:`remove the + action ` -- by passing a second argument to :meth:`AdminSite.add_action`:: admin.site.add_action(export_selected_objects, "export_selected") @@ -317,11 +317,11 @@ Disabling a site-wide action .. method:: AdminSite.disable_action(name) - If you need to disable a :ref:`site-wide action ` you can - call :meth:`AdminSite.disable_action`. + If you need to disable a :ref:`site-wide action ` you + can call :meth:`AdminSite.disable_action`. - For example, you can use this method to remove the built-in "delete selected - objects" action:: + For example, you can use this method to remove the built-in "delete + selected objects" action:: admin.site.disable_action("delete_selected") @@ -367,8 +367,8 @@ Conditionally enabling or disabling actions Finally, you can conditionally enable or disable actions on a per-request (and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`. - This returns a dictionary of actions allowed. The keys are action names, and - the values are ``(function, name, short_description)`` tuples. + This returns a dictionary of actions allowed. The keys are action names, + and the values are ``(function, name, short_description)`` tuples. For example, if you only want users whose names begin with 'J' to be able to delete objects in bulk:: diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 57183fa483..f8349df3e7 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -127,8 +127,8 @@ The ``register`` decorator pass It's given one or more model classes to register with the ``ModelAdmin``. - If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword - argument:: + If you're using a custom :class:`AdminSite`, pass it using the ``site`` + keyword argument:: from django.contrib import admin from .models import Author, Editor, Reader @@ -174,7 +174,8 @@ application and imports it. application. Such modules are expected to register models with the admin. Typically you won't need to call this function directly as - :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts. + :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django + starts. If you are using a custom ``AdminSite``, it is common to import all of the ``ModelAdmin`` subclasses into your code and register them to the custom @@ -204,13 +205,13 @@ subclass:: .. attribute:: ModelAdmin.actions_on_bottom Controls where on the page the actions bar appears. By default, the admin - changelist displays actions at the top of the page (``actions_on_top = True; - actions_on_bottom = False``). + changelist displays actions at the top of the page (``actions_on_top = + True; actions_on_bottom = False``). .. attribute:: ModelAdmin.actions_selection_counter - Controls whether a selection counter is displayed next to the action dropdown. - By default, the admin changelist will display it + Controls whether a selection counter is displayed next to the action + dropdown. By default, the admin changelist will display it (``actions_selection_counter = True``). .. attribute:: ModelAdmin.date_hierarchy @@ -313,7 +314,8 @@ subclass:: values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as read-only. - For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option. + For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` + option. The ``fields`` option accepts the same types of values as :attr:`~ModelAdmin.list_display`, except that callables and ``__`` lookups @@ -321,8 +323,8 @@ subclass:: will only be used if they're listed in :attr:`~ModelAdmin.readonly_fields`. To display multiple fields on the same line, wrap those fields in their own - tuple. In this example, the ``url`` and ``title`` fields will display on the - same line and the ``content`` field will be displayed below them on its + tuple. In this example, the ``url`` and ``title`` fields will display on + the same line and the ``content`` field will be displayed below them on its own line:: class FlatPageAdmin(admin.ModelAdmin): @@ -334,11 +336,11 @@ subclass:: dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option, as described in the next section. - If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present, - Django will default to displaying each field that isn't an ``AutoField`` and - has ``editable=True``, in a single fieldset, in the same order as the fields - are defined in the model, followed by any fields defined in - :attr:`~ModelAdmin.readonly_fields`. + If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are + present, Django will default to displaying each field that isn't an + ``AutoField`` and has ``editable=True``, in a single fieldset, in the same + order as the fields are defined in the model, followed by any fields + defined in :attr:`~ModelAdmin.readonly_fields`. .. attribute:: ModelAdmin.fieldsets @@ -380,10 +382,10 @@ subclass:: .. image:: _images/fieldsets.png - If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present, - Django will default to displaying each field that isn't an ``AutoField`` and - has ``editable=True``, in a single fieldset, in the same order as the fields - are defined in the model. + If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are + present, Django will default to displaying each field that isn't an + ``AutoField`` and has ``editable=True``, in a single fieldset, in the same + order as the fields are defined in the model. The ``field_options`` dictionary can have the following keys: @@ -489,11 +491,11 @@ subclass:: since the admin has its own way of defining fields, the ``Meta.fields`` attribute will be ignored. - If the ``ModelForm`` is only going to be used for the admin, the easiest - solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin`` - will provide the correct model to use. Alternatively, you can set - ``fields = []`` in the ``Meta`` class to satisfy the validation on the - ``ModelForm``. + If the ``ModelForm`` is only going to be used for the admin, the + easiest solution is to omit the ``Meta.model`` attribute, since + ``ModelAdmin`` will provide the correct model to use. Alternatively, + you can set ``fields = []`` in the ``Meta`` class to satisfy the + validation on the ``ModelForm``. .. admonition:: ``ModelAdmin.exclude`` takes precedence @@ -922,9 +924,9 @@ subclass:: .. attribute:: ModelAdmin.list_max_show_all Set ``list_max_show_all`` to control how many items can appear on a "Show - all" admin change list page. The admin will display a "Show all" link on the - change list only if the total result count is less than or equal to this - setting. By default, this is set to ``200``. + all" admin change list page. The admin will display a "Show all" link on + the change list only if the total result count is less than or equal to + this setting. By default, this is set to ``200``. .. attribute:: ModelAdmin.list_per_page @@ -1080,8 +1082,8 @@ subclass:: You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the ``django.contrib.admin`` module. - Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has - ``choices`` set. + Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or + has ``choices`` set. .. attribute:: ModelAdmin.autocomplete_fields @@ -1270,8 +1272,8 @@ subclass:: WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%') If you don't want to use ``icontains`` as the lookup, you can use any - lookup by appending it the field. For example, you could use :lookup:`exact` - by setting ``search_fields`` to ``['first_name__exact']``. + lookup by appending it the field. For example, you could use + :lookup:`exact` by setting ``search_fields`` to ``['first_name__exact']``. Some (older) shortcuts for specifying a field lookup are also available. You can prefix a field in ``search_fields`` with the following characters @@ -1298,9 +1300,9 @@ subclass:: .. attribute:: ModelAdmin.show_full_result_count Set ``show_full_result_count`` to control whether the full count of objects - should be displayed on a filtered admin page (e.g. ``99 results (103 total)``). - If this option is set to ``False``, a text like ``99 results (Show all)`` - is displayed instead. + should be displayed on a filtered admin page (e.g. ``99 results (103 + total)``). If this option is set to ``False``, a text like ``99 results + (Show all)`` is displayed instead. The default of ``show_full_result_count=True`` generates a query to perform a full count on the table which can be expensive if the table contains a @@ -1323,16 +1325,17 @@ subclass:: .. attribute:: ModelAdmin.view_on_site - Set ``view_on_site`` to control whether or not to display the "View on site" link. - This link should bring you to a URL where you can display the saved object. + Set ``view_on_site`` to control whether or not to display the "View on + site" link. This link should bring you to a URL where you can display the + saved object. This value can be either a boolean flag or a callable. If ``True`` (the default), the object's :meth:`~django.db.models.Model.get_absolute_url` method will be used to generate the url. If your model has a :meth:`~django.db.models.Model.get_absolute_url` method - but you don't want the "View on site" button to appear, you only need to set - ``view_on_site`` to ``False``:: + but you don't want the "View on site" button to appear, you only need to + set ``view_on_site`` to ``False``:: from django.contrib import admin @@ -1473,9 +1476,9 @@ default templates used by the :class:`ModelAdmin` views: readonly.append("age") # Edits the class attribute. return readonly - This results in ``readonly_fields`` becoming - ``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added - each time non-superuser visits the page. + This results in ``readonly_fields`` becoming ``["name", "age", "age", + ...]``, even for a superuser, as ``"age"`` is added each time non-superuser + visits the page. .. method:: ModelAdmin.get_ordering(request) @@ -1494,11 +1497,12 @@ default templates used by the :class:`ModelAdmin` views: The ``get_search_results`` method modifies the list of objects displayed into those that match the provided search term. It accepts the request, a - queryset that applies the current filters, and the user-provided search term. - It returns a tuple containing a queryset modified to implement the search, and - a boolean indicating if the results may contain duplicates. + queryset that applies the current filters, and the user-provided search + term. It returns a tuple containing a queryset modified to implement the + search, and a boolean indicating if the results may contain duplicates. - The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`. + The default implementation searches the fields named in + :attr:`ModelAdmin.search_fields`. This method may be overridden with your own custom search method. For example, you might wish to search by an integer field, or use an external @@ -1528,8 +1532,8 @@ default templates used by the :class:`ModelAdmin` views: This implementation is more efficient than ``search_fields = ('name', '=age')`` which results in a string comparison for the numeric - field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')`` - on PostgreSQL. + field, for example + ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')`` on PostgreSQL. .. _Solr: https://solr.apache.org .. _Haystack: https://haystacksearch.org @@ -1544,8 +1548,8 @@ default templates used by the :class:`ModelAdmin` views: .. method:: ModelAdmin.get_autocomplete_fields(request) - The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is - expected to return a ``list`` or ``tuple`` of field names that will be + The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and + is expected to return a ``list`` or ``tuple`` of field names that will be displayed with an autocomplete widget as described above in the :attr:`ModelAdmin.autocomplete_fields` section. @@ -1560,8 +1564,8 @@ default templates used by the :class:`ModelAdmin` views: The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the ``obj`` being edited (or ``None`` on an add form) and is expected to return - a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields` - section. + a ``dictionary``, as described above in the + :attr:`ModelAdmin.prepopulated_fields` section. .. method:: ModelAdmin.get_list_display(request) @@ -1572,11 +1576,11 @@ default templates used by the :class:`ModelAdmin` views: .. method:: ModelAdmin.get_list_display_links(request, list_display) - The ``get_list_display_links`` method is given the ``HttpRequest`` and - the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`. - It is expected to return either ``None`` or a ``list`` or ``tuple`` of field - names on the changelist that will be linked to the change view, as described - in the :attr:`ModelAdmin.list_display_links` section. + The ``get_list_display_links`` method is given the ``HttpRequest`` and the + ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`. It + is expected to return either ``None`` or a ``list`` or ``tuple`` of field + names on the changelist that will be linked to the change view, as + described in the :attr:`ModelAdmin.list_display_links` section. .. method:: ModelAdmin.get_exclude(request, obj=None) @@ -1595,7 +1599,8 @@ default templates used by the :class:`ModelAdmin` views: The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj`` being edited (or ``None`` on an add form) and is expected to return a list of 2-tuples, in which each 2-tuple represents a ``
`` on the - admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section. + admin form page, as described above in the :attr:`ModelAdmin.fieldsets` + section. .. method:: ModelAdmin.get_list_filter(request) @@ -1611,8 +1616,8 @@ default templates used by the :class:`ModelAdmin` views: .. method:: ModelAdmin.get_search_fields(request) - The ``get_search_fields`` method is given the ``HttpRequest`` and is expected - to return the same kind of sequence type as for the + The ``get_search_fields`` method is given the ``HttpRequest`` and is + expected to return the same kind of sequence type as for the :attr:`~ModelAdmin.search_fields` attribute. .. method:: ModelAdmin.get_sortable_by(request) @@ -1635,9 +1640,10 @@ default templates used by the :class:`ModelAdmin` views: The ``get_inline_instances`` method is given the ``HttpRequest`` and the ``obj`` being edited (or ``None`` on an add form) and is expected to return a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin` - objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin` - section. For example, the following would return inlines without the default - filtering based on add, change, delete, and view permissions:: + objects, as described below in the + :class:`~django.contrib.admin.InlineModelAdmin` section. For example, the + following would return inlines without the default filtering based on add, + change, delete, and view permissions:: class MyModelAdmin(admin.ModelAdmin): inlines = [MyInline] @@ -1862,8 +1868,8 @@ default templates used by the :class:`ModelAdmin` views: ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However, ``ModelAdmin`` ignores this value, overriding it with the :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to - omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the - correct model to use. + omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide + the correct model to use. .. method:: ModelAdmin.get_changelist_formset(request, **kwargs) @@ -1892,13 +1898,13 @@ default templates used by the :class:`ModelAdmin` views: can be manipulated by the user, they must be sanitized to prevent unauthorized data exposure. - The ``lookup_allowed()`` method is given a lookup path from the query string - (e.g. ``'user__email'``), the corresponding value - (e.g. ``'user@example.com'``), and the request, and returns a boolean - indicating whether filtering the changelist's ``QuerySet`` using the - parameters is permitted. If ``lookup_allowed()`` returns ``False``, - ``DisallowedModelAdminLookup`` - (subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised. + The ``lookup_allowed()`` method is given a lookup path from the query + string (e.g. ``'user__email'``), the corresponding value (e.g. + ``'user@example.com'``), and the request, and returns a boolean indicating + whether filtering the changelist's ``QuerySet`` using the parameters is + permitted. If ``lookup_allowed()`` returns ``False``, + ``DisallowedModelAdminLookup`` (subclass of + :exc:`~django.core.exceptions.SuspiciousOperation`) is raised. By default, ``lookup_allowed()`` allows access to a model's local fields, field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from @@ -1911,11 +1917,11 @@ default templates used by the :class:`ModelAdmin` views: .. method:: ModelAdmin.has_view_permission(request, obj=None) - Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise. - If obj is ``None``, should return ``True`` or ``False`` to indicate whether - viewing of objects of this type is permitted in general (e.g., ``False`` - will be interpreted as meaning that the current user is not permitted to - view any object of this type). + Should return ``True`` if viewing ``obj`` is permitted, ``False`` + otherwise. If obj is ``None``, should return ``True`` or ``False`` to + indicate whether viewing of objects of this type is permitted in general + (e.g., ``False`` will be interpreted as meaning that the current user is + not permitted to view any object of this type). The default implementation returns ``True`` if the user has either the "change" or "view" permission. @@ -2067,8 +2073,9 @@ default templates used by the :class:`ModelAdmin` views: :attr:`~django.db.models.Options.verbose_name_plural` to the number of objects that will be deleted. - ``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s - of the models that the user doesn't have permission to delete. + ``perms_needed`` is a set of + :attr:`~django.db.models.Options.verbose_name`\s of the models that the + user doesn't have permission to delete. ``protected`` is a list of strings representing of all the protected related objects that can't be deleted. The list is displayed in the @@ -2676,7 +2683,8 @@ If you want to allow editing and creating an ``Image`` instance on the ``Product``, add/change views you can use :class:`~django.contrib.contenttypes.admin.GenericTabularInline` or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both -subclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`) +subclasses of +:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`) provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular and stacked visual layouts for the forms representing the inline objects, respectively, just like their non-generic counterparts. They behave just like @@ -2735,8 +2743,8 @@ directory, so make sure you name the directory in all lowercase if you are going to run your app on a case-sensitive filesystem. To override an admin template for a specific app, copy and edit the template -from the :source:`django/contrib/admin/templates/admin` directory, and save it to one -of the directories you just created. +from the :source:`django/contrib/admin/templates/admin` directory, and save it +to one of the directories you just created. For example, if we wanted to add a tool to the change list view for all the models in an app named ``my_app``, we would copy @@ -2856,8 +2864,8 @@ The list of CSS variables are defined at :source:`django/contrib/admin/static/admin/css/base.css`. Dark mode variables, respecting the `prefers-color-scheme`_ media query, are -defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This is -linked to the document in ``{% block dark-mode-vars %}``. +defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This +is linked to the document in ``{% block dark-mode-vars %}``. .. _prefers-color-scheme: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme @@ -2949,7 +2957,8 @@ Templates can override or extend base admin templates as described in .. attribute:: AdminSite.app_index_template - Path to a custom template that will be used by the admin site app index view. + Path to a custom template that will be used by the admin site app index + view. .. attribute:: AdminSite.empty_value_display @@ -3019,14 +3028,15 @@ Templates can override or extend base admin templates as described in * ``site_title``: :attr:`AdminSite.site_title` * ``site_url``: :attr:`AdminSite.site_url` * ``has_permission``: :meth:`AdminSite.has_permission` - * ``available_apps``: a list of applications from the :doc:`application registry - ` available for the current user. Each entry in the - list is a dict representing an application with the following keys: + * ``available_apps``: a list of applications from the :doc:`application + registry ` available for the current user. Each entry + in the list is a dict representing an application with the following + keys: * ``app_label``: the application label * ``app_url``: the URL of the application index in the admin - * ``has_module_perms``: a boolean indicating if displaying and accessing of - the module's index page is permitted for the current user + * ``has_module_perms``: a boolean indicating if displaying and accessing + of the module's index page is permitted for the current user * ``models``: a list of the models available in the application Each model is a dict with the following keys: @@ -3102,7 +3112,8 @@ Templates can override or extend base admin templates as described in .. method:: AdminSite.get_model_admin(model) Returns an admin class for the given model class. Raises - ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't registered. + ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't + registered. .. method:: AdminSite.get_log_entries(request) @@ -3357,10 +3368,10 @@ password box. The detailed description of the modification. In the case of an edit, for example, the message contains a list of the edited fields. The Django admin site formats this content as a JSON structure, so that - :meth:`get_change_message` can recompose a message translated in the current - user language. Custom code might set this as a plain string though. You are - advised to use the :meth:`get_change_message` method to retrieve this value - instead of accessing it directly. + :meth:`get_change_message` can recompose a message translated in the + current user language. Custom code might set this as a plain string though. + You are advised to use the :meth:`get_change_message` method to retrieve + this value instead of accessing it directly. ``LogEntry`` methods -------------------- diff --git a/docs/ref/contrib/auth.txt b/docs/ref/contrib/auth.txt index 6f35b9fa98..531c8f4522 100644 --- a/docs/ref/contrib/auth.txt +++ b/docs/ref/contrib/auth.txt @@ -61,7 +61,8 @@ Fields .. attribute:: user_permissions - Many-to-many relationship to :class:`~django.contrib.auth.models.Permission` + Many-to-many relationship to + :class:`~django.contrib.auth.models.Permission` .. attribute:: is_staff @@ -79,8 +80,8 @@ Fields flag but the default backend (:class:`~django.contrib.auth.backends.ModelBackend`) and the :class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can - use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend` - or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` + use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend` or + :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` if you want to allow inactive users to login. In this case, you'll also want to customize the :class:`~django.contrib.auth.forms.AuthenticationForm` used by the @@ -124,9 +125,9 @@ Attributes .. attribute:: is_anonymous Read-only attribute which is always ``False``. This is a way of - differentiating :class:`~models.User` and :class:`~models.AnonymousUser` - objects. Generally, you should prefer using - :attr:`~django.contrib.auth.models.User.is_authenticated` to this + differentiating :class:`~models.User` and + :class:`~models.AnonymousUser` objects. Generally, you should prefer + using :attr:`~django.contrib.auth.models.User.is_authenticated` to this attribute. Methods @@ -246,8 +247,8 @@ Methods Returns ``True`` if the user has the specified permission, where perm is in the format ``"."``. (see - documentation on :ref:`permissions `). If the user is - inactive, this method will always return ``False``. For an active + documentation on :ref:`permissions `). If the user + is inactive, this method will always return ``False``. For an active superuser, this method will always return ``True``. If ``obj`` is passed in, this method won't check for a permission for @@ -330,7 +331,8 @@ Manager methods allow setting arbitrary fields on a :ref:`custom user model `. - See :ref:`Creating users ` for example usage. + See :ref:`Creating users ` for example + usage. .. versionchanged:: 5.2 @@ -523,10 +525,11 @@ can be used for notification when a user logs in or out. The name of the module used for authentication. ``credentials`` - A dictionary of keyword arguments containing the user credentials that were - passed to :func:`~django.contrib.auth.authenticate` or your own custom - authentication backend. Credentials matching a set of 'sensitive' patterns, - (including password) will not be sent in the clear as part of the signal. + A dictionary of keyword arguments containing the user credentials that + were passed to :func:`~django.contrib.auth.authenticate` or your own + custom authentication backend. Credentials matching a set of + 'sensitive' patterns (including password) will not be sent in the clear + as part of the signal. ``request`` The :class:`~django.http.HttpRequest` object, if one was provided to @@ -615,11 +618,11 @@ The following backends are available in :mod:`django.contrib.auth.backends`: :class:`~django.contrib.auth.models.User` and :class:`~django.contrib.auth.models.PermissionsMixin`. - :meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`, - and :meth:`get_group_permissions` allow an object to be passed as a - parameter for object-specific permissions, but this backend does not - implement them other than returning an empty set of permissions if - ``obj is not None``. + :meth:`has_perm`, :meth:`get_all_permissions`, + :meth:`get_user_permissions`, and :meth:`get_group_permissions` allow an + object to be passed as a parameter for object-specific permissions, but + this backend does not implement them other than returning an empty set of + permissions if ``obj is not None``. :meth:`with_perm` also allows an object to be passed as a parameter, but unlike others methods it returns an empty queryset if ``obj is not None``. @@ -678,8 +681,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`: *Asynchronous version*: ``aget_all_permissions()`` - Returns the set of permission strings the ``user_obj`` has, including both - user permissions and group permissions. Returns an empty set if + Returns the set of permission strings the ``user_obj`` has, including + both user permissions and group permissions. Returns an empty set if :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``. @@ -740,7 +743,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`: .. class:: AllowAllUsersModelBackend Same as :class:`ModelBackend` except that it doesn't reject inactive users - because :meth:`~ModelBackend.user_can_authenticate` always returns ``True``. + because :meth:`~ModelBackend.user_can_authenticate` always returns + ``True``. When using this backend, you'll likely want to customize the :class:`~django.contrib.auth.forms.AuthenticationForm` used by the diff --git a/docs/ref/contrib/contenttypes.txt b/docs/ref/contrib/contenttypes.txt index f8232cec1d..2f0b45ff25 100644 --- a/docs/ref/contrib/contenttypes.txt +++ b/docs/ref/contrib/contenttypes.txt @@ -188,8 +188,8 @@ The ``ContentTypeManager`` .. method:: get_for_id(id) - Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID. - Since this method uses the same shared cache as + Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by + ID. Since this method uses the same shared cache as :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`, it's preferred to use this method over the usual ``ContentType.objects.get(pk=id)`` @@ -338,10 +338,11 @@ model: .. admonition:: Serializing references to ``ContentType`` objects If you're serializing data (for example, when generating - :class:`~django.test.TransactionTestCase.fixtures`) from a model that implements - generic relations, you should probably be using a natural key to uniquely - identify related :class:`~django.contrib.contenttypes.models.ContentType` - objects. See :ref:`natural keys` and + :class:`~django.test.TransactionTestCase.fixtures`) from a model that + implements generic relations, you should probably be using a natural key to + uniquely identify related + :class:`~django.contrib.contenttypes.models.ContentType` objects. See + :ref:`natural keys` and :option:`dumpdata --natural-foreign` for more information. This will enable an API similar to the one used for a normal diff --git a/docs/ref/contrib/flatpages.txt b/docs/ref/contrib/flatpages.txt index 6329920de2..33d789be41 100644 --- a/docs/ref/contrib/flatpages.txt +++ b/docs/ref/contrib/flatpages.txt @@ -3,7 +3,8 @@ The flatpages app ================= .. module:: django.contrib.flatpages - :synopsis: A framework for managing simple ?flat? HTML content in a database. + :synopsis: A framework for managing simple ?flat? HTML content in a + database. Django comes with an optional "flatpages" application. It lets you store "flat" HTML content in a database and handles the management for you via Django's diff --git a/docs/ref/contrib/gis/commands.txt b/docs/ref/contrib/gis/commands.txt index fe3cea63f8..4686155a70 100644 --- a/docs/ref/contrib/gis/commands.txt +++ b/docs/ref/contrib/gis/commands.txt @@ -68,7 +68,8 @@ of using ``ogrinspect`` :ref:`in the tutorial `. .. django-admin-option:: --no-imports - Suppresses the ``from django.contrib.gis.db import models`` import statement. + Suppresses the ``from django.contrib.gis.db import models`` import + statement. .. django-admin-option:: --null NULL diff --git a/docs/ref/contrib/gis/db-api.txt b/docs/ref/contrib/gis/db-api.txt index cf26978169..7db103ed73 100644 --- a/docs/ref/contrib/gis/db-api.txt +++ b/docs/ref/contrib/gis/db-api.txt @@ -45,7 +45,8 @@ model): >>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))") >>> z.save() -:class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models: +:class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save +geometric models: .. code-block:: pycon @@ -72,8 +73,8 @@ transform procedure: ... ) # printing the last SQL statement executed (requires DEBUG=True) INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326)) -Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT -(Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in +Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, +WKT (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in hexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the input is not a ``GEOSGeometry`` object, the geometry field will attempt to create a ``GEOSGeometry`` instance from the input. @@ -169,10 +170,10 @@ For example: >>> qs = Zipcode.objects.filter(poly__contains=pnt) >>> qs = Elevation.objects.filter(poly__contains=rst) -In this case, ``poly`` is the geographic field, :lookup:`contains ` -is the spatial lookup type, ``pnt`` is the parameter (which may be a -:class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of -GeoJSON , WKT, or HEXEWKB), and ``rst`` is a +In this case, ``poly`` is the geographic field, +:lookup:`contains ` is the spatial lookup type, ``pnt`` is the +parameter (which may be a :class:`~django.contrib.gis.geos.GEOSGeometry` object +or a string of GeoJSON , WKT, or HEXEWKB), and ``rst`` is a :class:`~django.contrib.gis.gdal.GDALRaster` object. .. _spatial-lookup-raster: @@ -181,9 +182,9 @@ Raster Lookups -------------- The raster lookup syntax is similar to the syntax for geometries. The only -difference is that a band index can be specified as additional input. If no band -index is specified, the first band is used by default (index ``0``). In that -case the syntax is identical to the syntax for geometry lookups. +difference is that a band index can be specified as additional input. If no +band index is specified, the first band is used by default (index ``0``). In +that case the syntax is identical to the syntax for geometry lookups. To specify the band index, an additional parameter can be specified on both sides of the lookup. On the left hand side, the double underscore syntax is @@ -215,10 +216,11 @@ hand side, ``geom`` is a geometry input and ``rst`` is a :class:`~django.contrib.gis.gdal.GDALRaster` object. The band index defaults to ``0`` in the first two queries and is set to ``1`` on the others. -While all spatial lookups can be used with raster objects on both sides, not all -underlying operators natively accept raster input. For cases where the operator -expects geometry input, the raster is automatically converted to a geometry. -It's important to keep this in mind when interpreting the lookup results. +While all spatial lookups can be used with raster objects on both sides, not +all underlying operators natively accept raster input. For cases where the +operator expects geometry input, the raster is automatically converted to a +geometry. It's important to keep this in mind when interpreting the lookup +results. The type of raster support is listed for all lookups in the :ref:`compatibility table `. Lookups involving rasters are currently @@ -261,7 +263,8 @@ The following distance lookups are available: Distance lookups take a tuple parameter comprising: #. A geometry or raster to base calculations from; and -#. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance. +#. A number or :class:`~django.contrib.gis.measure.Distance` object containing + the distance. If a :class:`~django.contrib.gis.measure.Distance` object is used, it may be expressed in any units (the SQL generated will use units @@ -271,16 +274,16 @@ to be in the units of the field. .. note:: In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types - geographic distance queries are performed with. [#fndistsphere15]_ However, - these queries may take a long time, as great-circle distances must be - calculated on the fly for *every* row in the query. This is because the + geographic distance queries are performed with. [#fndistsphere15]_ + However, these queries may take a long time, as great-circle distances must + be calculated on the fly for *every* row in the query. This is because the spatial index on traditional geometry fields cannot be used. For much better performance on WGS84 distance queries, consider using :ref:`geography columns ` in your database instead because they are able to use their spatial index in distance queries. - You can tell GeoDjango to use a geography column by setting ``geography=True`` - in your field definition. + You can tell GeoDjango to use a geography column by setting + ``geography=True`` in your field definition. For example, let's say we have a ``SouthTexasCity`` model (from the :source:`GeoDjango distance tests ` ) on a diff --git a/docs/ref/contrib/gis/feeds.txt b/docs/ref/contrib/gis/feeds.txt index ded9b3d76d..105ebf2cc1 100644 --- a/docs/ref/contrib/gis/feeds.txt +++ b/docs/ref/contrib/gis/feeds.txt @@ -5,10 +5,10 @@ Geographic Feeds .. module:: django.contrib.gis.feeds :synopsis: GeoDjango's framework for generating spatial feeds. -GeoDjango has its own :class:`Feed` subclass that may embed location information -in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or -`W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of -Django's, please consult :doc:`Django's syndication documentation +GeoDjango has its own :class:`Feed` subclass that may embed location +information in RSS/Atom feeds formatted according to either the `Simple +GeoRSS`__ or `W3C Geo`_ standards. Because GeoDjango's syndication API is a +superset of Django's, please consult :doc:`Django's syndication documentation ` for details on general usage. .. _W3C Geo: https://www.w3.org/2003/01/geo/ diff --git a/docs/ref/contrib/gis/forms-api.txt b/docs/ref/contrib/gis/forms-api.txt index 472132cfbc..cece499642 100644 --- a/docs/ref/contrib/gis/forms-api.txt +++ b/docs/ref/contrib/gis/forms-api.txt @@ -5,8 +5,8 @@ GeoDjango Forms API .. module:: django.contrib.gis.forms :synopsis: GeoDjango forms API. -GeoDjango provides some specialized form fields and widgets in order to visually -display and edit geolocalized data on a map. By default, they use +GeoDjango provides some specialized form fields and widgets in order to +visually display and edit geolocalized data on a map. By default, they use `OpenLayers`_-powered maps, with a base WMS layer provided by `NASA`_. .. _OpenLayers: https://openlayers.org/ diff --git a/docs/ref/contrib/gis/functions.txt b/docs/ref/contrib/gis/functions.txt index d65f52d9d8..4fb7bd6d56 100644 --- a/docs/ref/contrib/gis/functions.txt +++ b/docs/ref/contrib/gis/functions.txt @@ -29,7 +29,7 @@ Measurements .. class:: Area(expression, **extra) *Availability*: MariaDB, `MySQL -`_, +`__, Oracle, `PostGIS `__, SpatiaLite Accepts a single geographic field or expression and returns the area of the @@ -48,8 +48,8 @@ geographic SRSes. `PostGIS `__, Oracle, SpatiaLite Accepts two geographic fields or expressions and returns the distance between -them, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a raw -float value is returned when the coordinates are geodetic. +them, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a +raw float value is returned when the coordinates are geodetic. On backends that support distance calculation on geodetic coordinates, the proper backend function is automatically chosen depending on the SRID value of @@ -81,18 +81,19 @@ queryset is calculated: .. note:: Because the ``distance`` attribute is a - :class:`~django.contrib.gis.measure.Distance` object, you can easily express - the value in the units of your choice. For example, ``city.distance.mi`` is - the distance value in miles and ``city.distance.km`` is the distance value - in kilometers. See :doc:`measure` for usage details and the list of - :ref:`supported_units`. + :class:`~django.contrib.gis.measure.Distance` object, you can easily + express the value in the units of your choice. For example, + ``city.distance.mi`` is the distance value in miles and + ``city.distance.km`` is the distance value in kilometers. See + :doc:`measure` for usage details and the list of :ref:`supported_units`. ``GeometryDistance`` -------------------- .. class:: GeometryDistance(expr1, expr2, **extra) -*Availability*: `PostGIS `__ +*Availability*: `PostGIS +`__ Accepts two geographic fields or expressions and returns the distance between them. When used in an :meth:`~django.db.models.query.QuerySet.order_by` clause, @@ -126,8 +127,8 @@ MySQL doesn't support length calculations on geographic SRSes. *Availability*: `PostGIS `__, Oracle, SpatiaLite -Accepts a single geographic field or expression and returns the perimeter of the -geometry field as a :class:`~django.contrib.gis.measure.Distance` object. +Accepts a single geographic field or expression and returns the perimeter of +the geometry field as a :class:`~django.contrib.gis.measure.Distance` object. Relationships ============= @@ -150,8 +151,9 @@ south = ``π``; west = ``3π/2``. .. class:: BoundingCircle(expression, num_seg=48, **extra) -*Availability*: `PostGIS `__, -`Oracle `__, `Oracle +`_, SpatiaLite 5.1+ @@ -205,8 +207,8 @@ representing the bounding box of the geometry. *Availability*: `PostGIS `__, SpatiaLite -Returns a float between 0 and 1 representing the location of the closest point on -``linestring`` to the given ``point``, as a fraction of the 2D line length. +Returns a float between 0 and 1 representing the location of the closest point +on ``linestring`` to the given ``point``, as a fraction of the 2D line length. ``PointOnSurface`` ------------------ @@ -216,8 +218,9 @@ Returns a float between 0 and 1 representing the location of the closest point o *Availability*: `PostGIS `__, MariaDB, Oracle, SpatiaLite -Accepts a single geographic field or expression and returns a ``Point`` geometry -guaranteed to lie on the surface of the field; otherwise returns ``None``. +Accepts a single geographic field or expression and returns a ``Point`` +geometry guaranteed to lie on the surface of the field; otherwise returns +``None``. Operations ========== @@ -334,7 +337,8 @@ parameter. .. class:: Scale(expression, x, y, z=0.0, **extra) -*Availability*: `PostGIS `__, SpatiaLite +*Availability*: `PostGIS `__, +SpatiaLite Accepts a single geographic field or expression and returns a geometry with scaled coordinates by multiplying them with the ``x``, ``y``, and optionally @@ -469,8 +473,8 @@ Keyword Argument Description *Availability*: Oracle, `PostGIS `__, SpatiaLite -Accepts a single geographic field or expression and returns a `Geographic Markup -Language (GML)`__ representation of the geometry. +Accepts a single geographic field or expression and returns a `Geographic +Markup Language (GML)`__ representation of the geometry. Example: @@ -498,7 +502,8 @@ __ https://en.wikipedia.org/wiki/Geography_Markup_Language .. class:: AsKML(expression, precision=8, **extra) -*Availability*: `PostGIS `__, SpatiaLite +*Availability*: `PostGIS `__, +SpatiaLite Accepts a single geographic field or expression and returns a `Keyhole Markup Language (KML)`__ representation of the geometry. @@ -527,7 +532,8 @@ __ https://developers.google.com/kml/documentation/ .. class:: AsSVG(expression, relative=False, precision=8, **extra) -*Availability*: `PostGIS `__, SpatiaLite +*Availability*: `PostGIS `__, +SpatiaLite Accepts a single geographic field or expression and returns a `Scalable Vector Graphics (SVG)`__ representation of the geometry. @@ -668,8 +674,8 @@ Accepts a single geographic field or expression and returns the memory size SpatiaLite Accepts a single geographic field or expression and returns the number of -geometries if the geometry field is a collection (e.g., a ``GEOMETRYCOLLECTION`` -or ``MULTI*`` field). Returns 1 for single geometries. +geometries if the geometry field is a collection (e.g., a +``GEOMETRYCOLLECTION`` or ``MULTI*`` field). Returns 1 for single geometries. On MySQL, returns ``None`` for single geometries. @@ -682,7 +688,7 @@ On MySQL, returns ``None`` for single geometries. `__, `PostGIS `__, Oracle, SpatiaLite -Accepts a single geographic field or expression and returns the number of points -in a geometry. +Accepts a single geographic field or expression and returns the number of +points in a geometry. On MySQL, returns ``None`` for any non-``LINESTRING`` geometry. diff --git a/docs/ref/contrib/gis/gdal.txt b/docs/ref/contrib/gis/gdal.txt index 9d10452305..51511717b1 100644 --- a/docs/ref/contrib/gis/gdal.txt +++ b/docs/ref/contrib/gis/gdal.txt @@ -299,11 +299,11 @@ __ https://gdal.org/drivers/vector/ ``Feature`` wraps an OGR feature. You never create a ``Feature`` object directly. Instead, you retrieve them from a :class:`Layer` object. Each feature consists of a geometry and a set of fields containing additional - properties. The geometry of a field is accessible via its ``geom`` property, - which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a - standard Python container for its fields, which it returns as :class:`Field` - objects: you can access a field directly by its index or name, or you can - iterate over a feature's fields, e.g. in a ``for`` loop. + properties. The geometry of a field is accessible via its ``geom`` + property, which returns an :class:`OGRGeometry` object. A ``Feature`` + behaves like a standard Python container for its fields, which it returns + as :class:`Field` objects: you can access a field directly by its index or + name, or you can iterate over a feature's fields, e.g. in a ``for`` loop. .. attribute:: geom @@ -537,9 +537,9 @@ coordinate transformation: .. method:: __getitem__() Returns the point at the specified index for a :class:`LineString`, the - interior ring at the specified index for a :class:`Polygon`, or the geometry - at the specified index in a :class:`GeometryCollection`. Not applicable to - other geometry types. + interior ring at the specified index for a :class:`Polygon`, or the + geometry at the specified index in a :class:`GeometryCollection`. Not + applicable to other geometry types. .. attribute:: dimension @@ -1273,28 +1273,28 @@ Raster Data Objects ---------------- :class:`GDALRaster` is a wrapper for the GDAL raster source object that -supports reading data from a variety of GDAL-supported geospatial file -formats and data sources using a consistent interface. Each -data source is represented by a :class:`GDALRaster` object which contains -one or more layers of data named bands. Each band, represented by a -:class:`GDALBand` object, contains georeferenced image data. For example, an RGB -image is represented as three bands: one for red, one for green, and one for -blue. +supports reading data from a variety of GDAL-supported geospatial file formats +and data sources using a consistent interface. Each data source is represented +by a :class:`GDALRaster` object which contains one or more layers of data named +bands. Each band, represented by a :class:`GDALBand` object, contains +georeferenced image data. For example, an RGB image is represented as three +bands: one for red, one for green, and one for blue. .. note:: For raster data there is no difference between a raster instance and its - data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are - always a data source. Temporary rasters can be instantiated in memory - using the corresponding driver, but they will be of the same class as file-based - raster sources. + data source. Unlike for the Geometry objects, :class:`GDALRaster` objects + are always a data source. Temporary rasters can be instantiated in memory + using the corresponding driver, but they will be of the same class as + file-based raster sources. .. class:: GDALRaster(ds_input, write=False) The constructor for ``GDALRaster`` accepts two parameters. The first parameter defines the raster source, and the second parameter defines if a - raster should be opened in write mode. For newly-created rasters, the second - parameter is ignored and the new raster is always created in write mode. + raster should be opened in write mode. For newly-created rasters, the + second parameter is ignored and the new raster is always created in write + mode. The first parameter can take three forms: a string or :class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual @@ -1358,8 +1358,8 @@ blue. .. attribute:: name - The name of the source which is equivalent to the input file path or the name - provided upon instantiation. + The name of the source which is equivalent to the input file path or + the name provided upon instantiation. .. code-block:: pycon @@ -1368,11 +1368,12 @@ blue. .. attribute:: driver - The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created - from a file, the driver type is detected automatically. The creation of rasters from - scratch is an in-memory raster by default (``'MEM'``), but can be - altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file. - For a list of file types, see also the `GDAL Raster Formats`__ list. + The name of the GDAL driver used to handle the input file. For + ``GDALRaster``\s created from a file, the driver type is detected + automatically. The creation of rasters from scratch is an in-memory + raster by default (``'MEM'``), but can be altered as needed. For + instance, use ``GTiff`` for a ``GeoTiff`` file. For a list of file + types, see also the `GDAL Raster Formats`__ list. __ https://gdal.org/drivers/raster/ @@ -1572,10 +1573,11 @@ blue. for file-based rasters the warp function will create a new raster on disk. - The only parameter that is set differently from the source raster is the - name. The default value of the raster name is the name of the source - raster appended with ``'_copy' + source_driver_name``. For file-based - rasters it is recommended to provide the file path of the target raster. + The only parameter that is set differently from the source raster is + the name. The default value of the raster name is the name of the + source raster appended with ``'_copy' + source_driver_name``. For + file-based rasters it is recommended to provide the file path of the + target raster. The resampling algorithm used for warping can be specified with the ``resampling`` argument. The default is ``NearestNeighbor``, and the @@ -1714,7 +1716,8 @@ blue. .. attribute:: pixel_count - The total number of pixels in this band. Is equal to ``width * height``. + The total number of pixels in this band. Is equal to ``width * + height``. .. method:: statistics(refresh=False, approximate=False) @@ -1764,8 +1767,8 @@ blue. .. attribute:: nodata_value The "no data" value for a band is generally a special marker value used - to mark pixels that are not valid data. Such pixels should generally not - be displayed, nor contribute to analysis operations. + to mark pixels that are not valid data. Such pixels should generally + not be displayed, nor contribute to analysis operations. To delete an existing "no data" value, set this property to ``None``. @@ -1780,31 +1783,32 @@ blue. The color interpretation for the band, as an integer between 0and 16. If ``as_string`` is ``True``, the data type is returned as a string - with the following possible values: - ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``, - ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``, + with the following possible values: ``GCI_Undefined``, + ``GCI_GrayIndex``, ``GCI_PaletteIndex``, ``GCI_RedBand``, + ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``, ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``, ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``, ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max`` - because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand`` - is returned as a string. + because both correspond to the integer 16, but only + ``GCI_YCbCr_CrBand`` is returned as a string. .. method:: data(data=None, offset=None, size=None, shape=None) - The accessor to the pixel values of the ``GDALBand``. Returns the complete - data array if no parameters are provided. A subset of the pixel array can - be requested by specifying an offset and block size as tuples. + The accessor to the pixel values of the ``GDALBand``. Returns the + complete data array if no parameters are provided. A subset of the + pixel array can be requested by specifying an offset and block size as + tuples. - If NumPy is available, the data is returned as NumPy array. For performance - reasons, it is highly recommended to use NumPy. + If NumPy is available, the data is returned as NumPy array. For + performance reasons, it is highly recommended to use NumPy. - Data is written to the ``GDALBand`` if the ``data`` parameter is provided. - The input can be of one of the following types - packed string, buffer, list, - array, and NumPy array. The number of items in the input should normally - correspond to the total number of pixels in the band, or to the number - of pixels for a specific block of pixel values if the ``offset`` and - ``size`` parameters are provided. + Data is written to the ``GDALBand`` if the ``data`` parameter is + provided. The input can be of one of the following types - packed + string, buffer, list, array, and NumPy array. The number of items in + the input should normally correspond to the total number of pixels in + the band, or to the number of pixels for a specific block of pixel + values if the ``offset`` and ``size`` parameters are provided. If the number of items in the input is different from the target pixel block, the ``shape`` parameter must be specified. The shape is a tuple @@ -1927,8 +1931,8 @@ Key Default Usage .. object:: datatype Integer representing the data type for all the bands. Defaults to ``6`` - (Float32). All bands of a new raster are required to have the same datatype. - The value mapping is: + (Float32). All bands of a new raster are required to have the same + datatype. The value mapping is: ===== =============== =================================== Value GDAL Pixel Type Description diff --git a/docs/ref/contrib/gis/geoquerysets.txt b/docs/ref/contrib/gis/geoquerysets.txt index d31a057863..1725f3bd5c 100644 --- a/docs/ref/contrib/gis/geoquerysets.txt +++ b/docs/ref/contrib/gis/geoquerysets.txt @@ -27,7 +27,8 @@ converted to a geometry where necessary using the `ST_Polygon `_ function. See also the :ref:`introduction to raster lookups `. -The database operators used by the lookups can be divided into three categories: +The database operators used by the lookups can be divided into three +categories: - Native raster support ``N``: the operator accepts rasters natively on both sides of the lookup, and raster input can be mixed with geometry inputs. @@ -65,8 +66,9 @@ Spatial lookups with rasters are only supported for PostGIS backends ``bbcontains`` -------------- -*Availability*: `PostGIS `__, -MariaDB, MySQL, SpatiaLite, PGRaster (Native) +*Availability*: `PostGIS +`__, MariaDB, MySQL, +SpatiaLite, PGRaster (Native) Tests if the geometry or raster field's bounding box completely contains the lookup geometry's bounding box. @@ -113,8 +115,9 @@ SpatiaLite ``MbrOverlaps(poly, geom)`` ``contained`` ------------- -*Availability*: `PostGIS `__, -MariaDB, MySQL, SpatiaLite, PGRaster (Native) +*Availability*: `PostGIS +`__, MariaDB, MySQL, +SpatiaLite, PGRaster (Native) Tests if the geometry field's bounding box is completely contained by the lookup geometry's bounding box. @@ -161,8 +164,8 @@ SpatiaLite ``Contains(poly, geom)`` ``contains_properly`` --------------------- -*Availability*: `PostGIS `__, -PGRaster (Bilateral) +*Availability*: `PostGIS +`__, PGRaster (Bilateral) Returns true if the lookup geometry intersects the interior of the geometry field, but not the boundary (or exterior). @@ -453,9 +456,10 @@ SpatiaLite ``Overlaps(poly, geom)`` *Availability*: `PostGIS `__, MariaDB, Oracle, SpatiaLite, PGRaster (Conversion) -Tests if the geometry field is spatially related to the lookup geometry by -the values given in the given pattern. This lookup requires a tuple parameter, -``(geom, pattern)``; the form of ``pattern`` will depend on the spatial backend: +Tests if the geometry field is spatially related to the lookup geometry by the +values given in the given pattern. This lookup requires a tuple parameter, +``(geom, pattern)``; the form of ``pattern`` will depend on the spatial +backend: MariaDB, PostGIS, and SpatiaLite ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -612,11 +616,11 @@ PostGIS equivalent: ``overlaps_left`` ----------------- -*Availability*: `PostGIS `__, -PGRaster (Bilateral) +*Availability*: `PostGIS +`__, PGRaster (Bilateral) -Tests if the geometry field's bounding box overlaps or is to the left of the lookup -geometry's bounding box. +Tests if the geometry field's bounding box overlaps or is to the left of the +lookup geometry's bounding box. Example:: @@ -634,11 +638,11 @@ PostGIS equivalent: ``overlaps_right`` ------------------ -*Availability*: `PostGIS `__, -PGRaster (Bilateral) +*Availability*: `PostGIS +`__, PGRaster (Bilateral) -Tests if the geometry field's bounding box overlaps or is to the right of the lookup -geometry's bounding box. +Tests if the geometry field's bounding box overlaps or is to the right of the +lookup geometry's bounding box. Example:: @@ -655,8 +659,8 @@ PostGIS equivalent: ``overlaps_above`` ------------------ -*Availability*: `PostGIS `__, -PGRaster (Conversion) +*Availability*: `PostGIS +`__, PGRaster (Conversion) Tests if the geometry field's bounding box overlaps or is above the lookup geometry's bounding box. @@ -676,8 +680,8 @@ PostGIS equivalent: ``overlaps_below`` ------------------ -*Availability*: `PostGIS `__, -PGRaster (Conversion) +*Availability*: `PostGIS +`__, PGRaster (Conversion) Tests if the geometry field's bounding box overlaps or is below the lookup geometry's bounding box. @@ -918,11 +922,11 @@ Example: *Availability*: `PostGIS `__, MariaDB, MySQL, SpatiaLite -Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry -column. This is analogous to a simplified version of the :class:`Union` -aggregate, except it can be several orders of magnitude faster than performing -a union because it rolls up geometries into a collection or multi object, not -caring about dissolving boundaries. +Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the +geometry column. This is analogous to a simplified version of the +:class:`Union` aggregate, except it can be several orders of magnitude faster +than performing a union because it rolls up geometries into a collection or +multi object, not caring about dissolving boundaries. .. versionchanged:: 6.0 @@ -955,8 +959,8 @@ Example: *Availability*: `PostGIS `__ Returns the 3D extent of all ``geo_field`` in the ``QuerySet`` as a 6-tuple, -comprising the lower left coordinate and upper right coordinate (each with x, y, -and z coordinates). +comprising the lower left coordinate and upper right coordinate (each with x, +y, and z coordinates). Example: diff --git a/docs/ref/contrib/gis/geos.txt b/docs/ref/contrib/gis/geos.txt index a17edb6390..d46ce8f41a 100644 --- a/docs/ref/contrib/gis/geos.txt +++ b/docs/ref/contrib/gis/geos.txt @@ -101,10 +101,10 @@ Finally, there is the :func:`fromfile` factory method which returns a You find many ``TypeError`` or ``AttributeError`` exceptions filling your web server's log files. This generally means that you are creating GEOS - objects at the top level of some of your Python modules. Then, due to a race - condition in the garbage collector, your module is garbage collected before - the GEOS object. To prevent this, create :class:`GEOSGeometry` objects - inside the local scope of your functions/methods. + objects at the top level of some of your Python modules. Then, due to a + race condition in the garbage collector, your module is garbage collected + before the GEOS object. To prevent this, create :class:`GEOSGeometry` + objects inside the local scope of your functions/methods. Geometries are Pythonic ----------------------- @@ -439,8 +439,8 @@ return a boolean. .. method:: GEOSGeometry.contains(other) - Returns ``True`` if :meth:`other.within(this) ` returns - ``True``. + Returns ``True`` if :meth:`other.within(this) ` + returns ``True``. .. method:: GEOSGeometry.covers(other) @@ -456,8 +456,8 @@ return a boolean. This predicate is similar to :meth:`GEOSGeometry.contains`, but is more inclusive (i.e. returns ``True`` for more cases). In particular, unlike - :meth:`~GEOSGeometry.contains` it does not distinguish between points in the - boundary and in the interior of geometries. For most situations, + :meth:`~GEOSGeometry.contains` it does not distinguish between points in + the boundary and in the interior of geometries. For most situations, ``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an added benefit, ``covers()`` is more amenable to optimization and hence should outperform :meth:`~GEOSGeometry.contains`. @@ -507,9 +507,9 @@ return a boolean. .. method:: GEOSGeometry.relate_pattern(other, pattern) - Returns ``True`` if the elements in the DE-9IM intersection matrix - for this geometry and the other matches the given ``pattern`` -- - a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}. + Returns ``True`` if the elements in the DE-9IM intersection matrix for this + geometry and the other matches the given ``pattern`` -- a string of nine + characters from the alphabet: {``T``, ``F``, ``*``, ``0``}. .. method:: GEOSGeometry.touches(other) @@ -548,9 +548,9 @@ Topological Methods .. method:: GEOSGeometry.interpolate_normalized(distance) Given a distance (float), returns the point (or closest point) within the - geometry (:class:`LineString` or :class:`MultiLineString`) at that distance. - The normalized version takes the distance as a float between 0 (origin) and - 1 (endpoint). + geometry (:class:`LineString` or :class:`MultiLineString`) at that + distance. The normalized version takes the distance as a float between 0 + (origin) and 1 (endpoint). Reverse of :meth:`GEOSGeometry.project`. @@ -583,10 +583,10 @@ Topological Methods By default, this function does not preserve topology. For example, :class:`Polygon` objects can be split, be collapsed into lines, or - disappear. :class:`Polygon` holes can be created or disappear, and lines may - cross. By specifying ``preserve_topology=True``, the result will have the - same dimension and number of components as the input; this is significantly - slower, however. + disappear. :class:`Polygon` holes can be created or disappear, and lines + may cross. By specifying ``preserve_topology=True``, the result will have + the same dimension and number of components as the input; this is + significantly slower, however. .. method:: GEOSGeometry.sym_difference(other) @@ -633,13 +633,13 @@ Topological Properties The result obeys the following contract: - * Unioning a set of :class:`LineString`\s has the effect of fully noding and - dissolving the linework. + * Unioning a set of :class:`LineString`\s has the effect of fully noding + and dissolving the linework. - * Unioning a set of :class:`Polygon`\s will always return a :class:`Polygon` - or :class:`MultiPolygon` geometry (unlike :meth:`GEOSGeometry.union`, - which may return geometries of lower dimension if a topology collapse - occurs). + * Unioning a set of :class:`Polygon`\s will always return a + :class:`Polygon` or :class:`MultiPolygon` geometry (unlike + :meth:`GEOSGeometry.union`, which may return geometries of lower + dimension if a topology collapse occurs). Other Properties & Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -655,7 +655,8 @@ Other Properties & Methods .. method:: GEOSGeometry.clone() - This method returns a :class:`GEOSGeometry` that is a clone of the original. + This method returns a :class:`GEOSGeometry` that is a clone of the + original. .. method:: GEOSGeometry.distance(geom) @@ -678,8 +679,8 @@ Other Properties & Methods Returns a GEOS ``PreparedGeometry`` for the contents of this geometry. ``PreparedGeometry`` objects are optimized for the contains, intersects, - covers, crosses, disjoint, overlaps, touches and within operations. Refer to - the :ref:`prepared-geometries` documentation for more information. + covers, crosses, disjoint, overlaps, touches and within operations. Refer + to the :ref:`prepared-geometries` documentation for more information. .. attribute:: GEOSGeometry.srs @@ -810,8 +811,8 @@ Other Properties & Methods ``Polygon`` objects may be instantiated by passing in parameters that represent the rings of the polygon. The parameters must either be - :class:`LinearRing` instances, or a sequence that may be used to construct a - :class:`LinearRing`: + :class:`LinearRing` instances, or a sequence that may be used to construct + a :class:`LinearRing`: .. code-block:: pycon @@ -973,7 +974,8 @@ Geometry Factories :param file_h: input file that contains spatial data :type file_h: a Python ``file`` object or a string path to the file - :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file + :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the + file Example: @@ -988,7 +990,8 @@ Geometry Factories :type string: str :param srid: spatial reference identifier :type srid: int - :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string + :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the + string ``fromstr(string, srid)`` is equivalent to :class:`GEOSGeometry(string, srid) `. @@ -1144,8 +1147,8 @@ include the SRID value (in other words, EWKB). .. class:: WKTWriter(dim=2, trim=False, precision=None) This class allows outputting the WKT representation of a geometry. See the - :attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes for - details about the constructor arguments. + :attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes + for details about the constructor arguments. .. method:: WKTWriter.write(geom) diff --git a/docs/ref/contrib/gis/install/geolibs.txt b/docs/ref/contrib/gis/install/geolibs.txt index 2f3f6024bf..027542dfdd 100644 --- a/docs/ref/contrib/gis/install/geolibs.txt +++ b/docs/ref/contrib/gis/install/geolibs.txt @@ -145,10 +145,11 @@ When GeoDjango can't find GEOS, this error is raised: ImportError: Could not find the GEOS library (tried "geos_c"). Try setting GEOS_LIBRARY_PATH in your settings. -The most common solution is to properly configure your :ref:`libsettings` *or* set -:ref:`geoslibrarypath` in your settings. +The most common solution is to properly configure your :ref:`libsettings` *or* +set :ref:`geoslibrarypath` in your settings. -If using a binary package of GEOS (e.g., on Ubuntu), you may need to :ref:`binutils`. +If using a binary package of GEOS (e.g., on Ubuntu), you may need to +:ref:`binutils`. .. _geoslibrarypath: @@ -169,7 +170,8 @@ GEOS C library. For example: The setting must be the *full* path to the **C** shared library; in other words you want to use ``libgeos_c.so``, not ``libgeos.so``. -See also :ref:`My logs are filled with GEOS-related errors `. +See also :ref:`My logs are filled with GEOS-related errors +`. .. _proj4: @@ -192,8 +194,8 @@ PROJ < 7.x) [#]_: $ wget https://download.osgeo.org/proj/proj-data-X.Y.tar.gz -Next, untar the source code archive, and extract the datum shifting files in the -``data`` subdirectory. This must be done *prior* to configuration: +Next, untar the source code archive, and extract the datum shifting files in +the ``data`` subdirectory. This must be done *prior* to configuration: .. code-block:: shell diff --git a/docs/ref/contrib/gis/install/index.txt b/docs/ref/contrib/gis/install/index.txt index f18f4438bb..93e0d8f149 100644 --- a/docs/ref/contrib/gis/install/index.txt +++ b/docs/ref/contrib/gis/install/index.txt @@ -19,11 +19,12 @@ instructions are available for: .. admonition:: Use the Source - Because GeoDjango takes advantage of the latest in the open source geospatial - software technology, recent versions of the libraries are necessary. - If binary packages aren't available for your platform, installation from - source may be required. When compiling the libraries from source, please - follow the directions closely, especially if you're a beginner. + Because GeoDjango takes advantage of the latest in the open source + geospatial software technology, recent versions of the libraries are + necessary. If binary packages aren't available for your platform, + installation from source may be required. When compiling the libraries from + source, please follow the directions closely, especially if you're a + beginner. Requirements ============ @@ -99,7 +100,8 @@ Add ``django.contrib.gis`` to :setting:`INSTALLED_APPS` Like other Django contrib applications, you will *only* need to add :mod:`django.contrib.gis` to :setting:`INSTALLED_APPS` in your settings. This is so that the ``gis`` templates can be located -- if not done, then -features such as the geographic admin or KML sitemaps will not function properly. +features such as the geographic admin or KML sitemaps will not function +properly. Troubleshooting =============== @@ -145,10 +147,11 @@ could place the following in their bash profile: Setting system library path ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include -additional paths from files in another directory, such as ``/etc/ld.so.conf.d``. -As the root user, add the custom library path (like ``/usr/local/lib``) on a -new line in ``ld.so.conf``. This is *one* example of how to do so: +On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which +may include additional paths from files in another directory, such as +``/etc/ld.so.conf.d``. As the root user, add the custom library path (like +``/usr/local/lib``) on a new line in ``ld.so.conf``. This is *one* example of +how to do so: .. code-block:: shell @@ -174,10 +177,11 @@ module) to discover libraries. The ``find_library`` routine uses a program called ``objdump`` (part of the ``binutils`` package) to verify a shared library on GNU/Linux systems. Thus, if ``binutils`` is not installed on your Linux system then Python's ctypes may not be able to find your library even if -your library path is set correctly and geospatial libraries were built perfectly. +your library path is set correctly and geospatial libraries were built +perfectly. -The ``binutils`` package may be installed on Debian and Ubuntu systems using the -following command: +The ``binutils`` package may be installed on Debian and Ubuntu systems using +the following command: .. code-block:: shell @@ -279,9 +283,10 @@ __ https://brew.sh/ Fink ^^^^ -`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users -of the `Fink`__ package system. `Different packages are available`__ (starting -with ``django-gis``), depending on which version of Python you want to use. +`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for +users of the `Fink`__ package system. `Different packages are available`__ +(starting with ``django-gis``), depending on which version of Python you want +to use. __ https://schwehr.blogspot.com/ __ https://www.finkproject.org/ diff --git a/docs/ref/contrib/gis/install/spatialite.txt b/docs/ref/contrib/gis/install/spatialite.txt index dd468fda26..80f86273c7 100644 --- a/docs/ref/contrib/gis/install/spatialite.txt +++ b/docs/ref/contrib/gis/install/spatialite.txt @@ -39,8 +39,8 @@ command line interface and enter the following query: sqlite> CREATE VIRTUAL TABLE testrtree USING rtree(id,minX,maxX,minY,maxY); -If you obtain an error, you will have to recompile SQLite from source. Otherwise, -skip this section. +If you obtain an error, you will have to recompile SQLite from source. +Otherwise, skip this section. To install from sources, download the latest amalgamation source archive from the `SQLite download page`__, and extract: @@ -51,8 +51,9 @@ the `SQLite download page`__, and extract: $ unzip sqlite-amalgamation-XXX0000.zip $ cd sqlite-amalgamation-XXX0000 -Next, run the ``configure`` script -- however the ``CFLAGS`` environment variable -needs to be customized so that SQLite knows to build the R*Tree module: +Next, run the ``configure`` script -- however the ``CFLAGS`` environment +variable needs to be customized so that SQLite knows to build the R*Tree +module: .. code-block:: shell diff --git a/docs/ref/contrib/gis/layermapping.txt b/docs/ref/contrib/gis/layermapping.txt index b1d91119f4..c7d08094fc 100644 --- a/docs/ref/contrib/gis/layermapping.txt +++ b/docs/ref/contrib/gis/layermapping.txt @@ -21,12 +21,12 @@ then inserting into a GeoDjango model. .. warning :: - GIS data sources, like shapefiles, may be very large. If you find - that :class:`LayerMapping` is using too much memory, set - :setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG` - is set to ``True``, Django :ref:`automatically logs ` - *every* SQL query -- and when SQL statements contain geometries, this may - consume more memory than is typical. + GIS data sources, like shapefiles, may be very large. If you find that + :class:`LayerMapping` is using too much memory, set :setting:`DEBUG` to + ``False`` in your settings. When :setting:`DEBUG` is set to ``True``, + Django :ref:`automatically logs ` *every* SQL + query -- and when SQL statements contain geometries, this may consume more + memory than is typical. Example ======= @@ -52,7 +52,8 @@ Example PRIMEM["Greenwich",0], UNIT["Degree",0.017453292519943295]] -#. Now we define our corresponding Django model (make sure to use :djadmin:`migrate`):: +#. Now we define our corresponding Django model (make sure to use + :djadmin:`migrate`):: from django.contrib.gis.db import models diff --git a/docs/ref/contrib/gis/measure.txt b/docs/ref/contrib/gis/measure.txt index 6073b7dc90..d5ae2856f3 100644 --- a/docs/ref/contrib/gis/measure.txt +++ b/docs/ref/contrib/gis/measure.txt @@ -206,6 +206,7 @@ Measurement API Alias for :class:`Area` class. .. rubric:: Footnotes -.. [#] `Robert Coup `_ is the initial author of the measure objects, - and was inspired by Brian Beck's work in `geopy `_ - and Geoff Biggs' PhD work on dimensioned units for robotics. +.. [#] `Robert Coup `_ is the initial author of the + measure objects, and was inspired by Brian Beck's work in `geopy + `_ and Geoff Biggs' PhD work on + dimensioned units for robotics. diff --git a/docs/ref/contrib/gis/model-api.txt b/docs/ref/contrib/gis/model-api.txt index 1b6ec1d543..ef965f76ea 100644 --- a/docs/ref/contrib/gis/model-api.txt +++ b/docs/ref/contrib/gis/model-api.txt @@ -108,9 +108,9 @@ All are optional. .. attribute:: BaseSpatialField.srid -Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry field to -the given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees -of longitude and latitude). +Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry +field to the given value. Defaults to 4326 (also known as `WGS84`__, units are +in degrees of longitude and latitude). __ https://en.wikipedia.org/wiki/WGS84 @@ -121,12 +121,12 @@ Selecting an SRID Choosing an appropriate SRID for your model is an important decision that the developer should consider carefully. The SRID is an integer specifier that -corresponds to the projection system that will be used to interpret the data -in the spatial database. [#fnsrid]_ Projection systems give the context to the +corresponds to the projection system that will be used to interpret the data in +the spatial database. [#fnsrid]_ Projection systems give the context to the coordinates that specify a location. Although the details of `geodesy`__ are beyond the scope of this documentation, the general problem is that the earth -is spherical and representations of the earth (e.g., paper maps, web maps) -are not. +is spherical and representations of the earth (e.g., paper maps, web maps) are +not. Most people are familiar with using latitude and longitude to reference a location on the earth's surface. However, latitude and longitude are angles, @@ -139,7 +139,7 @@ Thus, additional computation is required to obtain distances in planar units (e.g., kilometers and miles). Using a geographic coordinate system may introduce complications for the developer later on. For example, SpatiaLite does not have the capability to perform distance calculations between -geometries using geographic coordinate systems, e.g. constructing a query to +geometries using geographic coordinate systems, e.g. constructing a query to find all points within 5 miles of a county boundary stored as WGS84. [#fndist]_ Portions of the earth's surface may projected onto a two-dimensional, or @@ -263,7 +263,7 @@ geography column to a geometry type in the query:: For more information, the PostGIS documentation contains a helpful section on determining `when to use geography data type over geometry data type -`_. +`__. .. rubric:: Footnotes .. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL `_. diff --git a/docs/ref/contrib/gis/serializers.txt b/docs/ref/contrib/gis/serializers.txt index 2ce2e22c33..9f77da6ace 100644 --- a/docs/ref/contrib/gis/serializers.txt +++ b/docs/ref/contrib/gis/serializers.txt @@ -13,8 +13,8 @@ __ https://geojson.org/ The ``geojson`` serializer is not meant for round-tripping data, as it has no deserializer equivalent. For example, you cannot use :djadmin:`loaddata` to reload the output produced by this serializer. If you plan to reload the -outputted data, use the plain :ref:`json serializer ` -instead. +outputted data, use the plain :ref:`json serializer +` instead. In addition to the options of the ``json`` serializer, the ``geojson`` serializer accepts the following additional option when it is called by @@ -23,7 +23,8 @@ serializer accepts the following additional option when it is called by * ``geometry_field``: A string containing the name of a geometry field to use for the ``geometry`` key of the GeoJSON feature. This is only needed when you have a model with more than one geometry field and you don't want to use the - first defined geometry field (by default, the first geometry field is picked). + first defined geometry field (by default, the first geometry field is + picked). * ``id_field``: A string containing the name of a field to use for the ``id`` key of the GeoJSON feature. By default, the primary key of objects is used. diff --git a/docs/ref/contrib/gis/testing.txt b/docs/ref/contrib/gis/testing.txt index 75da181ee1..be71ae5d71 100644 --- a/docs/ref/contrib/gis/testing.txt +++ b/docs/ref/contrib/gis/testing.txt @@ -15,7 +15,8 @@ Settings .. note:: - The settings below have sensible defaults, and shouldn't require manual setting. + The settings below have sensible defaults, and shouldn't require manual + setting. .. setting:: POSTGIS_VERSION diff --git a/docs/ref/contrib/gis/tutorial.txt b/docs/ref/contrib/gis/tutorial.txt index e417d2d16d..95367b798f 100644 --- a/docs/ref/contrib/gis/tutorial.txt +++ b/docs/ref/contrib/gis/tutorial.txt @@ -6,8 +6,8 @@ Introduction ============ GeoDjango is an included contrib module for Django that turns it into a -world-class geographic web framework. GeoDjango strives to make it as simple -as possible to create geographic web applications, like location-based services. +world-class geographic web framework. GeoDjango strives to make it as simple as +possible to create geographic web applications, like location-based services. Its features include: * Django model fields for `OGC`_ geometries and raster data. @@ -310,8 +310,8 @@ database via GeoDjango models using the :doc:`layermapping`. There are many different ways to import data into a spatial database -- besides the tools included within GeoDjango, you may also use the following: -* `ogr2ogr`_: A command-line utility included with GDAL that - can import many vector data formats into PostGIS, MySQL, and Oracle databases. +* `ogr2ogr`_: A command-line utility included with GDAL that can import many + vector data formats into PostGIS, MySQL, and Oracle databases. * `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into PostGIS. @@ -375,12 +375,12 @@ You can see the layer's geometry type and how many features it contains: .. note:: Unfortunately, the shapefile data format does not allow for greater - specificity with regards to geometry types. This shapefile, like - many others, actually includes ``MultiPolygon`` geometries, not Polygons. - It's important to use a more general field type in models: a - GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a - ``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This - is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``. + specificity with regards to geometry types. This shapefile, like many + others, actually includes ``MultiPolygon`` geometries, not Polygons. It's + important to use a more general field type in models: a GeoDjango + ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a + ``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This is + why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``. The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference system associated with it. If it does, the ``srs`` attribute will return a @@ -412,18 +412,22 @@ units of degrees. In addition, shapefiles also support attribute fields that may contain additional data. Here are the fields on the World Borders layer: +.. code-block:: pycon + >>> print(lyr.fields) ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT'] The following code will let you examine the OGR types (e.g. integer or string) associated with each of the fields: +.. code-block:: pycon + >>> [fld.__name__ for fld in lyr.field_types] ['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger64', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal'] -You can iterate over each feature in the layer and extract information from both -the feature's geometry (accessed via the ``geom`` attribute) as well as the -feature's attribute fields (whose **values** are accessed via ``get()`` +You can iterate over each feature in the layer and extract information from +both the feature's geometry (accessed via the ``geom`` attribute) as well as +the feature's attribute fields (whose **values** are accessed via ``get()`` method): .. code-block:: pycon @@ -769,7 +773,8 @@ application with the following code:: admin.site.register(WorldBorder, admin.ModelAdmin) -Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows:: +Next, edit your ``urls.py`` in the ``geodjango`` application folder as +follows:: from django.contrib import admin from django.urls import include, path diff --git a/docs/ref/contrib/index.txt b/docs/ref/contrib/index.txt index cd78118be8..38079f3402 100644 --- a/docs/ref/contrib/index.txt +++ b/docs/ref/contrib/index.txt @@ -6,9 +6,9 @@ Django aims to follow Python's :ref:`"batteries included" philosophy `. It ships with a variety of extra, optional tools that solve common web development problems. -This code lives in :source:`django/contrib` in the Django distribution. This document -gives a rundown of the packages in ``contrib``, along with any dependencies -those packages have. +This code lives in :source:`django/contrib` in the Django distribution. This +document gives a rundown of the packages in ``contrib``, along with any +dependencies those packages have. .. admonition:: Including ``contrib`` packages in ``INSTALLED_APPS`` diff --git a/docs/ref/contrib/messages.txt b/docs/ref/contrib/messages.txt index 7fdf40f47b..19b0fac04a 100644 --- a/docs/ref/contrib/messages.txt +++ b/docs/ref/contrib/messages.txt @@ -104,19 +104,19 @@ templates. The built-in levels, which can be imported from ``django.contrib.messages`` directly, are: -=========== ======== +=========== ========================================================================================= Constant Purpose -=========== ======== +=========== ========================================================================================= ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment ``INFO`` Informational messages for the user ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully" ``WARNING`` A failure did not occur but may be imminent ``ERROR`` An action was **not** successful or some other failure occurred -=========== ======== +=========== ========================================================================================= -The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level -(or it can be `changed per request`_). Attempts to add messages of a level less -than this will be ignored. +The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded +level (or it can be `changed per request`_). Attempts to add messages of a +level less than this will be ignored. .. _`changed per request`: `Changing the minimum recorded level per-request`_ diff --git a/docs/ref/contrib/postgres/fields.txt b/docs/ref/contrib/postgres/fields.txt index 983b4234c9..8200cee3f1 100644 --- a/docs/ref/contrib/postgres/fields.txt +++ b/docs/ref/contrib/postgres/fields.txt @@ -11,8 +11,8 @@ Indexing these fields ===================== :class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a -B-tree index, which isn't particularly helpful when querying complex data types. -Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and +B-tree index, which isn't particularly helpful when querying complex data +types. Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and :class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though the index choice is dependent on the queries that you're using. Generally, GiST may be a good choice for the :ref:`range fields ` and @@ -450,8 +450,8 @@ operator ``?|``. For example: ``has_keys`` ~~~~~~~~~~~~ -Returns objects where all of the given keys are in the data. Uses the SQL operator -``?&``. For example: +Returns objects where all of the given keys are in the data. Uses the SQL +operator ``?&``. For example: .. code-block:: pycon @@ -741,8 +741,8 @@ passed range. ``not_gt`` ^^^^^^^^^^ -The returned ranges do not contain any points greater than the passed range, that -is the upper bound of the returned range is at most the upper bound of the +The returned ranges do not contain any points greater than the passed range, +that is the upper bound of the returned range is at most the upper bound of the passed range. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10)) diff --git a/docs/ref/contrib/postgres/lookups.txt b/docs/ref/contrib/postgres/lookups.txt index e7ccf1c21b..6dc6618f9a 100644 --- a/docs/ref/contrib/postgres/lookups.txt +++ b/docs/ref/contrib/postgres/lookups.txt @@ -88,7 +88,8 @@ can be chained with other lookup functions. To use it, you need to add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS` and activate the `unaccent extension on PostgreSQL`_. The :class:`~django.contrib.postgres.operations.UnaccentExtension` migration -operation is available if you want to perform this activation using migrations). +operation is available if you want to perform this activation using +migrations). .. _unaccent extension on PostgreSQL: https://www.postgresql.org/docs/current/unaccent.html @@ -105,7 +106,7 @@ The ``unaccent`` lookup can be used on .. warning:: - ``unaccent`` lookups should perform fine in most use cases. However, queries - using this filter will generally perform full table scans, which can be slow - on large tables. In those cases, using dedicated full text indexing tools - might be appropriate. + ``unaccent`` lookups should perform fine in most use cases. However, + queries using this filter will generally perform full table scans, which + can be slow on large tables. In those cases, using dedicated full text + indexing tools might be appropriate. diff --git a/docs/ref/contrib/postgres/search.txt b/docs/ref/contrib/postgres/search.txt index 220ab4c591..4647fcbfa2 100644 --- a/docs/ref/contrib/postgres/search.txt +++ b/docs/ref/contrib/postgres/search.txt @@ -295,8 +295,7 @@ the search vector you wish to use. For example:: name="search_vector_idx", ) -The PostgreSQL documentation has details on -`creating indexes for full text search +The PostgreSQL docs has details on `creating indexes for full text search `_. ``SearchVectorField`` diff --git a/docs/ref/contrib/redirects.txt b/docs/ref/contrib/redirects.txt index c3c082dec8..516c247bb3 100644 --- a/docs/ref/contrib/redirects.txt +++ b/docs/ref/contrib/redirects.txt @@ -16,7 +16,8 @@ To install the redirects app, follow these steps: #. Ensure that the ``django.contrib.sites`` framework :ref:`is installed `. -#. Add ``'django.contrib.redirects'`` to your :setting:`INSTALLED_APPS` setting. +#. Add ``'django.contrib.redirects'`` to your :setting:`INSTALLED_APPS` + setting. #. Add ``'django.contrib.redirects.middleware.RedirectFallbackMiddleware'`` to your :setting:`MIDDLEWARE` setting. #. Run the command :djadmin:`manage.py migrate `. @@ -24,8 +25,8 @@ To install the redirects app, follow these steps: How it works ============ -``manage.py migrate`` creates a ``django_redirect`` table in your database. This -is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields. +``manage.py migrate`` creates a ``django_redirect`` table in your database. +This is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields. The :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware` does all of the work. Each time any Django application raises a 404 @@ -71,10 +72,11 @@ Via the Python API .. class:: models.Redirect - Redirects are represented by a standard :doc:`Django model `, - which lives in :source:`django/contrib/redirects/models.py`. You can access - redirect objects via the :doc:`Django database API `. - For example: + Redirects are represented by a standard + :doc:`Django model `, which lives in + :source:`django/contrib/redirects/models.py`. You can access redirect + objects via the :doc:`Django database API `. For + example: .. code-block:: pycon diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index bb4b66c4f9..1190b3f852 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -61,12 +61,13 @@ To activate sitemap generation on your Django site, add this line to your name="django.contrib.sitemaps.views.sitemap", ) -This tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`. +This tells Django to build a sitemap when a client accesses +:file:`/sitemap.xml`. The name of the sitemap file is not important, but the location is. Search engines will only index links in your sitemap for the current URL level and -below. For instance, if :file:`sitemap.xml` lives in your root directory, it may -reference any URL in your site. However, if your sitemap lives at +below. For instance, if :file:`sitemap.xml` lives in your root directory, it +may reference any URL in your site. However, if your sitemap lives at :file:`/content/sitemap.xml`, it may only reference URLs that begin with :file:`/content/`. @@ -424,8 +425,9 @@ The sitemap framework also has the ability to create a sitemap index that references individual sitemap files, one per each section defined in your ``sitemaps`` dictionary. The only differences in usage are: -* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index` - and :func:`django.contrib.sitemaps.views.sitemap`. +* You use two views in your URLconf: + :func:`django.contrib.sitemaps.views.index` and + :func:`django.contrib.sitemaps.views.sitemap`. * The :func:`django.contrib.sitemaps.views.sitemap` view should take a ``section`` keyword argument. diff --git a/docs/ref/contrib/sites.txt b/docs/ref/contrib/sites.txt index fc279e943b..93ce59f177 100644 --- a/docs/ref/contrib/sites.txt +++ b/docs/ref/contrib/sites.txt @@ -160,7 +160,8 @@ it is not. If you don't have access to the request object, you can use the ``get_current()`` method of the :class:`~django.contrib.sites.models.Site` model's manager. You should then ensure that your settings file does contain -the :setting:`SITE_ID` setting. This example is equivalent to the previous one:: +the :setting:`SITE_ID` setting. This example is equivalent to the previous +one:: from django.contrib.sites.models import Site @@ -291,9 +292,10 @@ Caching the current ``Site`` object =================================== As the current site is stored in the database, each call to -``Site.objects.get_current()`` could result in a database query. But Django is a -little cleverer than that: on the first request, the current site is cached, and -any subsequent call returns the cached data instead of hitting the database. +``Site.objects.get_current()`` could result in a database query. But Django is +a little cleverer than that: on the first request, the current site is cached, +and any subsequent call returns the cached data instead of hitting the +database. If for any reason you want to force a database query, you can tell Django to clear the cache using ``Site.objects.clear_cache()``:: @@ -344,8 +346,9 @@ your model explicitly. For example:: on_site = CurrentSiteManager() With this model, ``Photo.objects.all()`` will return all ``Photo`` objects in -the database, but ``Photo.on_site.all()`` will return only the ``Photo`` objects -associated with the current site, according to the :setting:`SITE_ID` setting. +the database, but ``Photo.on_site.all()`` will return only the ``Photo`` +objects associated with the current site, according to the :setting:`SITE_ID` +setting. Put another way, these two statements are equivalent:: @@ -381,8 +384,9 @@ demonstrates this:: objects = models.Manager() on_site = CurrentSiteManager("publish_on") -If you attempt to use :class:`~django.contrib.sites.managers.CurrentSiteManager` -and pass a field name that doesn't exist, Django will raise a ``ValueError``. +If you attempt to use +:class:`~django.contrib.sites.managers.CurrentSiteManager` and pass a field +name that doesn't exist, Django will raise a ``ValueError``. Finally, note that you'll probably want to keep a normal (non-site-specific) ``Manager`` on your model, even if you use diff --git a/docs/ref/contrib/staticfiles.txt b/docs/ref/contrib/staticfiles.txt index f4b81edf77..2ca9c9a519 100644 --- a/docs/ref/contrib/staticfiles.txt +++ b/docs/ref/contrib/staticfiles.txt @@ -67,12 +67,12 @@ This is used by the default. By default, collected files receive permissions from -:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive permissions -from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would like different -permissions for these files and/or directories, you can subclass either of the -:ref:`static files storage classes ` and specify the -``file_permissions_mode`` and/or ``directory_permissions_mode`` parameters, -respectively. For example:: +:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive +permissions from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would +like different permissions for these files and/or directories, you can subclass +either of the :ref:`static files storage classes ` and +specify the ``file_permissions_mode`` and/or ``directory_permissions_mode`` +parameters, respectively. For example:: from django.contrib.staticfiles import storage @@ -280,10 +280,11 @@ counterparts and update the cache appropriately. .. class:: storage.ManifestStaticFilesStorage -A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage` -storage backend which stores the file names it handles by appending the MD5 -hash of the file's content to the filename. For example, the file -``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``. +A subclass of the +:class:`~django.contrib.staticfiles.storage.StaticFilesStorage` storage backend +which stores the file names it handles by appending the MD5 hash of the file's +content to the filename. For example, the file ``css/styles.css`` would also be +saved as ``css/styles.55e7cbb9ba48.css``. The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or @@ -551,12 +552,13 @@ Specialized test case to support 'live testing' .. class:: testing.StaticLiveServerTestCase -This unittest TestCase subclass extends :class:`django.test.LiveServerTestCase`. +This unittest TestCase subclass extends +:class:`django.test.LiveServerTestCase`. Just like its parent, you can use it to write tests that involve running the -code under test and consuming it with testing tools through HTTP (e.g. Selenium, -PhantomJS, etc.), because of which it's needed that the static assets are also -published. +code under test and consuming it with testing tools through HTTP (e.g. +Selenium, PhantomJS, etc.), because of which it's needed that the static assets +are also published. But given the fact that it makes use of the :func:`django.contrib.staticfiles.views.serve` view described above, it can diff --git a/docs/ref/contrib/syndication.txt b/docs/ref/contrib/syndication.txt index c57a373932..ce2d55a499 100644 --- a/docs/ref/contrib/syndication.txt +++ b/docs/ref/contrib/syndication.txt @@ -106,8 +106,8 @@ Note: See `Publishing Atom and RSS feeds in tandem`_, later, for an example. One thing is left to do. In an RSS feed, each ```` has a ````, -``<link>`` and ``<description>``. We need to tell the framework what data to put -into those elements. +``<link>`` and ``<description>``. We need to tell the framework what data to +put into those elements. * For the contents of ``<title>`` and ``<description>``, Django tries calling the methods ``item_title()`` and ``item_description()`` on @@ -138,10 +138,10 @@ into those elements. .. method:: Feed.get_context_data(**kwargs) - There is also a way to pass additional information to title and description - templates, if you need to supply more than the two variables mentioned - before. You can provide your implementation of ``get_context_data`` method - in your ``Feed`` subclass. For example:: + There is also a way to pass additional information to title and + description templates, if you need to supply more than the two variables + mentioned before. You can provide your implementation of + ``get_context_data`` method in your ``Feed`` subclass. For example:: from mysite.models import Article from django.contrib.syndication.views import Feed @@ -204,11 +204,11 @@ The framework also supports more complex feeds, via arguments. For example, a website could offer an RSS feed of recent crimes for every police beat in a city. It'd be silly to create a separate -:class:`~django.contrib.syndication.views.Feed` class for each police beat; that -would violate the :ref:`DRY principle <dry>` and would couple data to +:class:`~django.contrib.syndication.views.Feed` class for each police beat; +that would violate the :ref:`DRY principle <dry>` and would couple data to programming logic. Instead, the syndication framework lets you access the -arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output -items based on information in the feed's URL. +arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can +output items based on information in the feed's URL. The police beat feeds could be accessible via URLs like this: @@ -311,8 +311,8 @@ Language Feeds created by the syndication framework automatically include the appropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). By -default, this is :func:`django.utils.translation.get_language`. You can change it -by setting the ``language`` class attribute. +default, this is :func:`django.utils.translation.get_language`. You can change +it by setting the ``language`` class attribute. URLs ---- @@ -1033,7 +1033,8 @@ They share this interface: * ``categories`` should be a sequence of strings. :meth:`.SyndicationFeed.write` - Outputs the feed in the given encoding to outfile, which is a file-like object. + Outputs the feed in the given encoding to outfile, which is a file-like + object. :meth:`.SyndicationFeed.writeString` Returns the feed as a string in the given encoding. @@ -1078,8 +1079,8 @@ If the feed format is totally custom, you'll want to subclass However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS_, Apple's `iTunes podcast format`_, etc.), you've got a better choice. These types of feeds typically add extra elements and/or attributes to the underlying format, -and there are a set of methods that ``SyndicationFeed`` calls to get these extra -attributes. Thus, you can subclass the appropriate feed generator class +and there are a set of methods that ``SyndicationFeed`` calls to get these +extra attributes. Thus, you can subclass the appropriate feed generator class (``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are: .. _georss: https://georss.org @@ -1106,10 +1107,11 @@ attributes. Thus, you can subclass the appropriate feed generator class .. warning:: - If you override any of these methods, be sure to call the superclass methods - since they add the required elements for each feed format. + If you override any of these methods, be sure to call the superclass + methods since they add the required elements for each feed format. -For example, you might start implementing an iTunes RSS feed generator like so:: +For example, you might start implementing an iTunes RSS feed generator like +so:: class iTunesFeed(Rss201rev2Feed): def root_attributes(self): diff --git a/docs/ref/csp.txt b/docs/ref/csp.txt index e3666c9129..3ecee17acd 100644 --- a/docs/ref/csp.txt +++ b/docs/ref/csp.txt @@ -46,7 +46,8 @@ The :class:`~django.middleware.csp.ContentSecurityPolicyMiddleware` is configured using the following settings: * :setting:`SECURE_CSP`: defines the **enforced Content Security Policy**. -* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security Policy**. +* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security + Policy**. .. admonition:: These settings can be used independently or together diff --git a/docs/ref/csrf.txt b/docs/ref/csrf.txt index e963c1e627..b245517340 100644 --- a/docs/ref/csrf.txt +++ b/docs/ref/csrf.txt @@ -13,9 +13,9 @@ who visits the malicious site in their browser. A related type of attack, 'login CSRF', where an attacking site tricks a user's browser into logging into a site with someone else's credentials, is also covered. -The first defense against CSRF attacks is to ensure that GET requests (and other -'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect free. -Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be +The first defense against CSRF attacks is to ensure that GET requests (and +other 'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect +free. Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be protected by the steps outlined in :ref:`using-csrf`. .. _Cross Site Request Forgeries: https://owasp.org/www-community/attacks/csrf#overview @@ -120,13 +120,14 @@ vulnerability allows and much worse). Limitations =========== -Subdomains within a site will be able to set cookies on the client for the whole -domain. By setting the cookie and using a corresponding token, subdomains will -be able to circumvent the CSRF protection. The only way to avoid this is to -ensure that subdomains are controlled by trusted users (or, are at least unable -to set cookies). Note that even without CSRF, there are other vulnerabilities, -such as session fixation, that make giving subdomains to untrusted parties a bad -idea, and these vulnerabilities cannot easily be fixed with current browsers. +Subdomains within a site will be able to set cookies on the client for the +whole domain. By setting the cookie and using a corresponding token, subdomains +will be able to circumvent the CSRF protection. The only way to avoid this is +to ensure that subdomains are controlled by trusted users (or, are at least +unable to set cookies). Note that even without CSRF, there are other +vulnerabilities, such as session fixation, that make giving subdomains to +untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed +with current browsers. Utilities ========= diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt index d3df35a106..e54776359e 100644 --- a/docs/ref/databases.txt +++ b/docs/ref/databases.txt @@ -439,10 +439,10 @@ Django supports MySQL 8.0.11 and higher. Django's ``inspectdb`` feature uses the ``information_schema`` database, which contains detailed data on all database schemas. -Django expects the database to support Unicode (UTF-8 encoding) and delegates to -it the task of enforcing transactions and referential integrity. It is important -to be aware of the fact that the two latter ones aren't actually enforced by -MySQL when using the MyISAM storage engine, see the next section. +Django expects the database to support Unicode (UTF-8 encoding) and delegates +to it the task of enforcing transactions and referential integrity. It is +important to be aware of the fact that the two latter ones aren't actually +enforced by MySQL when using the MyISAM storage engine, see the next section. .. _mysql-storage-engines: @@ -691,8 +691,8 @@ storage engine, you have a couple of options. Table names ----------- -There are `known issues`_ in even the latest versions of MySQL that can cause the -case of a table name to be altered when certain SQL statements are executed +There are `known issues`_ in even the latest versions of MySQL that can cause +the case of a table name to be altered when certain SQL statements are executed under certain conditions. It is recommended that you use lowercase table names, if possible, to avoid any problems that might arise from this behavior. Django uses lowercase table names when it auto-generates table names from @@ -710,10 +710,10 @@ Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine If you use the MyISAM storage engine please be aware of the fact that you will receive database-generated errors if you try to use the :ref:`savepoint-related -methods of the transactions API <topics-db-transactions-savepoints>`. The reason -for this is that detecting the storage engine of a MySQL database/table is an -expensive operation so it was decided it isn't worth to dynamically convert -these methods in no-op's based in the results of such detection. +methods of the transactions API <topics-db-transactions-savepoints>`. The +reason for this is that detecting the storage engine of a MySQL database/table +is an expensive operation so it was decided it isn't worth to dynamically +convert these methods in no-op's based in the results of such detection. Notes on specific fields ------------------------ @@ -748,9 +748,9 @@ MySQL can store fractional seconds, provided that the column definition includes a fractional indication (e.g. ``DATETIME(6)``). Django will not upgrade existing columns to include fractional seconds if the -database server supports it. If you want to enable them on an existing database, -it's up to you to either manually update the column on the target database, by -executing a command like: +database server supports it. If you want to enable them on an existing +database, it's up to you to either manually update the column on the target +database, by executing a command like: .. code-block:: sql @@ -762,11 +762,12 @@ or using a :class:`~django.db.migrations.operations.RunSQL` operation in a ``TIMESTAMP`` columns ~~~~~~~~~~~~~~~~~~~~~ -If you are using a legacy database that contains ``TIMESTAMP`` columns, you must -set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption. +If you are using a legacy database that contains ``TIMESTAMP`` columns, you +must set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption. :djadmin:`inspectdb` maps these columns to :class:`~django.db.models.DateTimeField` and if you enable timezone support, -both MySQL and Django will attempt to convert the values from UTC to local time. +both MySQL and Django will attempt to convert the values from UTC to local +time. Row locking with ``QuerySet.select_for_update()`` ------------------------------------------------- @@ -795,9 +796,10 @@ Automatic typecasting can cause unexpected results When performing a query on a string type, but with an integer value, MySQL will coerce the types of all values in the table to an integer before performing the comparison. If your table contains the values ``'abc'``, ``'def'`` and you -query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1`` -will match the value ``'abc1'``. Therefore, string type fields included in Django -will always cast the value to a string before using it in a query. +query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE +mycolumn=1`` will match the value ``'abc1'``. Therefore, string type fields +included in Django will always cast the value to a string before using it in a +query. If you implement custom model fields that inherit from :class:`~django.db.models.Field` directly, are overriding @@ -865,14 +867,13 @@ __ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes SQLite is meant to be a lightweight database, and thus can't support a high level of concurrency. ``OperationalError: database is locked`` errors indicate that your application is experiencing more concurrency than ``sqlite`` can -handle in default configuration. This error means that one thread or process has -an exclusive lock on the database connection and another thread timed out +handle in default configuration. This error means that one thread or process +has an exclusive lock on the database connection and another thread timed out waiting for the lock the be released. -Python's SQLite wrapper has -a default timeout value that determines how long the second thread is allowed to -wait on the lock before it times out and raises the ``OperationalError: database -is locked`` error. +Python's SQLite wrapper has a default timeout value that determines how long +the second thread is allowed to wait on the lock before it times out and raises +the ``OperationalError: database is locked`` error. If you're getting this error, you can solve it by: diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt index 73d3754fc2..a9d4a1b7b4 100644 --- a/docs/ref/django-admin.txt +++ b/docs/ref/django-admin.txt @@ -54,8 +54,8 @@ command and a list of its available options. App names --------- -Many commands take a list of "app names." An "app name" is the basename of -the package containing your models. For example, if your :setting:`INSTALLED_APPS` +Many commands take a list of "app names." An "app name" is the basename of the +package containing your models. For example, if your :setting:`INSTALLED_APPS` contains the string ``'mysite.blog'``, the app name is ``blog``. Determining the version @@ -126,13 +126,14 @@ Lists all available tags. .. django-admin-option:: --deploy -Activates some additional checks that are only relevant in a deployment setting. +Activates some additional checks that are only relevant in a deployment +setting. You can use this option in your local development environment, but since your -local development settings module may not have many of your production settings, -you will probably want to point the ``check`` command at a different settings -module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE` environment -variable, or by passing the ``--settings`` option: +local development settings module may not have many of your production +settings, you will probably want to point the ``check`` command at a different +settings module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE` +environment variable, or by passing the ``--settings`` option: .. console:: @@ -317,8 +318,8 @@ When result of ``dumpdata`` is saved as a file, it can serve as a Note that ``dumpdata`` uses the default manager on the model for selecting the records to dump. If you're using a :ref:`custom manager <custom-managers>` as -the default manager and it filters some of the available records, not all of the -objects will be dumped. +the default manager and it filters some of the available records, not all of +the objects will be dumped. .. django-admin-option:: --all, -a @@ -459,12 +460,12 @@ Django doesn't create database defaults when a Similarly, database defaults aren't translated to model field defaults or detected in any fashion by ``inspectdb``. -By default, ``inspectdb`` creates unmanaged models. That is, ``managed = False`` -in the model's ``Meta`` class tells Django not to manage each table's creation, -modification, and deletion. If you do want to allow Django to manage the -table's lifecycle, you'll need to change the -:attr:`~django.db.models.Options.managed` option to ``True`` (or remove -it because ``True`` is its default value). +By default, ``inspectdb`` creates unmanaged models. That is, ``managed = +False`` in the model's ``Meta`` class tells Django not to manage each table's +creation, modification, and deletion. If you do want to allow Django to manage +the table's lifecycle, you'll need to change the +:attr:`~django.db.models.Options.managed` option to ``True`` (or remove it +because ``True`` is its default value). Database-specific notes ~~~~~~~~~~~~~~~~~~~~~~~ @@ -860,8 +861,8 @@ optimized. .. django-admin:: runserver [addrport] Starts a lightweight development web server on the local machine. By default, -the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an -IP address and port number explicitly. +the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in +an IP address and port number explicitly. If you run this script as a user with normal privileges (recommended), you might not have access to start a port on a low port number. Low port numbers @@ -1234,10 +1235,10 @@ Specifies the database for which to print the SQL. Defaults to ``default``. .. django-admin:: squashmigrations app_label [start_migration_name] migration_name -Squashes the migrations for ``app_label`` up to and including ``migration_name`` -down into fewer migrations, if possible. The resulting squashed migrations -can live alongside the unsquashed ones safely. For more information, -please read :ref:`migration-squashing`. +Squashes the migrations for ``app_label`` up to and including +``migration_name`` down into fewer migrations, if possible. The resulting +squashed migrations can live alongside the unsquashed ones safely. For more +information, please read :ref:`migration-squashing`. When ``start_migration_name`` is given, Django will only include migrations starting from and including this migration. This helps to mitigate the @@ -1633,9 +1634,9 @@ For example, this command: This is useful in a number of ways: -* When you're writing :doc:`unit tests </topics/testing/overview>` of how your views - act with certain fixture data, you can use ``testserver`` to interact with - the views in a web browser, manually. +* When you're writing :doc:`unit tests </topics/testing/overview>` of how your + views act with certain fixture data, you can use ``testserver`` to interact + with the views in a web browser, manually. * Let's say you're developing your Django application and have a "pristine" copy of a database that you'd like to interact with. You can dump your @@ -1758,10 +1759,10 @@ it when running interactively. Specifies the database into which the superuser object will be saved. -You can subclass the management command and override ``get_input_data()`` if you -want to customize data input and validation. Consult the source code for -details on the existing implementation and the method's parameters. For example, -it could be useful if you have a ``ForeignKey`` in +You can subclass the management command and override ``get_input_data()`` if +you want to customize data input and validation. Consult the source code for +details on the existing implementation and the method's parameters. For +example, it could be useful if you have a ``ForeignKey`` in :attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to allow creating an instance instead of entering the primary key of an existing instance. @@ -1831,8 +1832,8 @@ Please refer to its :djadmin:`description <collectstatic>` in the This command is only available if the :doc:`static files application </howto/static-files/index>` (``django.contrib.staticfiles``) is installed. -Please refer to its :djadmin:`description <findstatic>` in the :doc:`staticfiles -</ref/contrib/staticfiles>` documentation. +Please refer to its :djadmin:`description <findstatic>` in the +:doc:`staticfiles </ref/contrib/staticfiles>` documentation. Default options =============== @@ -2085,8 +2086,8 @@ Bash completion --------------- If you use the Bash shell, consider installing the Django bash completion -script, which lives in :source:`extras/django_bash_completion` in the Django source -distribution. It enables tab-completion of ``django-admin`` and +script, which lives in :source:`extras/django_bash_completion` in the Django +source distribution. It enables tab-completion of ``django-admin`` and ``manage.py`` commands, so you can, for instance... * Type ``django-admin``. @@ -2150,7 +2151,8 @@ Examples:: management.call_command(loaddata.Command(), "test_data", verbosity=0) Note that command options that take no arguments are passed as keywords -with ``True`` or ``False``, as you can see with the ``interactive`` option above. +with ``True`` or ``False``, as you can see with the ``interactive`` option +above. Named arguments can be passed by using either one of the following syntaxes:: diff --git a/docs/ref/files/file.txt b/docs/ref/files/file.txt index 23a3814f5d..6fd56c227b 100644 --- a/docs/ref/files/file.txt +++ b/docs/ref/files/file.txt @@ -36,11 +36,11 @@ The ``File`` class Some subclasses of :class:`File`, including :class:`~django.core.files.base.ContentFile` and :class:`~django.db.models.fields.files.FieldFile`, may replace this - attribute with an object other than a Python :py:term:`file object`. - In these cases, this attribute may itself be a :class:`File` - subclass (and not necessarily the same subclass). Whenever - possible, use the attributes and methods of the subclass itself - rather than the those of the subclass's ``file`` attribute. + attribute with an object other than a Python :py:term:`file + object`. In these cases, this attribute may itself be a + :class:`File` subclass (and not necessarily the same subclass). + Whenever possible, use the attributes and methods of the subclass + itself rather than the those of the subclass's ``file`` attribute. .. attribute:: mode diff --git a/docs/ref/files/uploads.txt b/docs/ref/files/uploads.txt index 39456c16f0..dd8ff99689 100644 --- a/docs/ref/files/uploads.txt +++ b/docs/ref/files/uploads.txt @@ -25,8 +25,8 @@ You'll usually use one of these methods to access the uploaded content: .. method:: UploadedFile.multiple_chunks(chunk_size=None) Returns ``True`` if the uploaded file is big enough to require reading in - multiple chunks. By default this will be any file larger than 2.5 megabytes, - but that's configurable; see below. + multiple chunks. By default this will be any file larger than 2.5 + megabytes, but that's configurable; see below. .. method:: UploadedFile.chunks(chunk_size=None) diff --git a/docs/ref/forms/api.txt b/docs/ref/forms/api.txt index ed2bb4d604..bfc32c0d5c 100644 --- a/docs/ref/forms/api.txt +++ b/docs/ref/forms/api.txt @@ -45,10 +45,10 @@ your :class:`Form` class constructor: >>> f = ContactForm(data) In this dictionary, the keys are the field names, which correspond to the -attributes in your :class:`Form` class. The values are the data you're trying to -validate. These will usually be strings, but there's no requirement that they be -strings; the type of data you pass depends on the :class:`Field`, as we'll see -in a moment. +attributes in your :class:`Form` class. The values are the data you're trying +to validate. These will usually be strings, but there's no requirement that +they be strings; the type of data you pass depends on the :class:`Field`, as +we'll see in a moment. .. attribute:: Form.is_bound @@ -90,8 +90,8 @@ validation for fields that are interdependent. See .. method:: Form.is_valid() The primary task of a :class:`Form` object is to validate data. With a bound -:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation -and return a boolean designating whether the data was valid: +:class:`Form` instance, call the :meth:`~Form.is_valid` method to run +validation and return a boolean designating whether the data was valid: .. code-block:: pycon @@ -506,12 +506,12 @@ fields. In this example, the data dictionary doesn't include a value for the >>> f.cleaned_data {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'} -In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an -empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat -empty values as an empty string. Each field type knows what its "blank" value -is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For -full details on each field's behavior in this case, see the "Empty value" note -for each field in the :ref:`built-in-fields` section below. +In this above example, the ``cleaned_data`` value for ``nick_name`` is set to +an empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s +treat empty values as an empty string. Each field type knows what its "blank" +value is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. +For full details on each field's behavior in this case, see the "Empty value" +note for each field in the :ref:`built-in-fields` section below. You can write code to perform validation for particular form fields (based on their name) or for the form as a whole (considering combinations of various @@ -1255,8 +1255,8 @@ Attributes of ``BoundField`` .. attribute:: BoundField.form - The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField` - is bound to. + The :class:`~django.forms.Form` instance this + :class:`~django.forms.BoundField` is bound to. .. attribute:: BoundField.help_text @@ -1264,8 +1264,8 @@ Attributes of ``BoundField`` .. attribute:: BoundField.html_name - The name that will be used in the widget's HTML ``name`` attribute. It takes - the form :attr:`~django.forms.Form.prefix` into account. + The name that will be used in the widget's HTML ``name`` attribute. It + takes the form :attr:`~django.forms.Form.prefix` into account. .. attribute:: BoundField.id_for_label @@ -1380,7 +1380,8 @@ Methods of ``BoundField`` .. method:: BoundField.as_hidden(attrs=None, **kwargs) - Returns a string of HTML for representing this as an ``<input type="hidden">``. + Returns a string of HTML for representing this as an + ``<input type="hidden">``. ``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`. @@ -1484,8 +1485,8 @@ Methods of ``BoundField`` .. method:: BoundField.value() - Use this method to render the raw value of this field as it would be rendered - by a ``Widget``: + Use this method to render the raw value of this field as it would be + rendered by a ``Widget``: .. code-block:: pycon diff --git a/docs/ref/forms/fields.txt b/docs/ref/forms/fields.txt index f0a8e6c341..c786239c25 100644 --- a/docs/ref/forms/fields.txt +++ b/docs/ref/forms/fields.txt @@ -239,7 +239,8 @@ Instead of a constant, you can also pass any callable: >>> print(DateForm()) <div><label for="id_day">Day:</label><input type="text" name="day" value="2023-02-11" required id="id_day"></div> -The callable will be evaluated only when the unbound form is displayed, not when it is defined. +The callable will be evaluated only when the unbound form is displayed, not +when it is defined. ``widget`` ---------- @@ -326,8 +327,8 @@ inside ``aria-describedby``: .. attribute:: Field.error_messages The ``error_messages`` argument lets you override the default messages that the -field will raise. Pass in a dictionary with keys matching the error messages you -want to override. For example, here is the default error message: +field will raise. Pass in a dictionary with keys matching the error messages +you want to override. For example, here is the default error message: .. code-block:: pycon @@ -411,8 +412,8 @@ Checking if the field data has changed .. method:: Field.has_changed() -The ``has_changed()`` method is used to determine if the field value has changed -from the initial value. Returns ``True`` or ``False``. +The ``has_changed()`` method is used to determine if the field value has +changed from the initial value. Returns ``True`` or ``False``. See the :class:`Form.has_changed` documentation for more information. @@ -443,10 +444,10 @@ For each field, we describe the default widget used if you don't specify .. note:: Since all ``Field`` subclasses have ``required=True`` by default, the - validation condition here is important. If you want to include a boolean - in your form that can be either ``True`` or ``False`` (e.g. a checked or - unchecked checkbox), you must remember to pass in ``required=False`` when - creating the ``BooleanField``. + validation condition here is important. If you want to include a + boolean in your form that can be either ``True`` or ``False`` (e.g. a + checked or unchecked checkbox), you must remember to pass in + ``required=False`` when creating the ``BooleanField``. ``CharField`` ------------- @@ -489,8 +490,8 @@ For each field, we describe the default widget used if you don't specify * Validates that the given value exists in the list of choices. * Error message keys: ``required``, ``invalid_choice`` - The ``invalid_choice`` error message may contain ``%(value)s``, which will be - replaced with the selected choice. + The ``invalid_choice`` error message may contain ``%(value)s``, which will + be replaced with the selected choice. Takes one extra argument: @@ -678,8 +679,9 @@ For each field, we describe the default widget used if you don't specify :ref:`bind the file data to the form <binding-uploaded-files>`. The ``max_length`` error refers to the length of the filename. In the error - message for that key, ``%(max)d`` will be replaced with the maximum filename - length and ``%(length)d`` will be replaced with the current filename length. + message for that key, ``%(max)d`` will be replaced with the maximum + filename length and ``%(length)d`` will be replaced with the current + filename length. ``FilePathField`` ----------------- @@ -692,8 +694,8 @@ For each field, we describe the default widget used if you don't specify * Validates that the selected choice exists in the list of choices. * Error message keys: ``required``, ``invalid_choice`` - The field allows choosing from files inside a certain directory. It takes five - extra arguments; only ``path`` is required: + The field allows choosing from files inside a certain directory. It takes + five extra arguments; only ``path`` is required: .. attribute:: path @@ -708,8 +710,8 @@ For each field, we describe the default widget used if you don't specify .. attribute:: match - A regular expression pattern; only files with names matching this expression - will be allowed as choices. + A regular expression pattern; only files with names matching this + expression will be allowed as choices. .. attribute:: allow_files @@ -723,7 +725,6 @@ For each field, we describe the default widget used if you don't specify whether folders in the specified location should be included. Either this or :attr:`allow_files` must be ``True``. - ``FloatField`` -------------- @@ -765,15 +766,16 @@ For each field, we describe the default widget used if you don't specify * Default widget: :class:`TextInput` * Empty value: ``''`` (an empty string) - * Normalizes to: A string. IPv6 addresses are normalized as described below. + * Normalizes to: A string. IPv6 addresses are normalized as described + below. * Validates that the given value is a valid IP address. * Error message keys: ``required``, ``invalid``, ``max_length`` The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2, - including using the IPv4 format suggested in paragraph 3 of that section, like - ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to - ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters - are converted to lowercase. + including using the IPv4 format suggested in paragraph 3 of that section, + like ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be + normalized to ``2001::1``, and ``::ffff:0a0a:0a0a`` to + ``::ffff:10.10.10.10``. All characters are converted to lowercase. Takes three optional arguments: @@ -962,10 +964,11 @@ For each field, we describe the default widget used if you don't specify of choices. * Error message keys: ``required``, ``invalid_choice``, ``invalid_list`` - The ``invalid_choice`` error message may contain ``%(value)s``, which will be - replaced with the selected choice. + The ``invalid_choice`` error message may contain ``%(value)s``, which will + be replaced with the selected choice. - Takes one extra required argument, ``choices``, as for :class:`ChoiceField`. + Takes one extra required argument, ``choices``, as for + :class:`ChoiceField`. ``NullBooleanField`` -------------------- @@ -1074,8 +1077,8 @@ For each field, we describe the default widget used if you don't specify .. class:: TypedChoiceField(**kwargs) - Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two - extra arguments, :attr:`coerce` and :attr:`empty_value`. + Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes + two extra arguments, :attr:`coerce` and :attr:`empty_value`. * Default widget: :class:`Select` * Empty value: Whatever you've given as :attr:`empty_value`. @@ -1089,26 +1092,27 @@ For each field, we describe the default widget used if you don't specify .. attribute:: coerce - A function that takes one argument and returns a coerced value. Examples - include the built-in ``int``, ``float``, ``bool`` and other types. Defaults - to an identity function. Note that coercion happens after input - validation, so it is possible to coerce to a value not present in - ``choices``. + A function that takes one argument and returns a coerced value. + Examples include the built-in ``int``, ``float``, ``bool`` and other + types. Defaults to an identity function. Note that coercion happens + after input validation, so it is possible to coerce to a value not + present in ``choices``. .. attribute:: empty_value The value to use to represent "empty." Defaults to the empty string; - ``None`` is another common choice here. Note that this value will not be - coerced by the function given in the ``coerce`` argument, so choose it - accordingly. + ``None`` is another common choice here. Note that this value will not + be coerced by the function given in the ``coerce`` argument, so choose + it accordingly. ``TypedMultipleChoiceField`` ---------------------------- .. class:: TypedMultipleChoiceField(**kwargs) - Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField` - takes two extra arguments, ``coerce`` and ``empty_value``. + Just like a :class:`MultipleChoiceField`, except + :class:`TypedMultipleChoiceField` takes two extra arguments, ``coerce`` and + ``empty_value``. * Default widget: :class:`SelectMultiple` * Empty value: Whatever you've given as ``empty_value`` @@ -1118,8 +1122,8 @@ For each field, we describe the default widget used if you don't specify coerced. * Error message keys: ``required``, ``invalid_choice`` - The ``invalid_choice`` error message may contain ``%(value)s``, which will be - replaced with the selected choice. + The ``invalid_choice`` error message may contain ``%(value)s``, which will + be replaced with the selected choice. Takes two extra arguments, ``coerce`` and ``empty_value``, as for :class:`TypedChoiceField`. @@ -1178,8 +1182,8 @@ Slightly complex built-in ``Field`` classes .. attribute:: fields - The list of fields that should be used to validate the field's value (in - the order in which they are provided). + The list of fields that should be used to validate the field's value + (in the order in which they are provided). .. code-block:: pycon @@ -1199,7 +1203,8 @@ Slightly complex built-in ``Field`` classes * Default widget: :class:`TextInput` * Empty value: ``''`` (an empty string) - * Normalizes to: the type returned by the ``compress`` method of the subclass. + * Normalizes to: the type returned by the ``compress`` method of the + subclass. * Validates the given value against each of the fields specified as an argument to the ``MultiValueField``. * Error message keys: ``required``, ``invalid``, ``incomplete`` @@ -1307,16 +1312,16 @@ Slightly complex built-in ``Field`` classes A list of formats used to attempt to convert a string to a valid ``datetime.date`` object. - If no ``input_date_formats`` argument is provided, the default input formats - for :class:`DateField` are used. + If no ``input_date_formats`` argument is provided, the default input + formats for :class:`DateField` are used. .. attribute:: input_time_formats A list of formats used to attempt to convert a string to a valid ``datetime.time`` object. - If no ``input_time_formats`` argument is provided, the default input formats - for :class:`TimeField` are used. + If no ``input_time_formats`` argument is provided, the default input + formats for :class:`TimeField` are used. .. _fields-which-handle-relationships: @@ -1378,11 +1383,11 @@ generating choices. See :ref:`iterating-relationship-choices` for details. .. attribute:: empty_label - By default the ``<select>`` widget used by ``ModelChoiceField`` will have an - empty choice at the top of the list. You can change the text of this - label (which is ``"---------"`` by default) with the ``empty_label`` - attribute, or you can disable the empty label entirely by setting - ``empty_label`` to ``None``:: + By default the ``<select>`` widget used by ``ModelChoiceField`` will + have an empty choice at the top of the list. You can change the text of + this label (which is ``"---------"`` by default) with the + ``empty_label`` attribute, or you can disable the empty label entirely + by setting ``empty_label`` to ``None``:: # A custom empty label field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)") diff --git a/docs/ref/forms/models.txt b/docs/ref/forms/models.txt index 459eb48ff2..8abe53833d 100644 --- a/docs/ref/forms/models.txt +++ b/docs/ref/forms/models.txt @@ -29,7 +29,8 @@ Model Form API reference. For introductory material about model forms, see the ``widgets`` is a dictionary of model field names mapped to a widget. - ``localized_fields`` is a list of names of fields which should be localized. + ``localized_fields`` is a list of names of fields which should be + localized. ``labels`` is a dictionary of model field names mapped to a label. @@ -43,11 +44,11 @@ Model Form API reference. For introductory material about model forms, see the See :ref:`modelforms-factory` for example usage. - You must provide the list of fields explicitly, either via keyword arguments - ``fields`` or ``exclude``, or the corresponding attributes on the form's - inner ``Meta`` class. See :ref:`modelforms-selecting-fields` for more - information. Omitting any definition of the fields to use will result in - an :exc:`~django.core.exceptions.ImproperlyConfigured` exception. + You must provide the list of fields explicitly, either via keyword + arguments ``fields`` or ``exclude``, or the corresponding attributes on the + form's inner ``Meta`` class. See :ref:`modelforms-selecting-fields` for + more information. Omitting any definition of the fields to use will result + in an :exc:`~django.core.exceptions.ImproperlyConfigured` exception. ``modelformset_factory`` ======================== diff --git a/docs/ref/forms/validation.txt b/docs/ref/forms/validation.txt index 52206dea2a..5715d15fa7 100644 --- a/docs/ref/forms/validation.txt +++ b/docs/ref/forms/validation.txt @@ -13,8 +13,8 @@ validation (accessing the ``errors`` attribute or calling ``full_clean()`` directly), but normally they won't be needed. In general, any cleaning method can raise ``ValidationError`` if there is a -problem with the data it is processing, passing the relevant information to -the ``ValidationError`` constructor. :ref:`See below <raising-validation-error>` +problem with the data it is processing, passing the relevant information to the +``ValidationError`` constructor. :ref:`See below <raising-validation-error>` for the best practice in raising ``ValidationError``. If no ``ValidationError`` is raised, the method should return the cleaned (normalized) data as a Python object. diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt index 2c277f4587..8c19bf1206 100644 --- a/docs/ref/forms/widgets.txt +++ b/docs/ref/forms/widgets.txt @@ -12,16 +12,17 @@ handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting -``<!DOCTYPE html>``. For example, it uses boolean attributes such as ``checked`` -rather than the XHTML style of ``checked='checked'``. +``<!DOCTYPE html>``. For example, it uses boolean attributes such as +``checked`` rather than the XHTML style of ``checked='checked'``. .. tip:: - Widgets should not be confused with the :doc:`form fields </ref/forms/fields>`. - Form fields deal with the logic of input validation and are used directly - in templates. Widgets deal with rendering of HTML form input elements on - the web page and extraction of raw submitted data. However, widgets do - need to be :ref:`assigned <widget-to-field>` to form fields. + Widgets should not be confused with the :doc:`form fields + </ref/forms/fields>`. Form fields deal with the logic of input validation + and are used directly in templates. Widgets deal with rendering of HTML + form input elements on the web page and extraction of raw submitted data. + However, widgets do need to be :ref:`assigned <widget-to-field>` to form + fields. .. _widget-to-field: @@ -120,7 +121,8 @@ means, for example, that all :class:`TextInput` widgets will appear the same on your web pages. There are two ways to customize widgets: :ref:`per widget instance -<styling-widget-instances>` and :ref:`per widget class <styling-widget-classes>`. +<styling-widget-instances>` and +:ref:`per widget class <styling-widget-classes>`. .. _styling-widget-instances: @@ -175,8 +177,8 @@ You can also modify a widget in the form definition:: name.widget.attrs.update({"class": "special"}) comment.widget.attrs.update(size="40") -Or if the field isn't declared directly on the form (such as model form fields), -you can use the :attr:`Form.fields` attribute:: +Or if the field isn't declared directly on the form (such as model form +fields), you can use the :attr:`Form.fields` attribute:: class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): @@ -279,7 +281,8 @@ foundation for custom widgets. this widget is required. * ``'value'``: The value as returned by :meth:`format_value`. * ``'attrs'``: HTML attributes to be set on the rendered widget. The - combination of the :attr:`attrs` attribute and the ``attrs`` argument. + combination of the :attr:`attrs` attribute and the ``attrs`` + argument. * ``'template_name'``: The value of ``self.template_name``. ``Widget`` subclasses can provide custom context values by overriding @@ -331,8 +334,8 @@ foundation for custom widgets. An attribute to identify if the widget should be grouped in a ``<fieldset>`` with a ``<legend>`` when rendered. Defaults to ``False`` - but is ``True`` when the widget contains multiple ``<input>`` tags such as - :class:`~django.forms.CheckboxSelectMultiple`, + but is ``True`` when the widget contains multiple ``<input>`` tags such + as :class:`~django.forms.CheckboxSelectMultiple`, :class:`~django.forms.RadioSelect`, :class:`~django.forms.MultiWidget`, :class:`~django.forms.SplitDateTimeWidget`, and @@ -507,8 +510,8 @@ Built-in widgets Django provides a representation of all the basic HTML widgets, plus some commonly used groups of widgets in the ``django.forms.widgets`` module, -including :ref:`the input of text <text-widgets>`, :ref:`various checkboxes -and selectors <selector-widgets>`, :ref:`uploading files <file-upload-widgets>`, +including :ref:`the input of text <text-widgets>`, :ref:`various checkboxes and +selectors <selector-widgets>`, :ref:`uploading files <file-upload-widgets>`, and :ref:`handling of multi-valued input <composite-widgets>`. .. _text-widgets: @@ -637,7 +640,8 @@ These widgets make use of the HTML elements ``input`` and ``textarea``. * ``template_name``: ``'django/forms/widgets/date.html'`` * Renders as: ``<input type="text" ...>`` - Takes same arguments as :class:`TextInput`, with one more optional argument: + Takes same arguments as :class:`TextInput`, with one more optional + argument: .. attribute:: DateInput.format @@ -657,7 +661,8 @@ These widgets make use of the HTML elements ``input`` and ``textarea``. * ``template_name``: ``'django/forms/widgets/datetime.html'`` * Renders as: ``<input type="text" ...>`` - Takes same arguments as :class:`TextInput`, with one more optional argument: + Takes same arguments as :class:`TextInput`, with one more optional + argument: .. attribute:: DateTimeInput.format @@ -681,7 +686,8 @@ These widgets make use of the HTML elements ``input`` and ``textarea``. * ``template_name``: ``'django/forms/widgets/time.html'`` * Renders as: ``<input type="text" ...>`` - Takes same arguments as :class:`TextInput`, with one more optional argument: + Takes same arguments as :class:`TextInput`, with one more optional + argument: .. attribute:: TimeInput.format @@ -866,9 +872,9 @@ that specifies the template used to render each choice. For example, for the The outer ``<div>`` container receives the ``id`` attribute of the widget, if defined, or :attr:`BoundField.auto_id` otherwise. - When looping over the radio buttons, the ``label`` and ``input`` tags include - ``for`` and ``id`` attributes, respectively. Each radio button has an - ``id_for_label`` attribute to output the element's ID. + When looping over the radio buttons, the ``label`` and ``input`` tags + include ``for`` and ``id`` attributes, respectively. Each radio button has + an ``id_for_label`` attribute to output the element's ID. ``CheckboxSelectMultiple`` ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1023,10 +1029,10 @@ Composite widgets list (which is ``---`` by default). You can change the text of this label with the ``empty_label`` attribute. ``empty_label`` can be a ``string``, ``list``, or ``tuple``. When a string is used, all select - boxes will each have an empty choice with this label. If ``empty_label`` - is a ``list`` or ``tuple`` of 3 string elements, the select boxes will - have their own custom label. The labels should be in this order - ``('year_label', 'month_label', 'day_label')``. + boxes will each have an empty choice with this label. If + ``empty_label`` is a ``list`` or ``tuple`` of 3 string elements, the + select boxes will have their own custom label. The labels should be in + this order ``('year_label', 'month_label', 'day_label')``. .. code-block:: python diff --git a/docs/ref/logging.txt b/docs/ref/logging.txt index d10da840bc..756ac6d8f9 100644 --- a/docs/ref/logging.txt +++ b/docs/ref/logging.txt @@ -164,7 +164,8 @@ Messages to this logger have the following extra context: * ``status_code``: The HTTP response code associated with the request. -* ``request``: The request object (a :py:class:`socket.socket`) that generated the logging message. +* ``request``: The request object (a :py:class:`socket.socket`) that generated + the logging message. .. _django-template-logger: @@ -290,8 +291,8 @@ Other ``django.security`` loggers not based on ``SuspiciousOperation`` are: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Logs the SQL queries that are executed during schema changes to the database by -the :doc:`migrations framework </topics/migrations>`. Note that it won't log the -queries executed by :class:`~django.db.migrations.operations.RunPython`. +the :doc:`migrations framework </topics/migrations>`. Note that it won't log +the queries executed by :class:`~django.db.migrations.operations.RunPython`. Messages to this logger have ``params`` and ``sql`` in their extra context (but unlike ``django.db.backends``, not duration). The values have the same meaning as explained in :ref:`django-db-logger`. @@ -453,5 +454,5 @@ logging module. .. class:: RequireDebugTrue() - This filter is similar to :class:`RequireDebugFalse`, except that records are - passed only when :setting:`DEBUG` is ``True``. + This filter is similar to :class:`RequireDebugFalse`, except that records + are passed only when :setting:`DEBUG` is ``True``. diff --git a/docs/ref/middleware.txt b/docs/ref/middleware.txt index 0cbcee4c4c..29e8f7b941 100644 --- a/docs/ref/middleware.txt +++ b/docs/ref/middleware.txt @@ -36,9 +36,9 @@ defines. See the :doc:`cache documentation </topics/cache>`. .. attribute:: response_redirect_class - Defaults to :class:`~django.http.HttpResponsePermanentRedirect`. Subclass - ``CommonMiddleware`` and override the attribute to customize the redirects - issued by the middleware. + Defaults to :class:`~django.http.HttpResponsePermanentRedirect`. + Subclass ``CommonMiddleware`` and override the attribute to customize + the redirects issued by the middleware. Adds a few conveniences for perfectionists: @@ -240,10 +240,10 @@ so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year, is common). Additionally, if you set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting -to ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` directive -to the ``Strict-Transport-Security`` header. This is recommended (assuming all -subdomains are served exclusively using HTTPS), otherwise your site may still -be vulnerable via an insecure connection to a subdomain. +to ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` +directive to the ``Strict-Transport-Security`` header. This is recommended +(assuming all subdomains are served exclusively using HTTPS), otherwise your +site may still be vulnerable via an insecure connection to a subdomain. If you wish to submit your site to the `browser preload list`_, set the :setting:`SECURE_HSTS_PRELOAD` setting to ``True``. That appends the @@ -339,13 +339,11 @@ this setting are: Instructs the browser to send the full URL as the referrer for same-origin links, and only the origin for cross-origin links. -``same-origin`` - Instructs the browser to send a full URL, but only for same-origin links. No - referrer will be sent for cross-origin links. +``same-origin`` Instructs the browser to send a full URL, but only for +same-origin links. No referrer will be sent for cross-origin links. -``strict-origin`` - Instructs the browser to send only the origin, not the full URL, and to send - no referrer when a protocol downgrade occurs. +``strict-origin`` Instructs the browser to send only the origin, not the full +URL, and to send no referrer when a protocol downgrade occurs. ``strict-origin-when-cross-origin`` Instructs the browser to send the full URL when the link is same-origin and @@ -509,19 +507,19 @@ every incoming ``HttpRequest`` object. See :ref:`Authentication in web requests .. method:: get_login_url() - Returns the URL that unauthenticated requests will be redirected to. This - result is either the ``login_url`` set on the - :func:`~django.contrib.auth.decorators.login_required` decorator (if not - ``None``), or :setting:`settings.LOGIN_URL <LOGIN_URL>`. + Returns the URL that unauthenticated requests will be redirected to. + This result is either the ``login_url`` set on the + :func:`~django.contrib.auth.decorators.login_required` decorator (if + not ``None``), or :setting:`settings.LOGIN_URL <LOGIN_URL>`. .. method:: get_redirect_field_name() Returns the name of the query parameter that contains the URL the user should be redirected to after a successful login. This result is either the ``redirect_field_name`` set on the - :func:`~.django.contrib.auth.decorators.login_required` decorator (if not - ``None``), or :attr:`redirect_field_name`. If ``None`` is returned, a query - parameter won't be added. + :func:`~.django.contrib.auth.decorators.login_required` decorator (if + not ``None``), or :attr:`redirect_field_name`. If ``None`` is returned, + a query parameter won't be added. Redirects all unauthenticated requests to a login page, except for views excluded with :func:`~.django.contrib.auth.decorators.login_not_required`. The @@ -605,7 +603,8 @@ You can add Cross Site Request Forgery protection to individual views using the .. class:: XFrameOptionsMiddleware -Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`. +Simple :doc:`clickjacking protection via the X-Frame-Options header +</ref/clickjacking/>`. Content Security Policy middleware ---------------------------------- @@ -625,7 +624,8 @@ This middleware sets the following headers on the response depending on the available settings: * ``Content-Security-Policy``, based on :setting:`SECURE_CSP`. -* ``Content-Security-Policy-Report-Only``, based on :setting:`SECURE_CSP_REPORT_ONLY`. +* ``Content-Security-Policy-Report-Only``, based on + :setting:`SECURE_CSP_REPORT_ONLY`. .. _middleware-ordering: diff --git a/docs/ref/migration-operations.txt b/docs/ref/migration-operations.txt index 26c0c14218..e636d682c7 100644 --- a/docs/ref/migration-operations.txt +++ b/docs/ref/migration-operations.txt @@ -48,7 +48,8 @@ database to match it. The field instance should be an unbound field (so just ``models.CharField(...)``, rather than a field taken from another model). -``options`` is an optional dictionary of values from the model's ``Meta`` class. +``options`` is an optional dictionary of values from the model's ``Meta`` +class. ``bases`` is an optional list of other classes to have this model inherit from; it can contain both class objects as well as strings in the format @@ -330,10 +331,11 @@ irreversible. The ``state_operations`` argument allows you to supply operations that are equivalent to the SQL in terms of project state. For example, if you are -manually creating a column, you should pass in a list containing an ``AddField`` -operation here so that the autodetector still has an up-to-date state of the -model. If you don't, when you next run ``makemigrations``, it won't see any -operation that adds that field and so will try to run it again. For example:: +manually creating a column, you should pass in a list containing an +``AddField`` operation here so that the autodetector still has an up-to-date +state of the model. If you don't, when you next run ``makemigrations``, it +won't see any operation that adds that field and so will try to run it again. +For example:: migrations.RunSQL( "ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;", @@ -385,9 +387,10 @@ database hints. The optional ``elidable`` argument determines whether or not the operation will be removed (elided) when :ref:`squashing migrations <migration-squashing>`. -You are advised to write the code as a separate function above the ``Migration`` -class in the migration file, and pass it to ``RunPython``. Here's an example of -using ``RunPython`` to create some initial objects on a ``Country`` model:: +You are advised to write the code as a separate function above the +``Migration`` class in the migration file, and pass it to ``RunPython``. Here's +an example of using ``RunPython`` to create some initial objects on a +``Country`` model:: from django.db import migrations @@ -427,10 +430,10 @@ custom data updates and alterations, and anything else you need access to an ORM and/or Python code for. Much like :class:`RunSQL`, ensure that if you change schema inside here you're -either doing it outside the scope of the Django model system (e.g. triggers) -or that you use :class:`SeparateDatabaseAndState` to add in operations that will -reflect your changes to the model state - otherwise, the versioned ORM and -the autodetector will stop working correctly. +either doing it outside the scope of the Django model system (e.g. triggers) or +that you use :class:`SeparateDatabaseAndState` to add in operations that will +reflect your changes to the model state - otherwise, the versioned ORM and the +autodetector will stop working correctly. By default, ``RunPython`` will run its contents inside a transaction on databases that do not support DDL transactions (for example, MySQL and @@ -455,8 +458,8 @@ if ``atomic=True`` is passed to the ``RunPython`` operation. .. warning:: - ``RunPython`` does not magically alter the connection of the models for you; - any model methods you call will go to the default database unless you + ``RunPython`` does not magically alter the connection of the models for + you; any model methods you call will go to the default database unless you give them the current database alias (available from ``schema_editor.connection.alias``, where ``schema_editor`` is the second argument to your function). @@ -608,7 +611,8 @@ Some things to note: ... * ``to_state`` in the database_backwards method is the *older* state; that is, - the one that will be the current state once the migration has finished reversing. + the one that will be the current state once the migration has finished + reversing. * You might see implementations of ``references_model`` on the built-in operations; this is part of the autodetection code and does not matter for diff --git a/docs/ref/models/class.txt b/docs/ref/models/class.txt index 4890955fe7..c36eeaa34f 100644 --- a/docs/ref/models/class.txt +++ b/docs/ref/models/class.txt @@ -77,5 +77,5 @@ Attributes # Add manager with another name people = models.Manager() - For more details on model managers see :doc:`Managers </topics/db/managers>` - and :ref:`Retrieving objects <retrieving-objects>`. + For more details on model managers see :doc:`Managers + </topics/db/managers>` and :ref:`Retrieving objects <retrieving-objects>`. diff --git a/docs/ref/models/constraints.txt b/docs/ref/models/constraints.txt index eefe741805..af6a2e4672 100644 --- a/docs/ref/models/constraints.txt +++ b/docs/ref/models/constraints.txt @@ -288,10 +288,10 @@ Defaults to :attr:`.BaseConstraint.violation_error_code`, when either is not set. If :attr:`.UniqueConstraint.fields` is set without a -:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together -<django.db.models.Options.unique_together>` error code when there are multiple -fields, and to the :attr:`.Field.unique` error code when there is a single -field. +:attr:`.UniqueConstraint.condition`, defaults to the +:attr:`Meta.unique_together <django.db.models.Options.unique_together>` error +code when there are multiple fields, and to the :attr:`.Field.unique` error +code when there is a single field. .. versionchanged:: 5.2 @@ -313,10 +313,10 @@ Defaults to :attr:`.BaseConstraint.violation_error_message`, when either is not set. If :attr:`.UniqueConstraint.fields` is set without a -:attr:`.UniqueConstraint.condition`, defaults to the :attr:`Meta.unique_together -<django.db.models.Options.unique_together>` error message when there are -multiple fields, and to the :attr:`.Field.unique` error message when there is a -single field. +:attr:`.UniqueConstraint.condition`, defaults to the +:attr:`Meta.unique_together <django.db.models.Options.unique_together>` error +message when there are multiple fields, and to the :attr:`.Field.unique` error +message when there is a single field. .. versionchanged:: 5.2 diff --git a/docs/ref/models/database-functions.txt b/docs/ref/models/database-functions.txt index aa18ed4045..0abd0e6a81 100644 --- a/docs/ref/models/database-functions.txt +++ b/docs/ref/models/database-functions.txt @@ -168,9 +168,9 @@ and ``comment.modified``. .. class:: Least(*expressions, **extra) -Accepts a list of at least two field names or expressions and returns the -least value. Each argument must be of a similar type, so mixing text and numbers -will result in a database error. +Accepts a list of at least two field names or expressions and returns the least +value. Each argument must be of a similar type, so mixing text and numbers will +result in a database error. .. warning:: @@ -565,8 +565,8 @@ value. If ``output_field`` is omitted, it will default to the ``output_field`` of ``expression``. A ``tzinfo`` subclass, usually provided by :mod:`zoneinfo`, can be passed to truncate a value in a specific timezone. -Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\s -return: +Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in +``kind``\s return: * "year": 2015-01-01 00:00:00+00:00 * "quarter": 2015-04-01 00:00:00+00:00 @@ -1823,7 +1823,8 @@ Usage example: Returns a substring of length ``length`` from the field or expression starting at position ``pos``. The position is 1-indexed, so the position must be greater -than 0. If ``length`` is ``None``, then the rest of the string will be returned. +than 0. If ``length`` is ``None``, then the rest of the string will be +returned. Usage example: diff --git a/docs/ref/models/expressions.txt b/docs/ref/models/expressions.txt index 0d0e82df13..d4095a3900 100644 --- a/docs/ref/models/expressions.txt +++ b/docs/ref/models/expressions.txt @@ -261,8 +261,8 @@ different fields with arithmetic:: If the fields that you're combining are of different types you'll need to tell Django what kind of field will be returned. Most expressions support -:ref:`output_field<output-field>` for this case, but since ``F()`` does not, you -will need to wrap the expression with :class:`ExpressionWrapper`:: +:ref:`output_field<output-field>` for this case, but since ``F()`` does not, +you will need to wrap the expression with :class:`ExpressionWrapper`:: from django.db.models import DateTimeField, ExpressionWrapper, F @@ -404,14 +404,15 @@ The ``Func`` API is as follows: ) To avoid an SQL injection vulnerability, ``extra_context`` :ref:`must - not contain untrusted user input <avoiding-sql-injection-in-query-expressions>` - as these values are interpolated into the SQL string rather than passed - as query parameters, where the database driver would escape them. + not contain untrusted user input + <avoiding-sql-injection-in-query-expressions>` as these values are + interpolated into the SQL string rather than passed as query + parameters, where the database driver would escape them. The ``*expressions`` argument is a list of positional expressions that the function will be applied to. The expressions will be converted to strings, -joined together with ``arg_joiner``, and then interpolated into the ``template`` -as the ``expressions`` placeholder. +joined together with ``arg_joiner``, and then interpolated into the +``template`` as the ``expressions`` placeholder. Positional arguments can be expressions or Python values. Strings are assumed to be column references and will be wrapped in ``F()`` expressions @@ -1381,14 +1382,17 @@ class:: Length.as_sqlserver = sqlserver_length -You can also customize the SQL using the ``template`` parameter of ``as_sql()``. +You can also customize the SQL using the ``template`` parameter of +``as_sql()``. We use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns ``sqlserver`` for the backend. Third-party backends can register their functions in the top level -``__init__.py`` file of the backend package or in a top level ``expressions.py`` -file (or package) that is imported from the top level ``__init__.py``. +``__init__.py`` file of the backend package or in a top level +``expressions.py`` file (or package) that is imported from the top level +``__init__.py``. For user projects wishing to patch the backend that they're using, this code -should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method. +should live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` +method. diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 39c7277de1..b08718879b 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -39,17 +39,17 @@ The following arguments are available to all field types. All are optional. .. attribute:: Field.null -If ``True``, Django will store empty values as ``NULL`` in the database. Default -is ``False``. +If ``True``, Django will store empty values as ``NULL`` in the database. +Default is ``False``. Avoid using :attr:`~Field.null` on string-based fields such as :class:`CharField` and :class:`TextField`. The Django convention is to use an -empty string, not ``NULL``, as the "no data" state for string-based fields. If a -string-based field has ``null=False``, empty strings can still be saved for "no -data". If a string-based field has ``null=True``, that means it has two possible -values for "no data": ``NULL``, and the empty string. In most cases, it's -redundant to have two possible values for "no data". One exception is when a -:class:`CharField` has both ``unique=True`` and ``blank=True`` set. In this +empty string, not ``NULL``, as the "no data" state for string-based fields. If +a string-based field has ``null=False``, empty strings can still be saved for +"no data". If a string-based field has ``null=True``, that means it has two +possible values for "no data": ``NULL``, and the empty string. In most cases, +it's redundant to have two possible values for "no data". One exception is when +a :class:`CharField` has both ``unique=True`` and ``blank=True`` set. In this situation, ``null=True`` is required to avoid unique constraint violations when saving multiple objects with blank values. @@ -60,8 +60,8 @@ set ``blank=True`` if you wish to permit empty values in forms, as the .. note:: - When using the Oracle database backend, the value ``NULL`` will be stored to - denote the empty string regardless of this attribute. + When using the Oracle database backend, the value ``NULL`` will be stored + to denote the empty string regardless of this attribute. ``blank`` --------- @@ -464,10 +464,10 @@ support tablespaces for indexes, this option is ignored. The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. -The default can't be a mutable object (model instance, ``list``, ``set``, etc.), -as a reference to the same instance of that object would be used as the default -value in all new model instances. Instead, wrap the desired default in a -callable. For example, if you want to specify a default ``dict`` for +The default can't be a mutable object (model instance, ``list``, ``set``, +etc.), as a reference to the same instance of that object would be used as the +default value in all new model instances. Instead, wrap the desired default in +a callable. For example, if you want to specify a default ``dict`` for :class:`~django.db.models.JSONField`, use a function:: def contact_default(): @@ -506,12 +506,12 @@ validation <validating-objects>`. Default is ``True``. .. attribute:: Field.error_messages The ``error_messages`` argument lets you override the default messages that the -field will raise. Pass in a dictionary with keys matching the error messages you -want to override. +field will raise. Pass in a dictionary with keys matching the error messages +you want to override. -Error message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``, -``unique``, and ``unique_for_date``. Additional error message keys are -specified for each field in the `Field types`_ section below. +Error message keys include ``null``, ``blank``, ``invalid``, +``invalid_choice``, ``unique``, and ``unique_for_date``. Additional error +message keys are specified for each field in the `Field types`_ section below. These error messages often don't propagate to forms. See :ref:`considerations-regarding-model-errormessages`. @@ -654,10 +654,10 @@ Field types .. class:: AutoField(**options) -An :class:`IntegerField` that automatically increments -according to available IDs. You usually won't need to use this directly; a -primary key field will automatically be added to your model if you don't specify -otherwise. See :ref:`automatic-primary-key-fields`. +An :class:`IntegerField` that automatically increments according to available +IDs. You usually won't need to use this directly; a primary key field will +automatically be added to your model if you don't specify otherwise. See +:ref:`automatic-primary-key-fields`. ``BigAutoField`` ---------------- @@ -815,8 +815,8 @@ The default form widget for this field is a and a shortcut for "Today". Includes an additional ``invalid_date`` error message key. -The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive. -Any combination of these options will result in an error. +The options ``auto_now_add``, ``auto_now``, and ``default`` are mutually +exclusive. Any combination of these options will result in an error. .. note:: As currently implemented, setting ``auto_now`` or ``auto_now_add`` to @@ -944,8 +944,8 @@ Has the following optional arguments: .. attribute:: FileField.upload_to - This attribute provides a way of setting the upload directory and file name, - and can be set in two ways. In both cases, the value is passed to the + This attribute provides a way of setting the upload directory and file + name, and can be set in two ways. In both cases, the value is passed to the :meth:`Storage.save() <django.core.files.storage.Storage.save>` method. If you specify a string value or a :class:`~pathlib.Path`, it may contain @@ -968,9 +968,9 @@ Has the following optional arguments: handles ``upload_to``. ``upload_to`` may also be a callable, such as a function. This will be - called to obtain the upload path, including the filename. This callable must - accept two arguments and return a Unix-style path (with forward slashes) - to be passed along to the storage system. The two arguments are: + called to obtain the upload path, including the filename. This callable + must accept two arguments and return a Unix-style path (with forward + slashes) to be passed along to the storage system. The two arguments are: ====================== =============================================== Argument Description @@ -1030,11 +1030,11 @@ takes a few steps: ``{{ object.mug_shot.url }}``. For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and -:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'`` -part of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting; -``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is -the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in -the directory ``/home/media/photos/2007/01/15``. +:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The +``'%Y/%m/%d'`` part of :attr:`~FileField.upload_to` is :func:`~time.strftime` +formatting; ``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month +and ``'%d'`` is the two-digit day. If you upload a file on Jan. 15, 2007, it +will be saved in the directory ``/home/media/photos/2007/01/15``. If you wanted to retrieve the uploaded file's on-disk filename, or the file's size, you could use the :attr:`~django.core.files.File.name` and @@ -1044,9 +1044,9 @@ information on the available attributes and methods, see the topic guide. .. note:: - The file is saved as part of saving the model in the database, so the actual - file name used on disk cannot be relied on until after the model has been - saved. + The file is saved as part of saving the model in the database, so the + actual file name used on disk cannot be relied on until after the model has + been saved. The uploaded file's relative URL can be obtained using the :attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally, @@ -1085,9 +1085,10 @@ file. The API of :class:`FieldFile` mirrors that of :class:`~django.core.files.File`, with one key difference: *The object wrapped by the class is not necessarily a wrapper around Python's built-in file object.* Instead, it is a wrapper around -the result of the :attr:`Storage.open()<django.core.files.storage.Storage.open>` -method, which may be a :class:`~django.core.files.File` object, or it may be a -custom storage's implementation of the :class:`~django.core.files.File` API. +the result of the +:attr:`Storage.open()<django.core.files.storage.Storage.open>` method, which +may be a :class:`~django.core.files.File` object, or it may be a custom +storage's implementation of the :class:`~django.core.files.File` API. In addition to the API inherited from :class:`~django.core.files.File` such as ``read()`` and ``write()``, :class:`FieldFile` includes several methods that @@ -1226,7 +1227,8 @@ directory on the filesystem. Has some special arguments, of which the first is .. attribute:: FilePathField.recursive Optional. Either ``True`` or ``False``. Default is ``False``. Specifies - whether all subdirectories of :attr:`~FilePathField.path` should be included + whether all subdirectories of :attr:`~FilePathField.path` should be + included .. attribute:: FilePathField.allow_files @@ -1269,11 +1271,11 @@ when :attr:`~django.forms.Field.localize` is ``False`` or .. admonition:: ``FloatField`` vs. ``DecimalField`` The :class:`FloatField` class is sometimes mixed up with the - :class:`DecimalField` class. Although they both represent real numbers, they - represent those numbers differently. ``FloatField`` uses Python's ``float`` - type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For - information on the difference between the two, see Python's documentation - for the :mod:`decimal` module. + :class:`DecimalField` class. Although they both represent real numbers, + they represent those numbers differently. ``FloatField`` uses Python's + ``float`` type internally, while ``DecimalField`` uses Python's ``Decimal`` + type. For information on the difference between the two, see Python's + documentation for the :mod:`decimal` module. ``GeneratedField`` ------------------ @@ -1375,8 +1377,9 @@ values are stored as null. Inherits all attributes and methods from :class:`FileField`, but also validates that the uploaded object is a valid image. -In addition to the special attributes that are available for :class:`FileField`, -an :class:`ImageField` also has ``height`` and ``width`` attributes. +In addition to the special attributes that are available for +:class:`FileField`, an :class:`ImageField` also has ``height`` and ``width`` +attributes. To facilitate querying on those attributes, :class:`ImageField` has the following optional arguments: @@ -1517,8 +1520,8 @@ all databases supported by Django. .. class:: SlugField(max_length=50, **options) :term:`Slug <slug>` is a newspaper term. A slug is a short label for something, -containing only letters, numbers, underscores or hyphens. They're generally used -in URLs. +containing only letters, numbers, underscores or hyphens. They're generally +used in URLs. Like a CharField, you can specify :attr:`~CharField.max_length` (read the note about database portability and :attr:`~CharField.max_length` in that section, @@ -2014,9 +2017,9 @@ that control how the relationship functions. :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am your friend, then you are my friend. - If you do not want symmetry in many-to-many relationships with ``self``, set - :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to - add the descriptor for the reverse relationship, allowing + If you do not want symmetry in many-to-many relationships with ``self``, + set :attr:`~ManyToManyField.symmetrical` to ``False``. This will force + Django to add the descriptor for the reverse relationship, allowing :class:`ManyToManyField` relationships to be non-symmetrical. .. attribute:: ManyToManyField.through @@ -2183,12 +2186,12 @@ that control how the relationship functions. .. attribute:: ManyToManyField.swappable - Controls the migration framework's reaction if this :class:`ManyToManyField` - is pointing at a swappable model. If it is ``True`` - the default - - then if the :class:`ManyToManyField` is pointing at a model which matches - the current value of ``settings.AUTH_USER_MODEL`` (or another swappable - model setting) the relationship will be stored in the migration using - a reference to the setting, not to the model directly. + Controls the migration framework's reaction if this + :class:`ManyToManyField` is pointing at a swappable model. If it is + ``True`` - the default - then if the :class:`ManyToManyField` is pointing + at a model which matches the current value of ``settings.AUTH_USER_MODEL`` + (or another swappable model setting) the relationship will be stored in the + migration using a reference to the setting, not to the model directly. You only want to override this to be ``False`` if you are sure your model should always point toward the swapped-in model - for example, @@ -2476,7 +2479,8 @@ Field API reference value) * when it saves to the database (Python value -> database backend value) - When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used: + When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are + used: .. method:: get_prep_value(value) @@ -2572,8 +2576,8 @@ Field API reference Returns the default :class:`django.forms.Field` of this field for :class:`~django.forms.ModelForm`. - If :meth:`~Field.formfield` is overridden to return ``None``, this field - is excluded from the :class:`~django.forms.ModelForm`. + If :meth:`~Field.formfield` is overridden to return ``None``, this + field is excluded from the :class:`~django.forms.ModelForm`. By default, if both ``form_class`` and ``choices_form_class`` are ``None``, it uses :class:`~django.forms.CharField`. If the field has @@ -2587,8 +2591,9 @@ Field API reference Returns a 4-tuple with enough information to recreate the field: 1. The name of the field on the model. - 2. The import path of the field (e.g. ``"django.db.models.IntegerField"``). - This should be the most portable version, so less specific may be better. + 2. The import path of the field (e.g. + ``"django.db.models.IntegerField"``). This should be the most + portable version, so less specific may be better. 3. A list of positional arguments. 4. A dict of keyword arguments. @@ -2598,9 +2603,10 @@ Field API reference Registering and fetching lookups ================================ -``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`. -The API can be used to customize which lookups are available for a field class -and its instances, and how lookups are fetched from a field. +``Field`` implements the :ref:`lookup registration API +<lookup-registration-api>`. The API can be used to customize which lookups are +available for a field class and its instances, and how lookups are fetched from +a field. .. _model-field-attributes: diff --git a/docs/ref/models/instances.txt b/docs/ref/models/instances.txt index 6baa0cb27d..d847666bbc 100644 --- a/docs/ref/models/instances.txt +++ b/docs/ref/models/instances.txt @@ -87,7 +87,8 @@ fields are present, then ``values`` are guaranteed to be in the order to each of the missing fields. In addition to creating the new model, the ``from_db()`` method must set the -``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` attribute. +``adding`` and ``db`` flags in the new instance's :attr:`~Model._state` +attribute. Below is an example showing how to record the initial values of fields that are loaded from the database:: @@ -485,11 +486,11 @@ rather than relying on the auto-assignment of the ID: If you assign auto-primary-key values manually, make sure not to use an already-existing primary-key value! If you create a new object with an explicit -primary-key value that already exists in the database, Django will assume you're -changing the existing record rather than creating a new one. +primary-key value that already exists in the database, Django will assume +you're changing the existing record rather than creating a new one. -Given the above ``'Cheddar Talk'`` blog example, this example would override the -previous record in the database:: +Given the above ``'Cheddar Talk'`` blog example, this example would override +the previous record in the database:: b4 = Blog(id=3, name="Not Cheddar", tagline="Anything but cheese.") b4.save() # Overrides the previous blog with ID=3! @@ -563,17 +564,18 @@ exists in the database. Otherwise, Django executes an ``INSERT``. The one gotcha here is that you should be careful not to specify a primary-key value explicitly when saving new objects, if you cannot guarantee the -primary-key value is unused. For more on this nuance, see `Explicitly specifying -auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below. +primary-key value is unused. For more on this nuance, see `Explicitly +specifying auto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ +below. In Django 1.5 and earlier, Django did a ``SELECT`` when the primary key -attribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``, -otherwise it did an ``INSERT``. The old algorithm results in one more query in -the ``UPDATE`` case. There are some rare cases where the database doesn't -report that a row was updated even if the database contains a row for the -object's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger -which returns ``NULL``. In such cases it is possible to revert to the old -algorithm by setting the :attr:`~django.db.models.Options.select_on_save` +attribute was set. If the ``SELECT`` found a row, then Django did an +``UPDATE``, otherwise it did an ``INSERT``. The old algorithm results in one +more query in the ``UPDATE`` case. There are some rare cases where the database +doesn't report that a row was updated even if the database contains a row for +the object's primary key value. An example is the PostgreSQL ``ON UPDATE`` +trigger which returns ``NULL``. In such cases it is possible to revert to the +old algorithm by setting the :attr:`~django.db.models.Options.select_on_save` option to ``True``. .. _ref-models-force-insert: diff --git a/docs/ref/models/lookups.txt b/docs/ref/models/lookups.txt index 3d6600dc44..d2d91deb4e 100644 --- a/docs/ref/models/lookups.txt +++ b/docs/ref/models/lookups.txt @@ -12,19 +12,22 @@ the ``WHERE`` clause of a database query. To learn how to *use* lookups, see :doc:`/topics/db/queries`; to learn how to *create* new lookups, see :doc:`/howto/custom-lookups`. -The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class -that registers lookups, and the :ref:`Query Expression API <query-expression>`, a -set of methods that a class has to implement to be registrable as a lookup. +The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` +class that registers lookups, and the :ref:`Query Expression API +<query-expression>`, a set of methods that a class has to implement to be +registrable as a lookup. Django has two base classes that follow the query expression API and from where all Django builtin lookups are derived: -* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``) +* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of + ``field_name__exact``) * :class:`Transform`: to transform a field A lookup expression consists of three parts: -* Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``); +* Fields part (e.g. + ``Book.objects.filter(author__best_friends__first_name...``); * Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``); * A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``. @@ -33,8 +36,8 @@ A lookup expression consists of three parts: Registration API ================ -Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to -register lookups on itself or its instances. The two prominent examples are +Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface +to register lookups on itself or its instances. The two prominent examples are :class:`~django.db.models.Field`, the base class of all model fields, and :class:`Transform`, the base class of all Django transforms. @@ -88,10 +91,10 @@ The Query Expression API ======================== The query expression API is a common set of methods that classes define to be -usable in query expressions to translate themselves into SQL expressions. Direct -field references, aggregates, and ``Transform`` are examples that follow this -API. A class is said to follow the query expression API when it implements the -following methods: +usable in query expressions to translate themselves into SQL expressions. +Direct field references, aggregates, and ``Transform`` are examples that follow +this API. A class is said to follow the query expression API when it implements +the following methods: .. method:: as_sql(compiler, connection) @@ -146,18 +149,20 @@ following methods: The notation to use a ``Transform`` in a lookup expression is ``<expression>__<transformation>`` (e.g. ``date__year``). - This class follows the :ref:`Query Expression API <query-expression>`, which - implies that you can use ``<expression>__<transform1>__<transform2>``. It's - a specialized :ref:`Func() expression <func-expressions>` that only accepts - one argument. It can also be used on the right hand side of a filter or - directly as an annotation. + This class follows the :ref:`Query Expression API <query-expression>`, + which implies that you can use + ``<expression>__<transform1>__<transform2>``. It's a specialized + :ref:`Func() expression <func-expressions>` that only accepts one argument. + It can also be used on the right hand side of a filter or directly as an + annotation. .. attribute:: bilateral A boolean indicating whether this transformation should apply to both - ``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in - the same order as they appear in the lookup expression. By default it is set - to ``False``. For example usage, see :doc:`/howto/custom-lookups`. + ``lhs`` and ``rhs``. Bilateral transformations will be applied to + ``rhs`` in the same order as they appear in the lookup expression. By + default it is set to ``False``. For example usage, see + :doc:`/howto/custom-lookups`. .. attribute:: lhs diff --git a/docs/ref/models/meta.txt b/docs/ref/models/meta.txt index 009433a44c..d06dc55111 100644 --- a/docs/ref/models/meta.txt +++ b/docs/ref/models/meta.txt @@ -31,12 +31,12 @@ Retrieving a single field instance of a model by name Returns the field instance given a name of a field. - ``field_name`` can be the name of a field on the model, a field - on an abstract or inherited model, or a field defined on another - model that points to the model. In the latter case, the ``field_name`` - will be (in order of preference) the :attr:`~.ForeignKey.related_query_name` - set by the user, the :attr:`~.ForeignKey.related_name` set by the user, or - the name automatically generated by Django. + ``field_name`` can be the name of a field on the model, a field on an + abstract or inherited model, or a field defined on another model that + points to the model. In the latter case, the ``field_name`` will be (in + order of preference) the :attr:`~.ForeignKey.related_query_name` set by the + user, the :attr:`~.ForeignKey.related_name` set by the user, or the name + automatically generated by Django. :attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved by name. @@ -129,9 +129,9 @@ Retrieving fields composing the primary key of a model Returns a list of the fields composing the primary key of a model. - When a :class:`composite primary key <django.db.models.CompositePrimaryKey>` - is defined on a model it will contain all the - :class:`fields <django.db.models.Field>` referenced by it. + When a :class:`composite primary key + <django.db.models.CompositePrimaryKey>` is defined on a model it will + contain all the :class:`fields <django.db.models.Field>` referenced by it. .. code-block:: python diff --git a/docs/ref/models/options.txt b/docs/ref/models/options.txt index fce426ac97..0d27830fc9 100644 --- a/docs/ref/models/options.txt +++ b/docs/ref/models/options.txt @@ -68,9 +68,9 @@ a database table named ``bookstore_book``. To override the database table name, use the ``db_table`` parameter in ``class Meta``. -If your database table name is an SQL reserved word, or contains characters that -aren't allowed in Python variable names -- notably, the hyphen -- that's OK. -Django quotes column and table names behind the scenes. +If your database table name is an SQL reserved word, or contains characters +that aren't allowed in Python variable names -- notably, the hyphen -- that's +OK. Django quotes column and table names behind the scenes. .. admonition:: Use lowercase table names for MariaDB and MySQL @@ -130,8 +130,8 @@ not be looking at your Django code. For example:: .. attribute:: Options.default_related_name - The name that will be used by default for the relation from a related object - back to this one. The default is ``<model_name>_set``. + The name that will be used by default for the relation from a related + object back to this one. The default is ``<model_name>_set``. This option also sets :attr:`~ForeignKey.related_query_name`. @@ -199,9 +199,10 @@ not be looking at your Django code. For example:: For tests involving models with ``managed=False``, it's up to you to ensure the correct tables are created as part of the test setup. - If you're interested in changing the Python-level behavior of a model class, - you *could* use ``managed=False`` and create a copy of an existing model. - However, there's a better approach for that situation: :ref:`proxy-models`. + If you're interested in changing the Python-level behavior of a model + class, you *could* use ``managed=False`` and create a copy of an existing + model. However, there's a better approach for that situation: + :ref:`proxy-models`. ``order_with_respect_to`` ------------------------- @@ -229,12 +230,12 @@ not be looking at your Django code. For example:: class Meta: order_with_respect_to = "question" - When ``order_with_respect_to`` is set, two additional methods are provided to - retrieve and to set the order of the related objects: ``get_RELATED_order()`` - and ``set_RELATED_order()``, where ``RELATED`` is the lowercased model name. For - example, assuming that a ``Question`` object has multiple related ``Answer`` - objects, the list returned contains the primary keys of the related ``Answer`` - objects: + When ``order_with_respect_to`` is set, two additional methods are provided + to retrieve and to set the order of the related objects: + ``get_RELATED_order()`` and ``set_RELATED_order()``, where ``RELATED`` is + the lowercased model name. For example, assuming that a ``Question`` object + has multiple related ``Answer`` objects, the list returned contains the + primary keys of the related ``Answer`` objects: .. code-block:: pycon @@ -242,16 +243,16 @@ not be looking at your Django code. For example:: >>> question.get_answer_order() [1, 2, 3] - The order of a ``Question`` object's related ``Answer`` objects can be set by - passing in a list of ``Answer`` primary keys: + The order of a ``Question`` object's related ``Answer`` objects can be set + by passing in a list of ``Answer`` primary keys: .. code-block:: pycon >>> question.set_answer_order([3, 1, 2]) The related objects also get two methods, ``get_next_in_order()`` and - ``get_previous_in_order()``, which can be used to access those objects in their - proper order. Assuming the ``Answer`` objects are ordered by ``id``: + ``get_previous_in_order()``, which can be used to access those objects in + their proper order. Assuming the ``Answer`` objects are ordered by ``id``: .. code-block:: pycon @@ -281,7 +282,8 @@ not be looking at your Django code. For example:: .. attribute:: Options.ordering - The default ordering for the object, for use when obtaining lists of objects:: + The default ordering for the object, for use when obtaining lists of + objects:: ordering = ["-order_date"] @@ -298,7 +300,8 @@ not be looking at your Django code. For example:: ordering = ["-pub_date"] - To order by ``pub_date`` descending, then by ``author`` ascending, use this:: + To order by ``pub_date`` descending, then by ``author`` ascending, use + this:: ordering = ["-pub_date", "author"] @@ -326,9 +329,10 @@ not be looking at your Django code. For example:: .. attribute:: Options.permissions - Extra permissions to enter into the permissions table when creating this object. - Add, change, delete, and view permissions are automatically created for each - model. This example specifies an extra permission, ``can_deliver_pizzas``:: + Extra permissions to enter into the permissions table when creating this + object. Add, change, delete, and view permissions are automatically created + for each model. This example specifies an extra permission, + ``can_deliver_pizzas``:: permissions = [("can_deliver_pizzas", "Can deliver pizzas")] @@ -351,8 +355,8 @@ not be looking at your Django code. For example:: .. attribute:: Options.proxy - If ``proxy = True``, a model which subclasses another model will be treated as - a :ref:`proxy model <proxy-models>`. + If ``proxy = True``, a model which subclasses another model will be treated + as a :ref:`proxy model <proxy-models>`. ``required_db_features`` ------------------------ @@ -373,8 +377,8 @@ not be looking at your Django code. For example:: Name of a supported database vendor that this model is specific to. Current built-in vendor names are: ``sqlite``, ``postgresql``, ``mysql``, - ``oracle``. If this attribute is not empty and the current connection vendor - doesn't match it, the model will not be synchronized. + ``oracle``. If this attribute is not empty and the current connection + vendor doesn't match it, the model will not be synchronized. ``select_on_save`` ------------------ @@ -433,8 +437,8 @@ not be looking at your Django code. For example:: unique_together = [["driver", "restaurant"]] This is a list of lists that must be unique when considered together. - It's used in the Django admin and is enforced at the database level (i.e., the - appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE`` + It's used in the Django admin and is enforced at the database level (i.e., + the appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE`` statement). For convenience, ``unique_together`` can be a single list when dealing with @@ -491,7 +495,8 @@ not be looking at your Django code. For example:: verbose_name_plural = "stories" - If this isn't given, Django will use :attr:`~Options.verbose_name` + ``"s"``. + If this isn't given, Django will use :attr:`~Options.verbose_name` + + ``"s"``. Read-only ``Meta`` attributes ============================= diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index f03f96443e..baeb3e8746 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -85,20 +85,21 @@ You can evaluate a ``QuerySet`` in the following ways: print("There is at least one Entry with the headline Test") Note: If you only want to determine if at least one result exists (and don't - need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`. + need the actual objects), it's more efficient to use + :meth:`~QuerySet.exists`. .. _pickling QuerySets: Pickling ``QuerySet``\s ----------------------- -If you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded -into memory prior to pickling. Pickling is usually used as a precursor to -caching and when the cached queryset is reloaded, you want the results to +If you :mod:`pickle` a ``QuerySet``, this will force all the results to be +loaded into memory prior to pickling. Pickling is usually used as a precursor +to caching and when the cached queryset is reloaded, you want the results to already be present and ready for use (reading from the database can take some time, defeating the purpose of caching). This means that when you unpickle a -``QuerySet``, it contains the results at the moment it was pickled, rather -than the results that are currently in the database. +``QuerySet``, it contains the results at the moment it was pickled, rather than +the results that are currently in the database. If you only want to pickle the necessary information to recreate the ``QuerySet`` from the database at a later time, pickle the ``query`` attribute @@ -207,8 +208,8 @@ The lookup parameters (``**kwargs``) should be in the format described in `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the underlying SQL statement. -If you need to execute more complex queries (for example, queries with ``OR`` statements), -you can use :class:`Q objects <django.db.models.Q>` (``*args``). +If you need to execute more complex queries (for example, queries with ``OR`` +statements), you can use :class:`Q objects <django.db.models.Q>` (``*args``). ``exclude()`` ~~~~~~~~~~~~~ @@ -249,8 +250,8 @@ In SQL terms, that evaluates to: Note the second example is more restrictive. -If you need to execute more complex queries (for example, queries with ``OR`` statements), -you can use :class:`Q objects <django.db.models.Q>` (``*args``). +If you need to execute more complex queries (for example, queries with ``OR`` +statements), you can use :class:`Q objects <django.db.models.Q>` (``*args``). ``annotate()`` ~~~~~~~~~~~~~~ @@ -536,8 +537,8 @@ field names, the database will only compare the specified field names. .. note:: When you specify field names, you *must* provide an ``order_by()`` in the - ``QuerySet``, and the fields in ``order_by()`` must start with the fields in - ``distinct()``, in the same order. + ``QuerySet``, and the fields in ``order_by()`` must start with the fields + in ``distinct()``, in the same order. For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each value in column ``a``. If you don't specify an order, you'll get some @@ -1102,7 +1103,7 @@ following models:: # ... author = models.ForeignKey(Person, on_delete=models.CASCADE) -... then a call to ``Book.objects.select_related('author__hometown').get(id=4)`` +Then a call to ``Book.objects.select_related('author__hometown').get(id=4)`` will cache the related ``Person`` *and* the related ``City``:: # Hits the database with joins to the author and hometown tables. @@ -1124,7 +1125,8 @@ You can also refer to the reverse direction of a ``select_related`` — that is, you can traverse a :class:`~django.db.models.OneToOneField` back to the object on which the field is defined. Instead of specifying the field name, use the :attr:`related_name -<django.db.models.ForeignKey.related_name>` for the field on the related object. +<django.db.models.ForeignKey.related_name>` for the field on the related +object. There may be some situations where you wish to call ``select_related()`` with a lot of related objects, or where you don't know all of the relations. In these @@ -1153,15 +1155,15 @@ Returns a ``QuerySet`` that will automatically retrieve, in a single batch, related objects for each of the specified lookups. This has a similar purpose to ``select_related``, in that both are designed to -stop the deluge of database queries that is caused by accessing related objects, -but the strategy is quite different. +stop the deluge of database queries that is caused by accessing related +objects, but the strategy is quite different. -``select_related`` works by creating an SQL join and including the fields of the -related object in the ``SELECT`` statement. For this reason, ``select_related`` -gets the related objects in the same database query. However, to avoid the much -larger result set that would result from joining across a 'many' relationship, -``select_related`` is limited to single-valued relationships - foreign key and -one-to-one. +``select_related`` works by creating an SQL join and including the fields of +the related object in the ``SELECT`` statement. For this reason, +``select_related`` gets the related objects in the same database query. +However, to avoid the much larger result set that would result from joining +across a 'many' relationship, ``select_related`` is limited to single-valued +relationships - foreign key and one-to-one. ``prefetch_related``, on the other hand, does a separate lookup for each relationship, and does the 'joining' in Python. This allows it to prefetch @@ -1240,8 +1242,8 @@ If you have an iterable of model instances, you can prefetch related attributes on those instances using the :func:`~django.db.models.prefetch_related_objects` function. -Note that the result cache of the primary ``QuerySet`` and all specified related -objects will then be fully loaded into memory. This changes the typical +Note that the result cache of the primary ``QuerySet`` and all specified +related objects will then be fully loaded into memory. This changes the typical behavior of a ``QuerySet``, which normally tries to avoid loading all objects into memory before they are needed, even after a query has been executed in the database. @@ -1329,16 +1331,16 @@ save both memory and CPU time. While ``prefetch_related`` supports prefetching ``GenericForeignKey`` relationships, the number of queries will depend on the data. Since a -``GenericForeignKey`` can reference data in multiple tables, one query per table -referenced is needed, rather than one query for all the items. There could be -additional queries on the ``ContentType`` table if the relevant rows have not -already been fetched. +``GenericForeignKey`` can reference data in multiple tables, one query per +table referenced is needed, rather than one query for all the items. There +could be additional queries on the ``ContentType`` table if the relevant rows +have not already been fetched. ``prefetch_related`` in most cases will be implemented using an SQL query that -uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause -could be generated, which, depending on the database, might have performance -problems of its own when it comes to parsing or executing the SQL query. Always -profile for your use case! +uses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' +clause could be generated, which, depending on the database, might have +performance problems of its own when it comes to parsing or executing the SQL +query. Always profile for your use case! If you use ``iterator()`` to run the query, ``prefetch_related()`` calls will only be observed if a value for ``chunk_size`` is provided. @@ -1372,8 +1374,8 @@ applicable to reduce the number of queries even further: ... Prefetch("restaurants", queryset=Restaurant.objects.select_related("best_pizza")) ... ) -You can also assign the prefetched result to a custom attribute with the optional -``to_attr`` argument. The result will be stored directly in a list. +You can also assign the prefetched result to a custom attribute with the +optional ``to_attr`` argument. The result will be stored directly in a list. This allows prefetching the same relation multiple times with a different ``QuerySet``; for instance: @@ -1386,8 +1388,8 @@ This allows prefetching the same relation multiple times with a different ... Prefetch("pizzas", queryset=vegetarian_pizzas, to_attr="vegetarian_menu"), ... ) -Lookups created with custom ``to_attr`` can still be traversed as usual by other -lookups: +Lookups created with custom ``to_attr`` can still be traversed as usual by +other lookups: .. code-block:: pycon @@ -1397,8 +1399,9 @@ lookups: ... "vegetarian_menu__toppings", ... ) -Using ``to_attr`` is recommended when filtering down the prefetch result as it is -less ambiguous than storing a filtered result in the related manager's cache: +Using ``to_attr`` is recommended when filtering down the prefetch result as it +is less ambiguous than storing a filtered result in the related manager's +cache: .. code-block:: pycon @@ -1486,8 +1489,8 @@ database selected by the outer query. All of the following are valid: >>> prefetch_related("pizza_list__toppings", Prefetch("pizzas", to_attr="pizza_list")) - This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet - when ``'pizza_list__toppings'`` is being processed. + This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't + exist yet when ``'pizza_list__toppings'`` is being processed. This consideration is not limited to the use of ``Prefetch`` objects. Some advanced techniques may require that the lookups be performed in a @@ -1510,7 +1513,7 @@ generated by a ``QuerySet``. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please `file a ticket <https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra - keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_ + keyword <https://code.djangoproject.com/query?keywords=~QuerySet.extra>`_ with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing ``extra()``. We are no longer improving or fixing bugs for this method. @@ -1707,13 +1710,13 @@ of the arguments is required, but you should use at least one of them. .. warning:: - If you are performing queries on MySQL, note that MySQL's silent type coercion - may cause unexpected results when mixing types. If you query on a string - type column, but with an integer value, MySQL will coerce the types of all values - in the table to an integer before performing the comparison. For example, if your - table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``, - both rows will match. To prevent this, perform the correct typecasting - before using the value in a query. + If you are performing queries on MySQL, note that MySQL's silent type + coercion may cause unexpected results when mixing types. If you query on a + string type column, but with an integer value, MySQL will coerce the types + of all values in the table to an integer before performing the comparison. + For example, if your table contains the values ``'abc'``, ``'def'`` and you + query for ``WHERE mycolumn=0``, both rows will match. To prevent this, + perform the correct typecasting before using the value in a query. ``defer()`` ~~~~~~~~~~~ @@ -1946,8 +1949,8 @@ By default, ``select_for_update()`` locks all rows that are selected by the query. For example, rows of related objects specified in :meth:`select_related` are locked in addition to rows of the queryset's model. If this isn't desired, specify the related objects you want to lock in ``select_for_update(of=(...))`` -using the same fields syntax as :meth:`select_related`. Use the value ``'self'`` -to refer to the queryset's model. +using the same fields syntax as :meth:`select_related`. Use the value +``'self'`` to refer to the queryset's model. .. admonition:: Lock parents models in ``select_for_update(of=(...))`` @@ -2191,7 +2194,8 @@ can use :exc:`django.core.exceptions.ObjectDoesNotExist` to handle *Asynchronous version*: ``acreate()`` -A convenience method for creating an object and saving it all in one step. Thus:: +A convenience method for creating an object and saving it all in one step. +Thus:: p = Person.objects.create(first_name="Bruce", last_name="Springsteen") @@ -2252,9 +2256,9 @@ found, ``get_or_create()`` returns a tuple of that object and ``False``. This method is atomic assuming that the database enforces uniqueness of the keyword arguments (see :attr:`~django.db.models.Field.unique` or - :attr:`~django.db.models.Options.unique_together`). If the fields used in the - keyword arguments do not have a uniqueness constraint, concurrent calls to - this method may result in multiple rows with the same parameters being + :attr:`~django.db.models.Options.unique_together`). If the fields used in + the keyword arguments do not have a uniqueness constraint, concurrent calls + to this method may result in multiple rows with the same parameters being inserted. You can specify more complex conditions for the retrieved object by chaining @@ -2306,10 +2310,11 @@ whenever a request to a page has a side effect on your data. For more, see .. warning:: - You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField` - attributes and reverse relations. In that case you will restrict the queries - inside the context of that relation. That could lead you to some integrity - problems if you don't use it consistently. + You can use ``get_or_create()`` through + :class:`~django.db.models.ManyToManyField` attributes and reverse relations. + In that case you will restrict the queries inside the context of that + relation. That could lead you to some integrity problems if you don't use it + consistently. Being the following models:: @@ -2336,10 +2341,10 @@ whenever a request to a page has a side effect on your data. For more, see >>> book.chapters.get_or_create(title="Chapter 1") # Raises IntegrityError - This is happening because it's trying to get or create "Chapter 1" through the - book "Ulysses", but it can't do either: the relation can't fetch that chapter - because it isn't related to that book, but it can't create it either because - ``title`` field should be unique. + This is happening because it's trying to get or create "Chapter 1" through + the book "Ulysses", but it can't do either: the relation can't fetch that + chapter because it isn't related to that book, but it can't create it either + because ``title`` field should be unique. ``update_or_create()`` ~~~~~~~~~~~~~~~~~~~~~~ @@ -2904,7 +2909,8 @@ you could do this: >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False) -(This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.) +(This assumes your ``Entry`` model has fields ``pub_date`` and +``comments_on``.) You can update multiple fields — there's no limit on how many. For example, here we update the ``comments_on`` and ``headline`` fields: @@ -3909,8 +3915,8 @@ Strings that reference fields on the model, transforms of the field, or ``output_field`` ~~~~~~~~~~~~~~~~ -An optional argument that represents the :doc:`model field </ref/models/fields>` -of the return value +An optional argument that represents the :doc:`model field +</ref/models/fields>` of the return value .. note:: diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index d39cd9fa3e..ab1f3575e8 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -113,9 +113,9 @@ All attributes should be considered read-only, unless stated otherwise. It's possible that a request can come in via POST with an empty ``POST`` dictionary -- if, say, a form is requested via the POST HTTP method but - does not include form data. Therefore, you shouldn't use ``if request.POST`` - to check for use of the POST method; instead, use ``if request.method == - "POST"`` (see :attr:`HttpRequest.method`). + does not include form data. Therefore, you shouldn't use ``if + request.POST`` to check for use of the POST method; instead, use ``if + request.method == "POST"`` (see :attr:`HttpRequest.method`). ``POST`` does *not* include file-upload information. See :attr:`FILES`. @@ -127,13 +127,15 @@ All attributes should be considered read-only, unless stated otherwise. A dictionary-like object containing all uploaded files. Each key in ``FILES`` is the ``name`` from the ``<input type="file" name="">``. Each - value in ``FILES`` is an :class:`~django.core.files.uploadedfile.UploadedFile`. + value in ``FILES`` is an + :class:`~django.core.files.uploadedfile.UploadedFile`. See :doc:`/topics/files` for more information. ``FILES`` will only contain data if the request method was POST and the - ``<form>`` that posted to the request had ``enctype="multipart/form-data"``. - Otherwise, ``FILES`` will be a blank dictionary-like object. + ``<form>`` that posted to the request had + ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank + dictionary-like object. .. attribute:: HttpRequest.META @@ -541,10 +543,10 @@ Methods .. class:: QueryDict In an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and -:attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``, -a dictionary-like class customized to deal with multiple values for the same -key. This is necessary because some HTML form elements, notably -``<select multiple>``, pass multiple values for the same key. +:attr:`~HttpRequest.POST` attributes are instances of +``django.http.QueryDict``, a dictionary-like class customized to deal with +multiple values for the same key. This is necessary because some HTML form +elements, notably ``<select multiple>``, pass multiple values for the same key. The ``QueryDict``\ s at ``request.POST`` and ``request.GET`` will be immutable when accessed in a normal request/response cycle. To get a mutable version you @@ -573,8 +575,8 @@ a subclass of dictionary. Exceptions are outlined here: instantiating one yourself, you can make it mutable by passing ``mutable=True`` to its ``__init__()``. - Strings for setting both keys and values will be converted from ``encoding`` - to ``str``. If ``encoding`` is not set, it defaults to + Strings for setting both keys and values will be converted from + ``encoding`` to ``str``. If ``encoding`` is not set, it defaults to :setting:`DEFAULT_CHARSET`. .. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None) @@ -613,8 +615,8 @@ a subclass of dictionary. Exceptions are outlined here: .. method:: QueryDict.__contains__(key) - Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo" - in request.GET``. + Returns ``True`` if the given key is set. This lets you do, e.g., ``if + "foo" in request.GET``. .. method:: QueryDict.get(key, default=None) @@ -623,7 +625,8 @@ a subclass of dictionary. Exceptions are outlined here: .. method:: QueryDict.setdefault(key, default=None) - Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally. + Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` + internally. .. method:: QueryDict.update(other_dict) @@ -643,8 +646,8 @@ a subclass of dictionary. Exceptions are outlined here: .. method:: QueryDict.items() Like :meth:`dict.items`, except this uses the same last-value logic as - :meth:`__getitem__` and returns an iterator object instead of a view object. - For example: + :meth:`__getitem__` and returns an iterator object instead of a view + object. For example: .. code-block:: pycon @@ -843,9 +846,9 @@ You can also set headers on instantiation: For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended to use the :func:`~django.utils.cache.patch_cache_control` and :func:`~django.utils.cache.patch_vary_headers` methods from -:mod:`django.utils.cache`, since these fields can have multiple, comma-separated -values. The "patch" methods ensure that other values, e.g. added by a -middleware, are not removed. +:mod:`django.utils.cache`, since these fields can have multiple, +comma-separated values. The "patch" methods ensure that other values, e.g. +added by a middleware, are not removed. HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise ``BadHeaderError`` @@ -1110,11 +1113,11 @@ types of HTTP responses. Like ``HttpResponse``, these subclasses live in .. class:: HttpResponseRedirect The first argument to the constructor is required -- the path to redirect - to. This can be a fully qualified URL - (e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain - (e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that - last case, the client browser will reconstruct the full URL itself - according to the current path. + to. This can be a fully qualified URL (e.g. + ``'https://www.yahoo.com/search/'``), an absolute path with no domain (e.g. + ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that last + case, the client browser will reconstruct the full URL itself according to + the current path. The constructor accepts an optional ``preserve_request`` keyword argument that defaults to ``False``, producing a response with a 302 status code. If diff --git a/docs/ref/schema-editor.txt b/docs/ref/schema-editor.txt index b459e646bc..f4da52eb02 100644 --- a/docs/ref/schema-editor.txt +++ b/docs/ref/schema-editor.txt @@ -31,8 +31,8 @@ of change are not possible on all databases - for example, MyISAM does not support foreign key constraints. If you are writing or maintaining a third-party database backend for Django, -you will need to provide a ``SchemaEditor`` implementation in order to work with -Django's migration functionality - however, as long as your database is +you will need to provide a ``SchemaEditor`` implementation in order to work +with Django's migration functionality - however, as long as your database is relatively standard in its use of SQL and relational design, you should be able to subclass one of the built-in Django ``SchemaEditor`` classes and tweak the syntax a little. diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index c1909ff40f..d5b7f2ad05 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -168,8 +168,8 @@ backend class (i.e. ``mypackage.backends.whatever.WhateverCache``). ``KEY_FUNCTION`` ~~~~~~~~~~~~~~~~ -A string containing a dotted path to a function (or any callable) that defines how to -compose a prefix, version and key into a final cache key. The default +A string containing a dotted path to a function (or any callable) that defines +how to compose a prefix, version and key into a final cache key. The default implementation is equivalent to the function:: def make_key(key, key_prefix, version): @@ -1116,7 +1116,8 @@ The default formatting to use for displaying date fields in any part of the system. Note that the locale-dictated format has higher precedence and will be applied instead. See :tfilter:`allowed date format strings <date>`. -See also :setting:`DATETIME_FORMAT`, :setting:`TIME_FORMAT` and :setting:`SHORT_DATE_FORMAT`. +See also :setting:`DATETIME_FORMAT`, :setting:`TIME_FORMAT` and +:setting:`SHORT_DATE_FORMAT`. .. setting:: DATE_INPUT_FORMATS @@ -1160,7 +1161,8 @@ The default formatting to use for displaying datetime fields in any part of the system. Note that the locale-dictated format has higher precedence and will be applied instead. See :tfilter:`allowed date format strings <date>`. -See also :setting:`DATE_FORMAT`, :setting:`TIME_FORMAT` and :setting:`SHORT_DATETIME_FORMAT`. +See also :setting:`DATE_FORMAT`, :setting:`TIME_FORMAT` and +:setting:`SHORT_DATETIME_FORMAT`. .. setting:: DATETIME_INPUT_FORMATS @@ -1458,9 +1460,9 @@ Port to use for the SMTP server defined in :setting:`EMAIL_HOST`. Default: ``'[Django] '`` -Subject-line prefix for email messages sent with ``django.core.mail.mail_admins`` -or ``django.core.mail.mail_managers``. You'll probably want to include the -trailing space. +Subject-line prefix for email messages sent with +``django.core.mail.mail_admins`` or ``django.core.mail.mail_managers``. You'll +probably want to include the trailing space. .. setting:: EMAIL_USE_LOCALTIME @@ -1536,11 +1538,11 @@ If :setting:`EMAIL_USE_SSL` or :setting:`EMAIL_USE_TLS` is ``True``, you can optionally specify the path to a PEM-formatted private key file for client authentication of the SSL connection along with :setting:`EMAIL_SSL_CERTFILE`. -Note that setting :setting:`EMAIL_SSL_CERTFILE` and :setting:`EMAIL_SSL_KEYFILE` -doesn't result in any certificate checking. They're passed to the underlying SSL -connection. Please refer to the documentation of Python's -:meth:`python:ssl.SSLContext.wrap_socket` function for details on how the -certificate chain file and private key file are handled. +Note that setting :setting:`EMAIL_SSL_CERTFILE` and +:setting:`EMAIL_SSL_KEYFILE` doesn't result in any certificate checking. +They're passed to the underlying SSL connection. Please refer to the +documentation of Python's :meth:`python:ssl.SSLContext.wrap_socket` function +for details on how the certificate chain file and private key file are handled. .. setting:: EMAIL_TIMEOUT @@ -1843,17 +1845,17 @@ A list of IP addresses, as strings, that: Default: ``'en-us'`` -A string representing the language code for this installation. This should be in -standard :term:`language ID format <language code>`. For example, U.S. English -is ``"en-us"``. See also the `list of language identifiers`_ and +A string representing the language code for this installation. This should be +in standard :term:`language ID format <language code>`. For example, U.S. +English is ``"en-us"``. See also the `list of language identifiers`_ and :doc:`/topics/i18n/index`. It serves three purposes: * If the locale middleware isn't in use, it decides which translation is served to all users. -* If the locale middleware is active, it provides a fallback language in case the - user's preferred language can't be determined or is not supported by the +* If the locale middleware is active, it provides a fallback language in case + the user's preferred language can't be determined or is not supported by the website. It also provides the fallback translation when a translation for a given literal doesn't exist for the user's preferred language. * If localization is explicitly disabled via the :tfilter:`unlocalize` filter @@ -1927,19 +1929,19 @@ application). See :doc:`/topics/i18n/index`. Default: ``'/'`` -The path set on the language cookie. This should either match the URL path of your -Django installation or be a parent of that path. +The path set on the language cookie. This should either match the URL path of +your Django installation or be a parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths and each instance will only see its own language cookie. Be cautious when updating this setting on a production site. If you update this -setting to use a deeper path than it previously used, existing user cookies that -have the old path will not be updated. This will result in site users being -unable to switch the language as long as these cookies persist. The only safe -and reliable option to perform the switch is to change the language cookie name -permanently (via the :setting:`LANGUAGE_COOKIE_NAME` setting), and to add +setting to use a deeper path than it previously used, existing user cookies +that have the old path will not be updated. This will result in site users +being unable to switch the language as long as these cookies persist. The only +safe and reliable option to perform the switch is to change the language cookie +name permanently (via the :setting:`LANGUAGE_COOKIE_NAME` setting), and to add a middleware that copies the value from the old cookie to a new one and then deletes the one. @@ -1950,8 +1952,8 @@ deletes the one. Default: ``None`` -The value of the `SameSite`_ flag on the language cookie. This flag prevents the -cookie from being sent in cross-site requests. +The value of the `SameSite`_ flag on the language cookie. This flag prevents +the cookie from being sent in cross-site requests. See :setting:`SESSION_COOKIE_SAMESITE` for details about ``SameSite``. @@ -2032,8 +2034,9 @@ Example:: "/var/local/translations/locale", ] -Django will look within each of these paths for the ``<locale_code>/LC_MESSAGES`` -directories containing the actual translation files. +Django will look within each of these paths for the +``<locale_code>/LC_MESSAGES`` directories containing the actual translation +files. .. setting:: LOGGING @@ -2243,8 +2246,8 @@ See also :setting:`DECIMAL_SEPARATOR`, :setting:`THOUSAND_SEPARATOR` and Default: ``False`` -Whether to prepend the "www." subdomain to URLs that don't have it. This is only -used if :class:`~django.middleware.common.CommonMiddleware` is installed +Whether to prepend the "www." subdomain to URLs that don't have it. This is +only used if :class:`~django.middleware.common.CommonMiddleware` is installed (see :doc:`/topics/http/middleware`). See also :setting:`APPEND_SLASH`. .. setting:: ROOT_URLCONF @@ -2459,9 +2462,9 @@ Following the example from the :setting:`SECURE_CSP` setting:: Default: ``False`` If ``True``, the :class:`~django.middleware.security.SecurityMiddleware` adds -the ``includeSubDomains`` directive to the :ref:`http-strict-transport-security` -header. It has no effect unless :setting:`SECURE_HSTS_SECONDS` is set to a -non-zero value. +the ``includeSubDomains`` directive to the +:ref:`http-strict-transport-security` header. It has no effect unless +:setting:`SECURE_HSTS_SECONDS` is set to a non-zero value. .. warning:: Setting this incorrectly can irreversibly (for the value of @@ -2570,8 +2573,8 @@ available in ``request.META``.) Default: ``[]`` (Empty list) -If a URL path matches a regular expression in this list, the request will not be -redirected to HTTPS. The +If a URL path matches a regular expression in this list, the request will not +be redirected to HTTPS. The :class:`~django.middleware.security.SecurityMiddleware` strips leading slashes from URL paths, so patterns shouldn't include them, e.g. ``SECURE_REDIRECT_EXEMPT = [r'^no-ssl/$', …]``. If @@ -2596,8 +2599,8 @@ to the value provided. Default: ``None`` If a string (e.g. ``secure.example.com``), all SSL redirects will be directed -to this host rather than the originally-requested host -(e.g. ``www.example.com``). If :setting:`SECURE_SSL_REDIRECT` is ``False``, this +to this host rather than the originally-requested host (e.g. +``www.example.com``). If :setting:`SECURE_SSL_REDIRECT` is ``False``, this setting has no effect. .. setting:: SECURE_SSL_REDIRECT @@ -3015,7 +3018,8 @@ See also :setting:`DECIMAL_SEPARATOR`, :setting:`NUMBER_GROUPING` and Default: ``True`` A boolean that specifies if datetimes will be timezone-aware by default or not. -If this is set to ``True``, Django will use timezone-aware datetimes internally. +If this is set to ``True``, Django will use timezone-aware datetimes +internally. When ``USE_TZ`` is False, Django will use naive datetimes in local time, except when parsing ISO 8601 formatted strings, where timezone information will always @@ -3282,13 +3286,15 @@ Controls where Django stores message data. Valid values are: * ``'django.contrib.messages.storage.session.SessionStorage'`` * ``'django.contrib.messages.storage.cookie.CookieStorage'`` -See :ref:`message storage backends <message-storage-backends>` for more details. +See :ref:`message storage backends <message-storage-backends>` for more +details. The backends that use cookies -- :class:`~django.contrib.messages.storage.cookie.CookieStorage` and :class:`~django.contrib.messages.storage.fallback.FallbackStorage` -- -use the value of :setting:`SESSION_COOKIE_DOMAIN`, :setting:`SESSION_COOKIE_SECURE` -and :setting:`SESSION_COOKIE_HTTPONLY` when setting their cookies. +use the value of :setting:`SESSION_COOKIE_DOMAIN`, +:setting:`SESSION_COOKIE_SECURE` and :setting:`SESSION_COOKIE_HTTPONLY` when +setting their cookies. .. setting:: MESSAGE_TAGS @@ -3412,8 +3418,8 @@ The name of the cookie to use for sessions. This can be whatever you want Default: ``'/'`` -The path set on the session cookie. This should either match the URL path of your -Django installation or be parent of that path. +The path set on the session cookie. This should either match the URL path of +your Django installation or be parent of that path. This is useful if you have multiple Django instances running under the same hostname. They can use different cookie paths, and each instance will only see diff --git a/docs/ref/signals.txt b/docs/ref/signals.txt index 60d7cd083d..6dc5122f96 100644 --- a/docs/ref/signals.txt +++ b/docs/ref/signals.txt @@ -10,8 +10,8 @@ using the :meth:`~django.dispatch.Signal.send` method. See the documentation on the :doc:`signal dispatcher </topics/signals>` for information regarding how to register for and receive signals. - The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when - a user is logged in / out <topics-auth-signals>`. + The :doc:`authentication framework </topics/auth/index>` sends + :ref:`signals when a user is logged in / out <topics-auth-signals>`. Model signals ============= @@ -36,8 +36,8 @@ model system. ``__init__()`` or :meth:`~django.db.models.Model.save` that you can override in your own code. - If you override these methods on your model, you must call the parent class' - methods for these signals to be sent. + If you override these methods on your model, you must call the parent + class' methods for these signals to be sent. Note also that Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To @@ -601,7 +601,8 @@ Arguments sent with this signal: .. data:: django.core.signals.got_request_exception :module: -This signal is sent whenever Django encounters an exception while processing an incoming HTTP request. +This signal is sent whenever Django encounters an exception while processing an +incoming HTTP request. Arguments sent with this signal: diff --git a/docs/ref/templates/api.txt b/docs/ref/templates/api.txt index cc6d807ce1..bd04c87ef2 100644 --- a/docs/ref/templates/api.txt +++ b/docs/ref/templates/api.txt @@ -115,9 +115,10 @@ overridden by what's passed by It defaults to ``'utf-8'``. - * ``'libraries'``: A dictionary of labels and dotted Python paths of template - tag modules to register with the template engine. This is used to add new - libraries or provide alternate labels for existing ones. For example:: + * ``'libraries'``: A dictionary of labels and dotted Python paths of + template tag modules to register with the template engine. This is used + to add new libraries or provide alternate labels for existing ones. For + example:: Engine( libraries={ @@ -136,8 +137,8 @@ overridden by what's passed by builtins=["myapp.builtins"], ) - Tags and filters from built-in libraries can be used without first calling - the :ttag:`{% load %}<load>` tag. + Tags and filters from built-in libraries can be used without first + calling the :ttag:`{% load %}<load>` tag. .. staticmethod:: Engine.get_default() @@ -434,11 +435,11 @@ Django's template language has no way to escape the characters used for its own syntax. For example, the :ttag:`templatetag` tag is required if you need to output character sequences like ``{%`` and ``%}``. -A similar issue exists if you want to include these sequences in template filter -or tag arguments. For example, when parsing a block tag, Django's template -parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents -the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError`` -will be raised for the following expressions: +A similar issue exists if you want to include these sequences in template +filter or tag arguments. For example, when parsing a block tag, Django's +template parser looks for the first occurrence of ``%}`` after a ``{%``. This +prevents the use of ``"%}"`` as a string literal. For example, a +``TemplateSyntaxError`` will be raised for the following expressions: .. code-block:: html+django @@ -588,8 +589,8 @@ tags <howto-writing-custom-template-tags>`. .. method:: Context.flatten() -Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary -including builtin variables. +Using ``flatten()`` method you can get whole ``Context`` stack as one +dictionary including builtin variables. .. code-block:: pycon @@ -600,7 +601,8 @@ including builtin variables. >>> c.flatten() {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'} -A ``flatten()`` method is also internally used to make ``Context`` objects comparable. +A ``flatten()`` method is also internally used to make ``Context`` objects +comparable. .. code-block:: pycon diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index 9e76319c43..432418b07f 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -1251,11 +1251,11 @@ you can also write the previous example as: {% endfor %} </ul> -Note that ``{% regroup %}`` does not order its input! Our example relies on -the fact that the ``cities`` list was ordered by ``country`` in the first place. -If the ``cities`` list did *not* order its members by ``country``, the -regrouping would naively display more than one group for a single country. For -example, say the ``cities`` list was set to this (note that the countries are not +Note that ``{% regroup %}`` does not order its input! Our example relies on the +fact that the ``cities`` list was ordered by ``country`` in the first place. If +the ``cities`` list did *not* order its members by ``country``, the regrouping +would naively display more than one group for a single country. For example, +say the ``cities`` list was set to this (note that the countries are not grouped together): .. code-block:: python @@ -1588,7 +1588,8 @@ image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). In some cases you might want to capture the result of ``widthratio`` in a -variable. It can be useful, for instance, in a :ttag:`blocktranslate` like this: +variable. It can be useful, for instance, in a :ttag:`blocktranslate` like +this: .. code-block:: html+django @@ -1740,7 +1741,8 @@ differences. .. note:: These format characters are not used in Django outside of templates. They - were designed to be compatible with PHP to ease transitioning for designers. + were designed to be compatible with PHP to ease transitioning for + designers. .. _date-and-time-formatting-specifiers: @@ -1754,32 +1756,32 @@ Format character Description Example output leading zeros. ``j`` Day of the month without leading ``'1'`` to ``'31'`` zeros. -``D`` Day of the week, textual, 3 letters. ``'Fri'`` -``l`` Day of the week, textual, long. ``'Friday'`` +``D`` Day of the week, textual, 3 letters. ``'Fri'`` +``l`` Day of the week, textual, long. ``'Friday'`` ``S`` English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'`` month, 2 characters. ``w`` Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday) leading zeros. -``z`` Day of the year. ``1`` to ``366`` +``z`` Day of the year. ``1`` to ``366`` **Week** ``W`` ISO-8601 week number of year, with ``1``, ``53`` weeks starting on Monday. **Month** -``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'`` -``n`` Month without leading zeros. ``'1'`` to ``'12'`` -``M`` Month, textual, 3 letters. ``'Jan'`` -``b`` Month, textual, 3 letters, lowercase. ``'jan'`` +``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'`` +``n`` Month without leading zeros. ``'1'`` to ``'12'`` +``M`` Month, textual, 3 letters. ``'Jan'`` +``b`` Month, textual, 3 letters, lowercase. ``'jan'`` ``E`` Month, locale specific alternative representation usually used for long - date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``) -``F`` Month, textual, long. ``'January'`` + date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``) +``F`` Month, textual, long. ``'January'`` ``N`` Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'`` style. Proprietary extension. -``t`` Number of days in the given month. ``28`` to ``31`` +``t`` Number of days in the given month. ``28`` to ``31`` **Year** -``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'`` -``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'`` -``L`` Boolean for whether it's a leap year. ``True`` or ``False`` +``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'`` +``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'`` +``L`` Boolean for whether it's a leap year. ``True`` or ``False`` ``o`` ISO-8601 week-numbering year, ``'1999'`` corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y @@ -1789,16 +1791,16 @@ Format character Description Example output zeros. ``G`` Hour, 24-hour format without leading ``'0'`` to ``'23'`` zeros. -``h`` Hour, 12-hour format. ``'01'`` to ``'12'`` -``H`` Hour, 24-hour format. ``'00'`` to ``'23'`` -``i`` Minutes. ``'00'`` to ``'59'`` -``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'`` -``u`` Microseconds. ``000000`` to ``999999`` +``h`` Hour, 12-hour format. ``'01'`` to ``'12'`` +``H`` Hour, 24-hour format. ``'00'`` to ``'23'`` +``i`` Minutes. ``'00'`` to ``'59'`` +``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'`` +``u`` Microseconds. ``000000`` to ``999999`` ``a`` ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'`` this is slightly different than PHP's output, because this includes periods to match Associated Press style.) -``A`` ``'AM'`` or ``'PM'``. ``'AM'`` +``A`` ``'AM'`` or ``'PM'``. ``'AM'`` ``f`` Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'`` with minutes left off if they're zero. Proprietary extension. @@ -1813,8 +1815,8 @@ Format character Description Example output depending on the datetime. ``I`` Daylight saving time, whether it's in ``'1'`` or ``'0'`` effect or not. -``O`` Difference to Greenwich time in hours. ``'+0200'`` -``T`` Time zone of this machine. ``'EST'``, ``'MDT'`` +``O`` Difference to Greenwich time in hours. ``'+0200'`` +``T`` Time zone of this machine. ``'EST'``, ``'MDT'`` ``Z`` Time zone offset in seconds. The ``-43200`` to ``43200`` offset for timezones west of UTC is always negative, and for those east of @@ -2519,8 +2521,8 @@ Example: If ``num_messages`` is ``1``, the output will be ``You have 1 message.`` If ``num_messages`` is ``2`` the output will be ``You have 2 messages.`` -For words that require a suffix other than ``'s'``, you can provide an alternate -suffix as a parameter to the filter. +For words that require a suffix other than ``'s'``, you can provide an +alternate suffix as a parameter to the filter. Example: diff --git a/docs/ref/templates/language.txt b/docs/ref/templates/language.txt index b24f291e4c..d80c2f6bd7 100644 --- a/docs/ref/templates/language.txt +++ b/docs/ref/templates/language.txt @@ -20,12 +20,13 @@ or Jinja2_, you should feel right at home with Django's templates. presentation, not program logic. The Django template system provides tags which function similarly to some - programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for` - tag for looping, etc. -- but these are not simply executed as the - corresponding Python code, and the template system will not execute - arbitrary Python expressions. Only the tags, filters and syntax listed below - are supported by default (although you can add :doc:`your own extensions - </howto/custom-template-tags>` to the template language as needed). + programming constructs -- an :ttag:`if` tag for boolean tests, a + :ttag:`for` tag for looping, etc. -- but these are not simply executed as + the corresponding Python code, and the template system will not execute + arbitrary Python expressions. Only the tags, filters and syntax listed + below are supported by default (although you can add :doc:`your own + extensions </howto/custom-template-tags>` to the template language as + needed). .. _`The Django template language: For Python programmers`: ../templates_python/ .. _Smarty: https://www.smarty.net/ @@ -97,8 +98,8 @@ Use a dot (``.``) to access attributes of a variable. result of the call becomes the template value. This lookup order can cause some unexpected behavior with objects that - override dictionary lookup. For example, consider the following code snippet - that attempts to loop over a ``collections.defaultdict``: + override dictionary lookup. For example, consider the following code + snippet that attempts to loop over a ``collections.defaultdict``: .. code-block:: html+django @@ -106,9 +107,9 @@ Use a dot (``.``) to access attributes of a variable. Do something with k and v here... {% endfor %} - Because dictionary lookup happens first, that behavior kicks in and provides - a default value instead of using the intended ``.items()`` method. In this - case, consider converting to a dictionary first. + Because dictionary lookup happens first, that behavior kicks in and + provides a default value instead of using the intended ``.items()`` method. + In this case, consider converting to a dictionary first. In the above example, ``{{ section.title }}`` will be replaced with the ``title`` attribute of the ``section`` object. @@ -202,10 +203,10 @@ some load external information into the template to be used by later variables. Some tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents ... {% endtag %}``). -Django ships with about two dozen built-in template tags. You can read all about -them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give -you a taste of what's available, here are some of the more commonly used -tags: +Django ships with about two dozen built-in template tags. You can read all +about them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. +To give you a taste of what's available, here are some of the more commonly +used tags: :ttag:`for` Loop over each item in an array. For example, to display a list of athletes @@ -288,9 +289,9 @@ A comment can contain any template code, invalid or not. For example: {# {% if foo %}bar{% else %} #} -This syntax can only be used for single-line comments (no newlines are permitted -between the ``{#`` and ``#}`` delimiters). If you need to comment out a -multiline portion of the template, see the :ttag:`comment` tag. +This syntax can only be used for single-line comments (no newlines are +permitted between the ``{#`` and ``#}`` delimiters). If you need to comment out +a multiline portion of the template, see the :ttag:`comment` tag. .. _template-inheritance: @@ -389,8 +390,8 @@ like: </html> Note that since the child template didn't define the ``sidebar`` block, the -value from the parent template is used instead. Content within a ``{% block %}`` -tag in a parent template is always used as a fallback. +value from the parent template is used instead. Content within a +``{% block %}`` tag in a parent template is always used as a fallback. You can use as many levels of inheritance as needed. One common way of using inheritance is the following three-level approach: @@ -410,12 +411,12 @@ areas, such as section-wide navigation. Here are some tips for working with inheritance: -* If you use :ttag:`{% extends %}<extends>` in a template, it must be the first template - tag in that template. Template inheritance won't work, otherwise. +* If you use :ttag:`{% extends %}<extends>` in a template, it must be the first + template tag in that template. Template inheritance won't work, otherwise. -* More :ttag:`{% block %}<block>` tags in your base templates are better. Remember, - child templates don't have to define all parent blocks, so you can fill - in reasonable defaults in a number of blocks, then only define the ones +* More :ttag:`{% block %}<block>` tags in your base templates are better. + Remember, child templates don't have to define all parent blocks, so you can + fill in reasonable defaults in a number of blocks, then only define the ones you need later. It's better to have more hooks than fewer hooks. * If you find yourself duplicating content in a number of templates, it @@ -894,8 +895,8 @@ tag in a template: {{ 45000|intcomma }} -In the above, the :ttag:`load` tag loads the ``humanize`` tag library, which then -makes the ``intcomma`` filter available for use. If you've enabled +In the above, the :ttag:`load` tag loads the ``humanize`` tag library, which +then makes the ``intcomma`` filter available for use. If you've enabled :mod:`django.contrib.admindocs`, you can consult the documentation area in your admin to find the list of custom libraries in your installation. @@ -906,8 +907,8 @@ Example: {% load humanize i18n %} -See :doc:`/howto/custom-template-tags` for information on writing your own custom -template libraries. +See :doc:`/howto/custom-template-tags` for information on writing your own +custom template libraries. Custom libraries and template inheritance ----------------------------------------- diff --git a/docs/ref/unicode.txt b/docs/ref/unicode.txt index 087e349c95..f8ac528666 100644 --- a/docs/ref/unicode.txt +++ b/docs/ref/unicode.txt @@ -60,15 +60,15 @@ You can use normal strings or bytestrings (starting with a 'b'). If your code only uses ASCII data, it's safe to use your normal strings, passing them around at will, because ASCII is a subset of UTF-8. -Don't be fooled into thinking that if your :setting:`DEFAULT_CHARSET` setting is set -to something other than ``'utf-8'`` you can use that other encoding in your -bytestrings! :setting:`DEFAULT_CHARSET` only applies to the strings generated as -the result of template rendering (and email). Django will always assume UTF-8 -encoding for internal bytestrings. The reason for this is that the -:setting:`DEFAULT_CHARSET` setting is not actually under your control (if you are the -application developer). It's under the control of the person installing and -using your application -- and if that person chooses a different setting, your -code must still continue to work. Ergo, it cannot rely on that setting. +Don't be fooled into thinking that if your :setting:`DEFAULT_CHARSET` setting +is set to something other than ``'utf-8'`` you can use that other encoding in +your bytestrings! :setting:`DEFAULT_CHARSET` only applies to the strings +generated as the result of template rendering (and email). Django will always +assume UTF-8 encoding for internal bytestrings. The reason for this is that the +:setting:`DEFAULT_CHARSET` setting is not actually under your control (if you +are the application developer). It's under the control of the person installing +and using your application -- and if that person chooses a different setting, +your code must still continue to work. Ergo, it cannot rely on that setting. In most cases when Django is dealing with strings, it will convert them to strings before doing anything else. So, as a general rule, if you pass @@ -209,8 +209,8 @@ In the first example, the UTF-8 characters are unquoted. In the second, the percent-encodings remain unchanged because they lie outside the valid UTF-8 range or represent a reserved character. -Both ``iri_to_uri()`` and ``uri_to_iri()`` functions are idempotent, which means the -following is always true:: +Both ``iri_to_uri()`` and ``uri_to_iri()`` functions are idempotent, which +means the following is always true:: iri_to_uri(iri_to_uri(some_string)) == iri_to_uri(some_string) uri_to_iri(uri_to_iri(some_string)) == uri_to_iri(some_string) @@ -272,8 +272,8 @@ setting. The built-in :py:mod:`~django.template.backends.django` backend provides the ``'file_charset'`` option to change the encoding used to read files from disk. -The :setting:`DEFAULT_CHARSET` setting controls the encoding of rendered templates. -This is set to UTF-8 by default. +The :setting:`DEFAULT_CHARSET` setting controls the encoding of rendered +templates. This is set to UTF-8 by default. Template tags and filters ------------------------- @@ -337,9 +337,10 @@ two fields will return their members as Unicode data. All other attributes and methods of ``HttpRequest`` return data exactly as it was submitted by the client. -By default, the :setting:`DEFAULT_CHARSET` setting is used as the assumed encoding -for form data. If you need to change this for a particular form, you can set -the ``encoding`` attribute on an ``HttpRequest`` instance. For example:: +By default, the :setting:`DEFAULT_CHARSET` setting is used as the assumed +encoding for form data. If you need to change this for a particular form, you +can set the ``encoding`` attribute on an ``HttpRequest`` instance. For +example:: def some_view(request): # We know that the data must be encoded as KOI8-R (for some reason). diff --git a/docs/ref/urlresolvers.txt b/docs/ref/urlresolvers.txt index ac0f74cdfc..f795aae7fe 100644 --- a/docs/ref/urlresolvers.txt +++ b/docs/ref/urlresolvers.txt @@ -59,10 +59,10 @@ matching against incoming URLs and sending them off to views, but you cannot reverse such patterns. The ``current_app`` argument allows you to provide a hint to the resolver -indicating the application to which the currently executing view belongs. -This ``current_app`` argument is used as a hint to resolve application -namespaces into URLs on specific application instances, according to the -:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`. +indicating the application to which the currently executing view belongs. This +``current_app`` argument is used as a hint to resolve application namespaces +into URLs on specific application instances, according to the :ref:`namespaced +URL resolution strategy <topics-http-reversing-url-namespaces>`. The ``urlconf`` argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used. @@ -104,8 +104,8 @@ For example: >>> reverse("cities", args=["Orléans"]) '.../Orl%C3%A9ans/' - Applying further encoding (such as :func:`urllib.parse.quote`) to the output - of ``reverse()`` may produce undesirable results. + Applying further encoding (such as :func:`urllib.parse.quote`) to the + output of ``reverse()`` may produce undesirable results. .. admonition:: Reversing class-based views by view object diff --git a/docs/ref/urls.txt b/docs/ref/urls.txt index 676350c44f..094fca992b 100644 --- a/docs/ref/urls.txt +++ b/docs/ref/urls.txt @@ -118,8 +118,8 @@ The ``view``, ``kwargs`` and ``name`` arguments are the same as for A function that takes a full Python import path to another URLconf module that should be "included" in this place. Optionally, the :term:`application - namespace` and :term:`instance namespace` where the entries will be included - into can also be specified. + namespace` and :term:`instance namespace` where the entries will be + included into can also be specified. Usually, the application namespace should be specified by the included module. If an application namespace is set, the ``namespace`` argument @@ -132,8 +132,10 @@ The ``view``, ``kwargs`` and ``name`` arguments are the same as for :arg module: URLconf module (or module name) :arg namespace: Instance namespace for the URL entries being included :type namespace: str - :arg pattern_list: Iterable of :func:`~django.urls.path` and/or :func:`~django.urls.re_path` instances. - :arg app_namespace: Application namespace for the URL entries being included + :arg pattern_list: Iterable of :func:`~django.urls.path` + and/or :func:`~django.urls.re_path` instances. + :arg app_namespace: Application namespace for the URL entries being + included :type app_namespace: str See :ref:`including-other-urlconfs` and :ref:`namespaces-and-include`. @@ -176,8 +178,8 @@ Helper function to return a URL pattern for serving files in debug mode:: .. data:: handler400 A callable, or a string representing the full Python import path to the view -that should be called if the HTTP client has sent a request that caused an error -condition and a response with a status code of 400. +that should be called if the HTTP client has sent a request that caused an +error condition and a response with a status code of 400. By default, this is :func:`django.views.defaults.bad_request`. If you implement a custom view, be sure it accepts ``request`` and ``exception`` diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index 6542f26476..fb053f6895 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -8,7 +8,8 @@ Django Utils This document covers all stable modules in ``django.utils``. Most of the modules in ``django.utils`` are designed for internal use and only the following parts can be considered stable and thus backwards compatible as per -the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`. +the :ref:`internal release deprecation policy +<internal-release-deprecation-policy>`. ``django.utils.cache`` ====================== @@ -297,7 +298,8 @@ The functions defined in this module share the following properties: ============================== .. module:: django.utils.feedgenerator - :synopsis: Syndication feed generation library -- used for generating RSS, etc. + :synopsis: Syndication feed generation library -- used for generating RSS, + etc. Sample usage: @@ -322,14 +324,16 @@ Sample usage: For simplifying the selection of a generator use ``feedgenerator.DefaultFeed`` which is currently ``Rss201rev2Feed`` -For definitions of the different versions of RSS, see: -https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss +For definitions of the different versions of RSS, see `The myth of RSS +compatibility +<https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss>`__. .. function:: get_tag_uri(url, date) Creates a TagURI. - See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id + See `How to make a good ID in Atom + <https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id>`__. ``Stylesheet`` -------------- @@ -367,8 +371,8 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 .. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, stylesheets=None, **kwargs) - Initialize the feed with the given dictionary of metadata, which applies - to the entire feed. + Initialize the feed with the given dictionary of metadata, which + applies to the entire feed. Any extra keyword arguments you pass to ``__init__`` will be stored in ``self.feed``. @@ -387,7 +391,8 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 Adds an item to the feed. All args are expected to be strings except ``pubdate`` and ``updateddate``, which are ``datetime.datetime`` - objects, and ``enclosures``, which is a list of ``Enclosure`` instances. + objects, and ``enclosures``, which is a list of ``Enclosure`` + instances. .. method:: num_items() @@ -518,7 +523,8 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 if person.friends: ... - The cached value can be treated like an ordinary attribute of the instance:: + The cached value can be treated like an ordinary attribute of the + instance:: # clear it, requiring re-computation next time it's called person.__dict__.pop("friends", None) @@ -695,8 +701,8 @@ escaping HTML. :func:`conditional_escape`. ``args_generator`` should be an iterator that yields arguments to pass to - :func:`format_html`, either sequences of positional arguments or mappings of - keyword arguments. + :func:`format_html`, either sequences of positional arguments or mappings + of keyword arguments. For example, tuples can be used for positional arguments:: @@ -837,7 +843,8 @@ Functions for working with Python modules. =========================== .. module:: django.utils.safestring - :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML. + :synopsis: Functions and classes for working with strings that can be + displayed safely without further escaping in HTML. Functions and classes for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe @@ -1166,8 +1173,8 @@ For a complete discussion on the usage of the following see the ``strict`` is ``True``, or if there is no generic variant and ``strict`` is ``False``. - If ``strict`` is ``False`` (the default), a country-specific variant may - be returned when neither the language code nor its generic variant is found. + If ``strict`` is ``False`` (the default), a country-specific variant may be + returned when neither the language code nor its generic variant is found. For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches aren't returned if ``strict=True``. diff --git a/docs/ref/validators.txt b/docs/ref/validators.txt index 3493363420..59eef7b35e 100644 --- a/docs/ref/validators.txt +++ b/docs/ref/validators.txt @@ -26,8 +26,8 @@ For example, here's a validator that only allows even numbers:: params={"value": value}, ) -You can add this to a model field via the field's :attr:`~django.db.models.Field.validators` -argument:: +You can add this to a model field via the field's +:attr:`~django.db.models.Field.validators` argument:: from django.db import models @@ -354,7 +354,7 @@ to, or in lieu of custom ``field.clean()`` methods. Uses Pillow to ensure that ``value.name`` (``value`` is a :class:`~django.core.files.File`) has `a valid image extension - <https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html>`_. + <https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html>`__. ``ProhibitNullCharactersValidator`` ----------------------------------- diff --git a/docs/releases/0.96.txt b/docs/releases/0.96.txt index 5a9492e389..23430152f4 100644 --- a/docs/releases/0.96.txt +++ b/docs/releases/0.96.txt @@ -98,9 +98,9 @@ Backslash escaping changed -------------------------- The Django database API now escapes backslashes given as query parameters. If -you have any database API code that matches backslashes, and it was working before -(despite the lack of escaping), you'll have to change your code to "unescape" the -slashes one level. +you have any database API code that matches backslashes, and it was working +before (despite the lack of escaping), you'll have to change your code to +"unescape" the slashes one level. For example, this used to work:: @@ -206,14 +206,16 @@ The test framework Django now includes a test framework so you can start transmuting fear into boredom (with apologies to Kent Beck). You can write tests based on -:mod:`doctest` or :mod:`unittest` and test your views with a simple test client. +:mod:`doctest` or :mod:`unittest` and test your views with a simple test +client. There is also new support for "fixtures" -- initial data, stored in any of the supported :doc:`serialization formats </topics/serialization>`, that will be loaded into your database at the start of your tests. This makes testing with real data much easier. -See :doc:`the testing documentation </topics/testing/index>` for the full details. +See :doc:`the testing documentation </topics/testing/index>` for the full +details. Improvements to the admin interface ----------------------------------- diff --git a/docs/releases/1.0-porting-guide.txt b/docs/releases/1.0-porting-guide.txt index 145334c238..62e4b86cab 100644 --- a/docs/releases/1.0-porting-guide.txt +++ b/docs/releases/1.0-porting-guide.txt @@ -5,14 +5,15 @@ Porting your apps from Django 0.96 to 1.0 Django 1.0 breaks compatibility with 0.96 in some areas. This guide will help you port 0.96 projects and apps to 1.0. The first part of -this document includes the common changes needed to run with 1.0. If after going -through the first part your code still breaks, check the section `Less-common -Changes`_ for a list of a bunch of less-common compatibility issues. +this document includes the common changes needed to run with 1.0. If after +going through the first part your code still breaks, check the section +`Less-common Changes`_ for a list of a bunch of less-common compatibility +issues. .. seealso:: - The :doc:`1.0 release notes </releases/1.0>`. That document explains the new - features in 1.0 more deeply; the porting guide is more concerned with + The :doc:`1.0 release notes </releases/1.0>`. That document explains the + new features in 1.0 more deeply; the porting guide is more concerned with helping you quickly update your code. Common changes @@ -83,7 +84,8 @@ see `the admin`_ below for more details. Example ~~~~~~~ -Below is an example ``models.py`` file with all the changes you'll need to make: +Below is an example ``models.py`` file with all the changes you'll need to +make: Old (0.96) ``models.py``:: @@ -127,14 +129,14 @@ The Admin One of the biggest changes in 1.0 is the new admin. The Django administrative interface (``django.contrib.admin``) has been completely refactored; admin definitions are now completely decoupled from model definitions, the framework -has been rewritten to use Django's new form-handling library and redesigned with -extensibility and customization in mind. +has been rewritten to use Django's new form-handling library and redesigned +with extensibility and customization in mind. Practically, this means you'll need to rewrite all of your ``class Admin`` -declarations. You've already seen in `models`_ above how to replace your ``class -Admin`` with an ``admin.site.register()`` call in an ``admin.py`` file. Below are -some more details on how to rewrite that ``Admin`` declaration into the new -syntax. +declarations. You've already seen in `models`_ above how to replace your +``class Admin`` with an ``admin.site.register()`` call in an ``admin.py`` file. +Below are some more details on how to rewrite that ``Admin`` declaration into +the new syntax. Use new inline syntax ~~~~~~~~~~~~~~~~~~~~~ @@ -210,8 +212,8 @@ New (1.0):: * More detailed information about the changes and the reasons behind them can be found on the `NewformsAdminBranch wiki page`__ - * The new admin comes with a ton of new features; you can read about them in - the :doc:`admin documentation </ref/contrib/admin/index>`. + * The new admin comes with a ton of new features; you can read about them + in the :doc:`admin documentation </ref/contrib/admin/index>`. __ https://code.djangoproject.com/wiki/NewformsAdminBranch @@ -301,10 +303,10 @@ Old (0.96) New (1.0) Work with file fields using the new API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The internal implementation of :class:`django.db.models.FileField` have changed. -A visible result of this is that the way you access special attributes (URL, -filename, image size, etc.) of these model fields has changed. You will need to -make the following changes, assuming your model's +The internal implementation of :class:`django.db.models.FileField` have +changed. A visible result of this is that the way you access special attributes +(URL, filename, image size, etc.) of these model fields has changed. You will +need to make the following changes, assuming your model's :class:`~django.db.models.FileField` is called ``myfile``: =================================== ======================== @@ -358,8 +360,8 @@ Less-common changes =================== The following changes are smaller, more localized changes. They should only -affect more advanced users, but it's probably worth reading through the list and -checking your code for these things. +affect more advanced users, but it's probably worth reading through the list +and checking your code for these things. Signals ------- @@ -370,8 +372,8 @@ Signals :class:`~django.dispatch.Signal` object instead of through module methods in ``django.dispatch.dispatcher``. -* Remove any use of the ``Anonymous`` and ``Any`` sender options; they no longer - exist. You can still receive signals sent by any sender by using +* Remove any use of the ``Anonymous`` and ``Any`` sender options; they no + longer exist. You can still receive signals sent by any sender by using ``sender=None`` * Make any custom signals you've declared into instances of @@ -502,7 +504,8 @@ New (1.0):: The ``LazyDate`` helper class no longer exists. Default field values and query arguments can both be callable objects, so -instances of ``LazyDate`` can be replaced with a reference to ``datetime.datetime.now``: +instances of ``LazyDate`` can be replaced with a reference to +``datetime.datetime.now``: Old (0.96):: @@ -631,7 +634,8 @@ Accessing ``HTTPResponse`` headers ``django.http.HttpResponse.headers`` has been renamed to ``_headers`` and :class:`~django.http.HttpResponse` now supports containment checking directly. -So use ``if header in response:`` instead of ``if header in response.headers:``. +So use ``if header in response:`` instead of ``if header in +response.headers:``. Generic relations ----------------- diff --git a/docs/releases/1.0.2.txt b/docs/releases/1.0.2.txt index b34522a08d..18ab1bdf59 100644 --- a/docs/releases/1.0.2.txt +++ b/docs/releases/1.0.2.txt @@ -7,8 +7,8 @@ Welcome to Django 1.0.2! This is the second "bugfix" release in the Django 1.0 series, improving the stability and performance of the Django 1.0 codebase. As such, Django 1.0.2 contains no new features (and, pursuant to -:doc:`our compatibility policy </misc/api-stability>`, maintains backwards compatibility with Django -1.0.0), but does contain a number of fixes and other +:doc:`our compatibility policy </misc/api-stability>`, maintains backwards +compatibility with Django 1.0.0), but does contain a number of fixes and other improvements. Django 1.0.2 is a recommended upgrade for any development or deployment currently using or targeting Django 1.0. diff --git a/docs/releases/1.0.txt b/docs/releases/1.0.txt index 9264ae5f47..0189aa8e71 100644 --- a/docs/releases/1.0.txt +++ b/docs/releases/1.0.txt @@ -4,20 +4,21 @@ Django 1.0 release notes Welcome to Django 1.0! -We've been looking forward to this moment for over three years, and it's finally -here. Django 1.0 represents the largest milestone in Django's development to -date: a web framework that a group of perfectionists can truly be proud of. +We've been looking forward to this moment for over three years, and it's +finally here. Django 1.0 represents the largest milestone in Django's +development to date: a web framework that a group of perfectionists can truly +be proud of. Django 1.0 represents over three years of community development as an Open Source project. Django's received contributions from hundreds of developers, been translated into fifty languages, and today is used by developers on every continent and in every kind of job. -An interesting historical note: when Django was first released in July 2005, the -initial released version of Django came from an internal repository at revision -number 8825. Django 1.0 represents revision 8961 of our public repository. It -seems fitting that our 1.0 release comes at the moment where community -contributions overtake those made privately. +An interesting historical note: when Django was first released in July 2005, +the initial released version of Django came from an internal repository at +revision number 8825. Django 1.0 represents revision 8961 of our public +repository. It seems fitting that our 1.0 release comes at the moment where +community contributions overtake those made privately. Stability and forwards-compatibility ==================================== @@ -77,9 +78,9 @@ Refactored admin application ---------------------------- The Django administrative interface (``django.contrib.admin``) has been -completely refactored; admin definitions are now completely decoupled from model -definitions (no more ``class Admin`` declaration in models!), rewritten to use -Django's new form-handling library (introduced in the 0.96 release as +completely refactored; admin definitions are now completely decoupled from +model definitions (no more ``class Admin`` declaration in models!), rewritten +to use Django's new form-handling library (introduced in the 0.96 release as ``django.newforms``, and now available as simply ``django.forms``) and redesigned with extensibility and customization in mind. Full documentation for the admin application is available online in the official Django documentation: @@ -90,8 +91,8 @@ Improved Unicode handling ------------------------- Django's internals have been refactored to use Unicode throughout; this -drastically simplifies the task of dealing with non-Western-European content and -data in Django. Additionally, utility functions have been provided to ease +drastically simplifies the task of dealing with non-Western-European content +and data in Django. Additionally, utility functions have been provided to ease interoperability with third-party libraries and systems which may or may not handle Unicode gracefully. Details are available in Django's Unicode-handling documentation. @@ -102,24 +103,25 @@ An improved ORM --------------- Django's object-relational mapper -- the component which provides the mapping -between Django model classes and your database, and which mediates your database -queries -- has been dramatically improved by a massive refactoring. For most -users of Django this is backwards-compatible; the public-facing API for database -querying underwent a few minor changes, but most of the updates took place in -the ORM's internals. A guide to the changes, including backwards-incompatible -modifications and mentions of new features opened up by this refactoring, is -`available on the Django wiki`__. +between Django model classes and your database, and which mediates your +database queries -- has been dramatically improved by a massive refactoring. +For most users of Django this is backwards-compatible; the public-facing API +for database querying underwent a few minor changes, but most of the updates +took place in the ORM's internals. A guide to the changes, including +backwards-incompatible modifications and mentions of new features opened up by +this refactoring, is `available on the Django wiki`__. __ https://code.djangoproject.com/wiki/QuerysetRefactorBranch Automatic escaping of template variables ---------------------------------------- -To provide improved security against cross-site scripting (XSS) vulnerabilities, -Django's template system now automatically escapes the output of variables. This -behavior is configurable, and allows both variables and larger template -constructs to be marked as safe (requiring no escaping) or unsafe (requiring -escaping). A full guide to this feature is in the documentation for the +To provide improved security against cross-site scripting (XSS) +vulnerabilities, Django's template system now automatically escapes the output +of variables. This behavior is configurable, and allows both variables and +larger template constructs to be marked as safe (requiring no escaping) or +unsafe (requiring escaping). A full guide to this feature is in the +documentation for the :ttag:`autoescape` tag. ``django.contrib.gis`` (GeoDjango) @@ -129,8 +131,8 @@ A project over a year in the making, this adds world-class GIS (`Geographic Information Systems`_) support to Django, in the form of a ``contrib`` application. Its documentation is currently being maintained externally, and will be merged into the main Django documentation shortly. Huge thanks go to -Justin Bronn, Jeremy Dunck, Brett Hoerner and Travis Pinney for their efforts in -creating and completing this feature. +Justin Bronn, Jeremy Dunck, Brett Hoerner and Travis Pinney for their efforts +in creating and completing this feature. See :doc:`GeoDjango </ref/contrib/gis/index>` for details. @@ -142,8 +144,8 @@ Pluggable file storage Django's built-in ``FileField`` and ``ImageField`` now can take advantage of pluggable file-storage backends, allowing extensive customization of where and how uploaded files get stored by Django. For details, see :doc:`the files -documentation </topics/files>`; big thanks go to Marty Alchin for putting in the -hard work to get this completed. +documentation </topics/files>`; big thanks go to Marty Alchin for putting in +the hard work to get this completed. Jython compatibility -------------------- @@ -159,18 +161,20 @@ Jython 2.5 release. Generic relations in forms and admin ------------------------------------ -Classes are now included in ``django.contrib.contenttypes`` which can be used to -support generic relations in both the admin interface and in end-user forms. See -:ref:`the documentation for generic relations <generic-relations>` for details. +Classes are now included in ``django.contrib.contenttypes`` which can be used +to support generic relations in both the admin interface and in end-user forms. +See :ref:`the documentation for generic relations <generic-relations>` for +details. ``INSERT``/``UPDATE`` distinction --------------------------------- Although Django's default behavior of having a model's ``save()`` method -automatically determine whether to perform an ``INSERT`` or an ``UPDATE`` at the -SQL level is suitable for the majority of cases, there are occasional situations -where forcing one or the other is useful. As a result, models can now support an -additional parameter to ``save()`` which can force a specific operation. +automatically determine whether to perform an ``INSERT`` or an ``UPDATE`` at +the SQL level is suitable for the majority of cases, there are occasional +situations where forcing one or the other is useful. As a result, models can +now support an additional parameter to ``save()`` which can force a specific +operation. See :ref:`ref-models-force-insert` for details. @@ -181,8 +185,8 @@ Django's ``CacheMiddleware`` has been split into three classes: ``CacheMiddleware`` itself still exists and retains all of its previous functionality, but it is now built from two separate middleware classes which handle the two parts of caching (inserting into and reading from the cache) -separately, offering additional flexibility for situations where combining these -functions into a single middleware posed problems. +separately, offering additional flexibility for situations where combining +these functions into a single middleware posed problems. Full details, including updated notes on appropriate use, are in :doc:`the caching documentation </topics/cache>`. @@ -197,9 +201,9 @@ increasing its flexibility and customizability. Removal of deprecated features ------------------------------ -A number of features and methods which had previously been marked as deprecated, -and which were scheduled for removal prior to the 1.0 release, are no longer -present in Django. These include imports of the form library from +A number of features and methods which had previously been marked as +deprecated, and which were scheduled for removal prior to the 1.0 release, are +no longer present in Django. These include imports of the form library from ``django.newforms`` (now located simply at ``django.forms``), the ``form_for_model`` and ``form_for_instance`` helper functions (which have been replaced by ``ModelForm``) and a number of deprecated features which were @@ -216,9 +220,9 @@ Multi-table model inheritance with ``to_field`` ----------------------------------------------- If you're using :ref:`multiple table model inheritance -<multi-table-inheritance>`, be aware of this caveat: child models using a custom -``parent_link`` and ``to_field`` will cause database integrity errors. A set of -models like the following are **not valid**:: +<multi-table-inheritance>`, be aware of this caveat: child models using a +custom ``parent_link`` and ``to_field`` will cause database integrity errors. A +set of models like the following are **not valid**:: class Parent(models.Model): name = models.CharField(max_length=10) @@ -237,7 +241,9 @@ Caveats with support of certain databases ----------------------------------------- Django attempts to support as many features as possible on all database -backends. However, not all database backends are alike, and in particular many of the supported database differ greatly from version to version. It's a good idea to checkout our :doc:`notes on supported database </ref/databases>`: +backends. However, not all database backends are alike, and in particular many +of the supported database differ greatly from version to version. It's a good +idea to checkout our :doc:`notes on supported database </ref/databases>`: - :ref:`mysql-notes` - :ref:`sqlite-notes` diff --git a/docs/releases/1.1.2.txt b/docs/releases/1.1.2.txt index 8fdaa09be9..8e1c50c294 100644 --- a/docs/releases/1.1.2.txt +++ b/docs/releases/1.1.2.txt @@ -49,8 +49,8 @@ will improve protection against Cross-Site Request Forgery (CSRF) attacks. This feature requires the use of a new :ttag:`csrf_token` template tag in all forms that Django renders. -To make it easier to support both 1.1.X and 1.2.X versions of Django with -the same templates, we have decided to introduce the :ttag:`csrf_token` template +To make it easier to support both 1.1.X and 1.2.X versions of Django with the +same templates, we have decided to introduce the :ttag:`csrf_token` template tag to the 1.1.X branch. In the 1.1.X branch, :ttag:`csrf_token` does nothing - it has no effect on templates or form processing. However, it means that the same template will work with Django 1.2. diff --git a/docs/releases/1.1.txt b/docs/releases/1.1.txt index 72bb313563..97e33653af 100644 --- a/docs/releases/1.1.txt +++ b/docs/releases/1.1.txt @@ -86,11 +86,12 @@ set by some proxy configurations. It has been demonstrated that this mechanism cannot be made reliable enough for general-purpose use, and that (despite documentation to the contrary) its inclusion in Django may lead application developers to assume that the value of -``REMOTE_ADDR`` is "safe" or in some way reliable as a source of authentication. +``REMOTE_ADDR`` is "safe" or in some way reliable as a source of +authentication. While not directly a security issue, we've decided to remove this middleware -with the Django 1.1 release. It has been replaced with a class that does nothing -other than raise a ``DeprecationWarning``. +with the Django 1.1 release. It has been replaced with a class that does +nothing other than raise a ``DeprecationWarning``. If you've been relying on this middleware, the easiest upgrade path is: @@ -124,10 +125,10 @@ Changes to how model formsets are saved In Django 1.1, :class:`~django.forms.models.BaseModelFormSet` now calls ``ModelForm.save()``. -This is backwards-incompatible if you were modifying ``self.initial`` in a model -formset's ``__init__``, or if you relied on the internal ``_total_form_count`` -or ``_initial_form_count`` attributes of BaseFormSet. Those attributes are now -public methods. +This is backwards-incompatible if you were modifying ``self.initial`` in a +model formset's ``__init__``, or if you relied on the internal +``_total_form_count`` or ``_initial_form_count`` attributes of BaseFormSet. +Those attributes are now public methods. Fixed the ``join`` filter's escaping behavior --------------------------------------------- @@ -224,11 +225,11 @@ A number of features have been added to Django's model layer: "Unmanaged" models ~~~~~~~~~~~~~~~~~~ -You can now control whether or not Django manages the life-cycle of the database -tables for a model using the :attr:`~Options.managed` model option. This -defaults to ``True``, meaning that Django will create the appropriate database -tables in ``syncdb`` and remove them as part of the ``reset`` -command. That is, Django *manages* the database table's lifecycle. +You can now control whether or not Django manages the life-cycle of the +database tables for a model using the :attr:`~Options.managed` model option. +This defaults to ``True``, meaning that Django will create the appropriate +database tables in ``syncdb`` and remove them as part of the ``reset`` command. +That is, Django *manages* the database table's lifecycle. If you set this to ``False``, however, no database table creating or deletion will be automatically performed for this model. This is useful if the model @@ -275,15 +276,16 @@ Test performance improvements .. currentmodule:: django.test -Tests written using Django's :doc:`testing framework </topics/testing/index>` now run -dramatically faster (as much as 10 times faster in many cases). +Tests written using Django's :doc:`testing framework </topics/testing/index>` +now run dramatically faster (as much as 10 times faster in many cases). This was accomplished through the introduction of transaction-based tests: when -using :class:`django.test.TestCase`, your tests will now be run in a transaction -which is rolled back when finished, instead of by flushing and re-populating the -database. This results in an immense speedup for most types of unit tests. See -the documentation for :class:`TestCase` and :class:`TransactionTestCase` for a -full description, and some important notes on database support. +using :class:`django.test.TestCase`, your tests will now be run in a +transaction which is rolled back when finished, instead of by flushing and +re-populating the database. This results in an immense speedup for most types +of unit tests. See the documentation for :class:`TestCase` and +:class:`TransactionTestCase` for a full description, and some important notes +on database support. Test client improvements ------------------------ @@ -339,11 +341,11 @@ URL namespaces Django 1.1 improves :ref:`named URL patterns <naming-url-patterns>` with the introduction of URL "namespaces." -In short, this feature allows the same group of URLs, from the same application, -to be included in a Django URLConf multiple times, with varying (and potentially -nested) named prefixes which will be used when performing reverse resolution. In -other words, reusable applications like Django's admin interface may be -registered multiple times without URL conflicts. +In short, this feature allows the same group of URLs, from the same +application, to be included in a Django URLConf multiple times, with varying +(and potentially nested) named prefixes which will be used when performing +reverse resolution. In other words, reusable applications like Django's admin +interface may be registered multiple times without URL conflicts. For full details, see :ref:`the documentation on defining URL namespaces <topics-http-defining-url-namespaces>`. @@ -391,22 +393,21 @@ Other new features and changes introduced since Django 1.0 include: * The ``include()`` function in Django URLconf modules can now accept sequences of URL patterns (generated by ``patterns()``) in addition to module names. -* Instances of Django forms (see :doc:`the forms overview </topics/forms/index>`) - now have two additional methods, ``hidden_fields()`` and ``visible_fields()``, - which return the list of hidden -- i.e., ``<input type="hidden">`` -- and - visible fields on the form, respectively. +* Instances of Django forms (see :doc:`the forms overview + </topics/forms/index>`) now have two additional methods, ``hidden_fields()`` + and ``visible_fields()``, which return the list of hidden -- i.e., + ``<input type="hidden">`` -- and visible fields on the form, respectively. * The ``redirect_to`` generic view - now accepts an additional keyword argument - ``permanent``. If ``permanent`` is ``True``, the view will emit an HTTP - permanent redirect (status code 301). If ``False``, the view will emit an HTTP - temporary redirect (status code 302). + now accepts an additional keyword argument ``permanent``. If ``permanent`` is + ``True``, the view will emit an HTTP permanent redirect (status code 301). If + ``False``, the view will emit an HTTP temporary redirect (status code 302). -* A new database lookup type -- ``week_day`` -- has been added for ``DateField`` - and ``DateTimeField``. This type of lookup accepts a number between 1 (Sunday) - and 7 (Saturday), and returns objects where the field value matches that day - of the week. See :ref:`the full list of lookup types <field-lookups>` for - details. +* A new database lookup type -- ``week_day`` -- has been added for + ``DateField`` and ``DateTimeField``. This type of lookup accepts a number + between 1 (Sunday) and 7 (Saturday), and returns objects where the field + value matches that day of the week. See :ref:`the full list of lookup types + <field-lookups>` for details. * The ``{% for %}`` tag in Django's template language now accepts an optional ``{% empty %}`` clause, to be displayed when ``{% for %}`` is asked to loop @@ -453,7 +454,7 @@ Django: * :doc:`How to contribute to Django </internals/contributing/index>` Contributions on any level -- developing code, writing documentation or simply -triaging tickets and helping to test proposed bugfixes -- are always welcome and -appreciated. +triaging tickets and helping to test proposed bugfixes -- are always welcome +and appreciated. And that's the way it is. diff --git a/docs/releases/1.10.3.txt b/docs/releases/1.10.3.txt index 6cdecb74f9..d1c842e058 100644 --- a/docs/releases/1.10.3.txt +++ b/docs/releases/1.10.3.txt @@ -26,7 +26,7 @@ DNS rebinding vulnerability when ``DEBUG=True`` Older versions of Django don't validate the ``Host`` header against ``settings.ALLOWED_HOSTS`` when ``settings.DEBUG=True``. This makes them vulnerable to a `DNS rebinding attack -<https://benmmurphy.github.io/blog/2016/07/11/rails-webconsole-dns-rebinding/>`_. +<https://benmmurphy.github.io/blog/2016/07/11/rails-webconsole-dns-rebinding/>`__. While Django doesn't ship a module that allows remote code execution, this is at least a cross-site scripting vector, which could be quite serious if diff --git a/docs/releases/1.10.txt b/docs/releases/1.10.txt index 7d22efbcf9..0c0da89643 100644 --- a/docs/releases/1.10.txt +++ b/docs/releases/1.10.txt @@ -92,9 +92,10 @@ Minor features it easier to add custom tools in this case. * The :class:`~django.contrib.admin.models.LogEntry` model now stores change - messages in a JSON structure so that the message can be dynamically translated - using the current active language. A new ``LogEntry.get_change_message()`` - method is now the preferred way of retrieving the change message. + messages in a JSON structure so that the message can be dynamically + translated using the current active language. A new + ``LogEntry.get_change_message()`` method is now the preferred way of + retrieving the change message. * Selected objects for fields in ``ModelAdmin.raw_id_fields`` now have a link to object's change form. @@ -286,10 +287,10 @@ Forms a ``minlength`` attribute if the field has a ``min_length``. * Required form fields now have the ``required`` HTML attribute. Set the new - :attr:`Form.use_required_attribute <django.forms.Form.use_required_attribute>` - attribute to ``False`` to disable it. The ``required`` attribute isn't - included on forms of formsets because the browser validation may not be - correct when adding and deleting formsets. + :attr:`Form.use_required_attribute + <django.forms.Form.use_required_attribute>` attribute to ``False`` to disable + it. The ``required`` attribute isn't included on forms of formsets because + the browser validation may not be correct when adding and deleting formsets. Generic Views ~~~~~~~~~~~~~ @@ -387,12 +388,12 @@ Models * Reverse foreign keys from proxy models are now propagated to their concrete class. The reverse relation attached by a :class:`~django.db.models.ForeignKey` pointing to a proxy model is now - accessible as a descriptor on the proxied model class and may be referenced in - queryset filtering. + accessible as a descriptor on the proxied model class and may be referenced + in queryset filtering. * The new :meth:`Field.rel_db_type() <django.db.models.Field.rel_db_type>` - method returns the database column data type for fields such as ``ForeignKey`` - and ``OneToOneField`` that point to another field. + method returns the database column data type for fields such as + ``ForeignKey`` and ``OneToOneField`` that point to another field. * The :attr:`~django.db.models.Func.arity` class attribute is added to :class:`~django.db.models.Func`. This attribute can be used to set the number @@ -755,10 +756,9 @@ custom lookup for it. For example:: aggregate function now returns a ``float`` instead of ``decimal.Decimal``. (It's still wrapped in a measure of square meters.) -* The default :class:`~django.contrib.gis.geos.GEOSGeometry` representation (WKT - output) is trimmed by default. That is, instead of - ``POINT (23.0000000000000000 5.5000000000000000)``, you'll get - ``POINT (23 5.5)``. +* The default :class:`~django.contrib.gis.geos.GEOSGeometry` representation + (WKT output) is trimmed by default. That is, instead of ``POINT + (23.0000000000000000 5.5000000000000000)``, you'll get ``POINT (23 5.5)``. Maximum size of a request body and the number of GET/POST parameters is limited ------------------------------------------------------------------------------- @@ -903,8 +903,8 @@ Miscellaneous might be possible to use :attr:`~django.db.models.FileField.upload_to` also. * The subject of mail sent by ``AdminEmailHandler`` is no longer truncated at - 989 characters. If you were counting on a limited length, truncate the subject - yourself. + 989 characters. If you were counting on a limited length, truncate the + subject yourself. * Private expressions ``django.db.models.expressions.Date`` and ``DateTime`` are removed. The new :class:`~django.db.models.functions.Trunc` expressions diff --git a/docs/releases/1.11.13.txt b/docs/releases/1.11.13.txt index d5a72bb529..e6b1e83d01 100644 --- a/docs/releases/1.11.13.txt +++ b/docs/releases/1.11.13.txt @@ -18,5 +18,5 @@ Bugfixes * Fixed a regression in Django 1.11.12 where ``QuerySet.values()`` or ``values_list()`` after combining an annotated and unannotated queryset with - ``union()``, ``difference()``, or ``intersection()`` crashed due to mismatching - columns (:ticket:`29286`). + ``union()``, ``difference()``, or ``intersection()`` crashed due to + mismatching columns (:ticket:`29286`). diff --git a/docs/releases/1.11.5.txt b/docs/releases/1.11.5.txt index dda3489b93..1c73430afa 100644 --- a/docs/releases/1.11.5.txt +++ b/docs/releases/1.11.5.txt @@ -23,7 +23,8 @@ Bugfixes * Added compatibility for ``cx_Oracle`` 6 (:ticket:`28498`). -* Fixed select widget rendering when option values are tuples (:ticket:`28502`). +* Fixed select widget rendering when option values are tuples + (:ticket:`28502`). * Django 1.11 inadvertently changed the sequence and trigger naming scheme on Oracle. This causes errors on INSERTs for some tables if diff --git a/docs/releases/1.11.9.txt b/docs/releases/1.11.9.txt index a7939a6028..2eec57d528 100644 --- a/docs/releases/1.11.9.txt +++ b/docs/releases/1.11.9.txt @@ -9,8 +9,8 @@ Django 1.11.9 fixes several bugs in 1.11.8. Bugfixes ======== -* Fixed a regression in Django 1.11 that added newlines between ``MultiWidget``'s - subwidgets (:ticket:`28890`). +* Fixed a regression in Django 1.11 that added newlines between + ``MultiWidget``'s subwidgets (:ticket:`28890`). * Fixed incorrect class-based model index name generation for models with quoted ``db_table`` (:ticket:`28876`). diff --git a/docs/releases/1.11.txt b/docs/releases/1.11.txt index 4eb244c336..5a9baa93a2 100644 --- a/docs/releases/1.11.txt +++ b/docs/releases/1.11.txt @@ -104,8 +104,8 @@ Minor features 20%. * The :class:`~django.contrib.auth.views.LoginView` and - :class:`~django.contrib.auth.views.LogoutView` class-based views supersede the - deprecated ``login()`` and ``logout()`` function-based views. + :class:`~django.contrib.auth.views.LogoutView` class-based views supersede + the deprecated ``login()`` and ``logout()`` function-based views. * The :class:`~django.contrib.auth.views.PasswordChangeView`, :class:`~django.contrib.auth.views.PasswordChangeDoneView`, @@ -115,8 +115,8 @@ Minor features :class:`~django.contrib.auth.views.PasswordResetCompleteView` class-based views supersede the deprecated ``password_change()``, ``password_change_done()``, ``password_reset()``, ``password_reset_done()``, - ``password_reset_confirm()``, and ``password_reset_complete()`` function-based - views. + ``password_reset_confirm()``, and ``password_reset_complete()`` + function-based views. * The new ``post_reset_login`` attribute for :class:`~django.contrib.auth.views.PasswordResetConfirmView` allows @@ -143,17 +143,18 @@ Minor features * Added password validators ``help_text`` to :class:`~django.contrib.auth.forms.UserCreationForm`. -* The ``HttpRequest`` is now passed to :func:`~django.contrib.auth.authenticate` - which in turn passes it to the authentication backend if it accepts a - ``request`` argument. +* The ``HttpRequest`` is now passed to + :func:`~django.contrib.auth.authenticate` which in turn passes it to the + authentication backend if it accepts a ``request`` argument. * The :func:`~django.contrib.auth.signals.user_login_failed` signal now receives a ``request`` argument. * :class:`~django.contrib.auth.forms.PasswordResetForm` supports custom user - models that use an email field named something other than ``'email'``. - Set :attr:`CustomUser.EMAIL_FIELD - <django.contrib.auth.models.CustomUser.EMAIL_FIELD>` to the name of the field. + models that use an email field named something other than ``'email'``. Set + :attr:`CustomUser.EMAIL_FIELD + <django.contrib.auth.models.CustomUser.EMAIL_FIELD>` to the name of the + field. * :func:`~django.contrib.auth.get_user_model` can now be called at import time, even in modules that define models. @@ -231,10 +232,10 @@ Minor features Cache ~~~~~ -* Memcached backends now pass the contents of :setting:`OPTIONS <CACHES-OPTIONS>` - as keyword arguments to the client constructors, allowing for more advanced - control of client behavior. See the :ref:`cache arguments <cache_arguments>` - documentation for examples. +* Memcached backends now pass the contents of + :setting:`OPTIONS <CACHES-OPTIONS>` as keyword arguments to the client + constructors, allowing for more advanced control of client behavior. See the + :ref:`cache arguments <cache_arguments>` documentation for examples. * Memcached backends now allow defining multiple servers as a comma-delimited string in :setting:`LOCATION <CACHES-LOCATION>`, for convenience with @@ -506,7 +507,8 @@ backends. * The ``DatabaseOperations.datetime_cast_time_sql()`` method is added to support the :lookup:`time` lookup. It accepts a ``field_name`` and ``tzname`` - arguments and returns the SQL necessary to cast a datetime value to time value. + arguments and returns the SQL necessary to cast a datetime value to time + value. * To enable ``FOR UPDATE SKIP LOCKED`` support, set ``DatabaseFeatures.has_select_for_update_skip_locked = True``. @@ -831,9 +833,9 @@ Miscellaneous ``contrib.auth.views.logout_then_login()`` is deprecated. * ``contrib.auth``’s ``password_change()``, ``password_change_done()``, - ``password_reset()``, ``password_reset_done()``, ``password_reset_confirm()``, - and ``password_reset_complete()`` function-based views are deprecated in favor - of new class-based views + ``password_reset()``, ``password_reset_done()``, + ``password_reset_confirm()``, and ``password_reset_complete()`` + function-based views are deprecated in favor of new class-based views :class:`~django.contrib.auth.views.PasswordChangeView`, :class:`~django.contrib.auth.views.PasswordChangeDoneView`, :class:`~django.contrib.auth.views.PasswordResetView`, diff --git a/docs/releases/1.2.txt b/docs/releases/1.2.txt index cff793047e..b171478943 100644 --- a/docs/releases/1.2.txt +++ b/docs/releases/1.2.txt @@ -49,8 +49,8 @@ These are just the highlights; full details and a complete list of features Wherever possible these features have been introduced in a backwards-compatible manner per :doc:`our API stability policy </misc/api-stability>` policy. -However, a handful of features *have* changed in ways that, for some users, will be -backwards-incompatible. The big changes are: +However, a handful of features *have* changed in ways that, for some users, +will be backwards-incompatible. The big changes are: * Support for Python 2.3 has been dropped. See the full notes below. @@ -139,13 +139,13 @@ perform any validation of the instance's data. Improved CSRF protection ------------------------ -Django now has much improved protection against :doc:`Cross-Site Request Forgery -(CSRF) attacks</ref/csrf>`. This type of attack occurs when a malicious +Django now has much improved protection against :doc:`Cross-Site Request +Forgery (CSRF) attacks</ref/csrf>`. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user -who visits the malicious site in their browser. A related type of attack, "login -CSRF," where an attacking site tricks a user's browser into logging into a site -with someone else's credentials, is also covered. +who visits the malicious site in their browser. A related type of attack, +"login CSRF," where an attacking site tricks a user's browser into logging into +a site with someone else's credentials, is also covered. .. _messages-framework: @@ -184,8 +184,8 @@ Relaxed requirements for usernames ---------------------------------- The built-in :class:`~django.contrib.auth.models.User` model's -:attr:`~django.contrib.auth.models.User.username` field now allows a wider range -of characters, including ``@``, ``+``, ``.`` and ``-`` characters. +:attr:`~django.contrib.auth.models.User.username` field now allows a wider +range of characters, including ``@``, ``+``, ``.`` and ``-`` characters. Email backends -------------- @@ -297,8 +297,8 @@ Both the :djadmin:`test` subcommand of ``django-admin.py`` and the ``--failfast`` option. When specified, this option causes the test runner to exit after encountering a failure instead of continuing with the test run. In addition, the handling of ``Ctrl-C`` during a test run has been improved to -trigger a graceful exit from the test run that reports details of the tests that -were run before the interruption. +trigger a graceful exit from the test run that reports details of the tests +that were run before the interruption. ``BigIntegerField`` ------------------- @@ -308,11 +308,11 @@ Models can now use a 64-bit :class:`~django.db.models.BigIntegerField` type. Improved localization --------------------- -Django's :doc:`internationalization framework </topics/i18n/index>` has been expanded -with locale-aware formatting and form processing. That means, if enabled, dates -and numbers on templates will be displayed using the format specified for the -current locale. Django will also use localized formats when parsing data in -forms. See :doc:`/topics/i18n/formatting` for more details. +Django's :doc:`internationalization framework </topics/i18n/index>` has been +expanded with locale-aware formatting and form processing. That means, if +enabled, dates and numbers on templates will be displayed using the format +specified for the current locale. Django will also use localized formats when +parsing data in forms. See :doc:`/topics/i18n/formatting` for more details. ``readonly_fields`` in ``ModelAdmin`` ------------------------------------- @@ -631,24 +631,24 @@ wrapping other objects of unknown type. In Django 1.1 and earlier, it handled introspection in a non-standard way, depending on wrapped objects implementing a public method named -``get_all_members()``. Since this could easily lead to name clashes, it has been -changed to use the standard Python introspection method, involving +``get_all_members()``. Since this could easily lead to name clashes, it has +been changed to use the standard Python introspection method, involving ``__members__`` and ``__dir__()``. If you used ``LazyObject`` in your own code -and implemented the ``get_all_members()`` method for wrapped objects, you'll need -to make a couple of changes: +and implemented the ``get_all_members()`` method for wrapped objects, you'll +need to make a couple of changes: -First, if your class does not have special requirements for introspection (i.e., -you have not implemented ``__getattr__()`` or other methods that allow for -attributes not discoverable by normal mechanisms), you can simply remove the -``get_all_members()`` method. The default implementation on ``LazyObject`` will -do the right thing. +First, if your class does not have special requirements for introspection +(i.e., you have not implemented ``__getattr__()`` or other methods that allow +for attributes not discoverable by normal mechanisms), you can simply remove +the ``get_all_members()`` method. The default implementation on ``LazyObject`` +will do the right thing. If you have more complex requirements for introspection, first rename the ``get_all_members()`` method to ``__dir__()``. This is the standard -introspection method for Python 2.6 and above. If you require support for Python -versions earlier than 2.6, add the following code to the class:: +introspection method for Python 2.6 and above. If you require support for +Python versions earlier than 2.6, add the following code to the class:: __members__ = property(lambda self: self.__dir__()) @@ -743,9 +743,9 @@ will need to update your FormSet and/or admin definitions. ``email_re`` ------------ -An undocumented regular expression for validating email addresses has been moved -from ``django.form.fields`` to ``django.core.validators``. You will need to -update your imports if you are using it. +An undocumented regular expression for validating email addresses has been +moved from ``django.form.fields`` to ``django.core.validators``. You will need +to update your imports if you are using it. .. _deprecated-features-1.2: @@ -911,7 +911,8 @@ User Messages API The API for storing messages in the user ``Message`` model (via ``user.message_set.create``) is now deprecated and will be removed in Django -1.4 according to the standard :doc:`release process </internals/release-process>`. +1.4 according to the standard +:doc:`release process </internals/release-process>`. To upgrade your code, you need to replace any instances of this:: diff --git a/docs/releases/1.3.6.txt b/docs/releases/1.3.6.txt index 5d25bdacd8..216e865948 100644 --- a/docs/releases/1.3.6.txt +++ b/docs/releases/1.3.6.txt @@ -16,11 +16,11 @@ Host header poisoning Some parts of Django -- independent of end-user-written applications -- make use of full URLs, including domain name, which are generated from the HTTP Host header. Django's documentation has for some time contained notes advising users -on how to configure web servers to ensure that only valid Host headers can reach -the Django application. However, it has been reported to us that even with the -recommended web server configurations there are still techniques available for -tricking many common web servers into supplying the application with an -incorrect and possibly malicious Host header. +on how to configure web servers to ensure that only valid Host headers can +reach the Django application. However, it has been reported to us that even +with the recommended web server configurations there are still techniques +available for tricking many common web servers into supplying the application +with an incorrect and possibly malicious Host header. For this reason, Django 1.3.6 adds a new setting, ``ALLOWED_HOSTS``, which should contain an explicit list of valid host/domain names for this site. A @@ -32,8 +32,8 @@ The default value for this setting in Django 1.3.6 is ``['*']`` (matching any host), for backwards-compatibility, but we strongly encourage all sites to set a more restrictive value. -This host validation is disabled when ``DEBUG`` is ``True`` or when running tests. - +This host validation is disabled when ``DEBUG`` is ``True`` or when running +tests. XML deserialization =================== diff --git a/docs/releases/1.3.txt b/docs/releases/1.3.txt index 310a66f198..8ca4726e92 100644 --- a/docs/releases/1.3.txt +++ b/docs/releases/1.3.txt @@ -69,10 +69,10 @@ provided, along with a completely generic view base class that can be used as the basis for reusable applications that can be easily extended. -See :doc:`the documentation on class-based generic views</topics/class-based-views/index>` -for more details. There is also a document to help you `convert -your function-based generic views to class-based -views <https://raw.githubusercontent.com/django/django/ea9dc9f4b03ae034c1dc080730422dda7a9c2e47/docs/topics/generic-views-migration.txt>`_. +See :doc:`the documentation on class-based generic views +</topics/class-based-views/index>` for more details. There is also a document +to help you `convert your function-based generic views to class-based views +<https://raw.githubusercontent.com/django/django/ea9dc9f4b03ae034c1dc080730422dda7a9c2e47/docs/topics/generic-views-migration.txt>`__. Logging ------- @@ -520,9 +520,9 @@ behavior: u'<bound method User.get_full_name of <... This has been resolved in Django 1.3 - the result in both cases will be ``u'Joe -Bloggs'``. Although the previous behavior was not useful for a template language -designed for web designers, and was never deliberately supported, it is possible -that some templates may be broken by this change. +Bloggs'``. Although the previous behavior was not useful for a template +language designed for web designers, and was never deliberately supported, it +is possible that some templates may be broken by this change. Use of custom SQL to load initial data in tests ----------------------------------------------- @@ -580,9 +580,9 @@ gettext domain): * The ``locale`` subdirectory of the directory containing the settings, that usually coincides with and is known as the *project directory* is being deprecated in this release as a source of translations. (the precedence of - these translations is intermediate between applications and :setting:`LOCALE_PATHS` - translations). See the `corresponding deprecated features section`_ - of this document. + these translations is intermediate between applications and + :setting:`LOCALE_PATHS` translations). See the `corresponding deprecated + features section`_ of this document. For translatable literals found in JavaScript code (``'djangojs'`` gettext domain): diff --git a/docs/releases/1.4.13.txt b/docs/releases/1.4.13.txt index 54f131e7d3..746900ca0f 100644 --- a/docs/releases/1.4.13.txt +++ b/docs/releases/1.4.13.txt @@ -23,10 +23,10 @@ types. Therefore, Django would remove the header if the request was made by Internet Explorer. To remedy this, the special behavior for these older Internet Explorer versions -has been removed, and the ``Vary`` header is no longer stripped from the response. -In addition, modifications to the ``Cache-Control`` header for all Internet Explorer -requests with a ``Content-Disposition`` header have also been removed as they -were found to have similar issues. +has been removed, and the ``Vary`` header is no longer stripped from the +response. In addition, modifications to the ``Cache-Control`` header for all +Internet Explorer requests with a ``Content-Disposition`` header have also been +removed as they were found to have similar issues. Malformed redirect URLs from user input not correctly validated =============================================================== @@ -43,5 +43,5 @@ The security checks for these redirects (namely URLs, such as ``http:\\\\\\djangoproject.com``, which are accepted by some browsers with more liberal URL parsing. -To remedy this, the validation in ``is_safe_url()`` has been tightened to be able -to handle and correctly validate these malformed URLs. +To remedy this, the validation in ``is_safe_url()`` has been tightened to be +able to handle and correctly validate these malformed URLs. diff --git a/docs/releases/1.4.14.txt b/docs/releases/1.4.14.txt index 5e8f0c16b8..37f6e50d2e 100644 --- a/docs/releases/1.4.14.txt +++ b/docs/releases/1.4.14.txt @@ -24,20 +24,20 @@ File upload denial-of-service Before this release, Django's file upload handing in its default configuration may degrade to producing a huge number of ``os.stat()`` system calls when a -duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may produce -a huge data-dependent slowdown that slowly worsens over time. The net result is -that given enough time, a user with the ability to upload files can cause poor -performance in the upload handler, eventually causing it to become very slow -simply by uploading 0-byte files. At this point, even a slow network connection -and few HTTP requests would be all that is necessary to make a site unavailable. +duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may +produce a huge data-dependent slowdown that slowly worsens over time. The net +result is that given enough time, a user with the ability to upload files can +cause poor performance in the upload handler, eventually causing it to become +very slow simply by uploading 0-byte files. At this point, even a slow network +connection and few HTTP requests would be all that is necessary to make a site +unavailable. -We've remedied the issue by changing the algorithm for generating file names -if a file with the uploaded name already exists. -:meth:`Storage.get_available_name() +We've remedied the issue by changing the algorithm for generating file names if +a file with the uploaded name already exists. :meth:`Storage.get_available_name <django.core.files.storage.Storage.get_available_name>` now appends an underscore plus a random 7 character alphanumeric string (e.g. ``"_x3a1gho"``), -rather than iterating through an underscore followed by a number (e.g. ``"_1"``, -``"_2"``, etc.). +rather than iterating through an underscore followed by a number (e.g. +``"_1"``, ``"_2"``, etc.). ``RemoteUserMiddleware`` session hijacking ========================================== diff --git a/docs/releases/1.4.2.txt b/docs/releases/1.4.2.txt index 9c70082df1..de7b272ebf 100644 --- a/docs/releases/1.4.2.txt +++ b/docs/releases/1.4.2.txt @@ -50,9 +50,11 @@ Other bugfixes and changes * Subclass HTMLParser only for appropriate Python versions (#18239). * Added batch_size argument to qs.bulk_create() (#17788). -* Fixed a small regression in the admin filters where wrongly formatted dates passed as url parameters caused an unhandled ValidationError (#18530). +* Fixed a small regression in the admin filters where wrongly formatted dates + passed as url parameters caused an unhandled ValidationError (#18530). * Fixed an endless loop bug when accessing permissions in templates (#18979) * Fixed some Python 2.5 compatibility issues * Fixed an issue with quoted filenames in Content-Disposition header (#19006) -* Made the context option in ``trans`` and ``blocktrans`` tags accept literals wrapped in single quotes (#18881). +* Made the context option in ``trans`` and ``blocktrans`` tags accept literals + wrapped in single quotes (#18881). * Numerous documentation improvements and fixes. diff --git a/docs/releases/1.4.4.txt b/docs/releases/1.4.4.txt index 8e6b5b287e..5b5ab146d7 100644 --- a/docs/releases/1.4.4.txt +++ b/docs/releases/1.4.4.txt @@ -17,11 +17,11 @@ Host header poisoning Some parts of Django -- independent of end-user-written applications -- make use of full URLs, including domain name, which are generated from the HTTP Host header. Django's documentation has for some time contained notes advising users -on how to configure web servers to ensure that only valid Host headers can reach -the Django application. However, it has been reported to us that even with the -recommended web server configurations there are still techniques available for -tricking many common web servers into supplying the application with an -incorrect and possibly malicious Host header. +on how to configure web servers to ensure that only valid Host headers can +reach the Django application. However, it has been reported to us that even +with the recommended web server configurations there are still techniques +available for tricking many common web servers into supplying the application +with an incorrect and possibly malicious Host header. For this reason, Django 1.4.4 adds a new setting, ``ALLOWED_HOSTS``, containing an explicit list of valid host/domain names for this site. A request with a @@ -33,7 +33,8 @@ The default value for this setting in Django 1.4.4 is ``['*']`` (matching any host), for backwards-compatibility, but we strongly encourage all sites to set a more restrictive value. -This host validation is disabled when ``DEBUG`` is ``True`` or when running tests. +This host validation is disabled when ``DEBUG`` is ``True`` or when running +tests. XML deserialization @@ -82,7 +83,8 @@ to users with change permission for that model. Other bugfixes and changes ========================== -* Prevented transaction state from leaking from one request to the next (#19707). +* Prevented transaction state from leaking from one request to the next + (#19707). * Changed an SQL command syntax to be MySQL 4 compatible (#19702). * Added backwards-compatibility with old unsalted MD5 passwords (#18144). * Numerous documentation improvements and fixes. diff --git a/docs/releases/1.4.txt b/docs/releases/1.4.txt index c5dd134f36..94b16b6500 100644 --- a/docs/releases/1.4.txt +++ b/docs/releases/1.4.txt @@ -21,10 +21,11 @@ handling date/times. When enabled, this Django will store date/times in UTC, use timezone-aware objects internally, and translate them to users' local timezones for display. -If you're upgrading an existing project to Django 1.4, switching to the timezone -aware mode may take some care: the new mode disallows some rather sloppy -behavior that used to be accepted. We encourage anyone who's upgrading to check -out the :ref:`timezone migration guide <time-zones-migration-guide>` and the +If you're upgrading an existing project to Django 1.4, switching to the +timezone aware mode may take some care: the new mode disallows some rather +sloppy behavior that used to be accepted. We encourage anyone who's upgrading +to check out the :ref:`timezone migration guide <time-zones-migration-guide>` +and the :ref:`timezone FAQ <time-zones-faq>` for useful pointers. Other notable new features in Django 1.4 include: @@ -63,9 +64,9 @@ required Python version. Django is tested and supported on Python 2.5, 2.6 and 2.7. This change should affect only a small number of Django users, as most -operating-system vendors today are shipping Python 2.5 or newer as their default -version. If you're still using Python 2.4, however, you'll need to stick to -Django 1.3 until you can upgrade. Per :doc:`our support policy +operating-system vendors today are shipping Python 2.5 or newer as their +default version. If you're still using Python 2.4, however, you'll need to +stick to Django 1.3 until you can upgrade. Per :doc:`our support policy </internals/release-process>`, Django 1.3 will continue to receive security support until the release of Django 1.5. @@ -274,10 +275,10 @@ Improved password hashing Django's auth system (``django.contrib.auth``) stores passwords using a one-way algorithm. Django 1.3 uses the SHA1_ algorithm, but increasing processor speeds and theoretical attacks have revealed that SHA1 isn't as secure as we'd like. -Thus, Django 1.4 introduces a new password storage system: by default Django now -uses the PBKDF2_ algorithm (as recommended by NIST_). You can also easily choose -a different algorithm (including the popular bcrypt_ algorithm). For more -details, see :ref:`auth_password_storage`. +Thus, Django 1.4 introduces a new password storage system: by default Django +now uses the PBKDF2_ algorithm (as recommended by NIST_). You can also easily +choose a different algorithm (including the popular bcrypt_ algorithm). For +more details, see :ref:`auth_password_storage`. .. _sha1: https://en.wikipedia.org/wiki/SHA1 .. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2 @@ -306,8 +307,8 @@ Multiple sort in admin interface -------------------------------- The admin change list now supports sorting on multiple columns. It respects all -elements of the :attr:`~django.contrib.admin.ModelAdmin.ordering` attribute, and -sorting on multiple columns by clicking on headers is designed to mimic the +elements of the :attr:`~django.contrib.admin.ModelAdmin.ordering` attribute, +and sorting on multiple columns by clicking on headers is designed to mimic the behavior of desktop GUIs. We also added a :meth:`~django.contrib.admin.ModelAdmin.get_ordering` method for specifying the ordering dynamically (i.e., depending on the request). @@ -431,8 +432,8 @@ number of positional or keyword arguments. For example:: ... return ... -Then, in the template, any number of arguments may be passed to the template tag. -For example: +Then, in the template, any number of arguments may be passed to the template +tag. For example: .. code-block:: html+django @@ -495,8 +496,8 @@ CSRF improvements We've made various improvements to our CSRF features, including the :func:`~django.views.decorators.csrf.ensure_csrf_cookie` decorator, which can help with AJAX-heavy sites; protection for PUT and DELETE requests; and the -:setting:`CSRF_COOKIE_SECURE` and :setting:`CSRF_COOKIE_PATH` settings, which can -improve the security and usefulness of CSRF protection. See the :doc:`CSRF +:setting:`CSRF_COOKIE_SECURE` and :setting:`CSRF_COOKIE_PATH` settings, which +can improve the security and usefulness of CSRF protection. See the :doc:`CSRF docs </ref/csrf>` for more information. Error report filtering @@ -593,8 +594,8 @@ Django 1.4 also includes several smaller improvements worth noting: MySQL with the InnoDB database engine. * A new 403 response handler has been added as - ``'django.views.defaults.permission_denied'``. You can set your own handler by - setting the value of :data:`django.conf.urls.handler403`. See the + ``'django.views.defaults.permission_denied'``. You can set your own handler + by setting the value of :data:`django.conf.urls.handler403`. See the documentation about :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>` for more information. @@ -609,9 +610,9 @@ Django 1.4 also includes several smaller improvements worth noting: * The :ttag:`if` template tag now supports ``{% elif %}`` clauses. * If your Django app is behind a proxy, you might find the new - :setting:`SECURE_PROXY_SSL_HEADER` setting useful. It solves the problem of your - proxy "eating" the fact that a request came in via HTTPS. But only use this - setting if you know what you're doing. + :setting:`SECURE_PROXY_SSL_HEADER` setting useful. It solves the problem of + your proxy "eating" the fact that a request came in via HTTPS. But only use + this setting if you know what you're doing. * A new, plain-text, version of the HTTP 500 status code internal error page served when :setting:`DEBUG` is ``True`` is now sent to the client when @@ -634,8 +635,8 @@ Django 1.4 also includes several smaller improvements worth noting: ``DISTINCT ON``. The ``distinct()`` ``QuerySet`` method now accepts an optional list of model - field names. If specified, then the ``DISTINCT`` statement is limited to these - fields. This is only supported in PostgreSQL. + field names. If specified, then the ``DISTINCT`` statement is limited to + these fields. This is only supported in PostgreSQL. For more details, see the documentation for :meth:`~django.db.models.query.QuerySet.distinct`. @@ -797,10 +798,11 @@ instance: * ``contrib.comments`` form security hash - * Consequences: The user will see the validation error "Security hash failed." + * Consequences: The user will see the validation error "Security hash + failed." - * Time period: The amount of time you expect users to take filling out comment - forms. + * Time period: The amount of time you expect users to take filling out + comment forms. * ``FormWizard`` security hash @@ -1026,9 +1028,9 @@ keyword argument. ``django.core.template_loaders`` -------------------------------- -This was an alias to ``django.template.loader`` since 2005, and we've removed it -without emitting a warning due to the length of the deprecation. If your code -still referenced this, please use ``django.template.loader`` instead. +This was an alias to ``django.template.loader`` since 2005, and we've removed +it without emitting a warning due to the length of the deprecation. If your +code still referenced this, please use ``django.template.loader`` instead. ``django.db.models.fields.URLField.verify_exists`` -------------------------------------------------- @@ -1147,11 +1149,12 @@ changed, which may break any custom tags that use this class. Loading some incomplete fixtures no longer works ------------------------------------------------ -Prior to 1.4, a default value was inserted for fixture objects that were missing -a specific date or datetime value when auto_now or auto_now_add was set for the -field. This was something that should not have worked, and in 1.4 loading such -incomplete fixtures will fail. Because fixtures are a raw import, they should -explicitly specify all field values, regardless of field options on the model. +Prior to 1.4, a default value was inserted for fixture objects that were +missing a specific date or datetime value when auto_now or auto_now_add was set +for the field. This was something that should not have worked, and in 1.4 +loading such incomplete fixtures will fail. Because fixtures are a raw import, +they should explicitly specify all field values, regardless of field options on +the model. Development Server Multithreading --------------------------------- @@ -1254,16 +1257,17 @@ disable this backward-compatibility shim and deprecation warning. ----------------------------- Until Django 1.3, the ``include()``, ``patterns()``, and ``url()`` functions, -plus :data:`~django.conf.urls.handler404` and :data:`~django.conf.urls.handler500` -were located in a ``django.conf.urls.defaults`` module. +plus :data:`~django.conf.urls.handler404` and +:data:`~django.conf.urls.handler500` were located in a +``django.conf.urls.defaults`` module. In Django 1.4, they live in :mod:`django.conf.urls`. ``django.contrib.databrowse`` ----------------------------- -Databrowse has not seen active development for some time, and this does not show -any sign of changing. There had been a suggestion for a `GSOC project`_ to +Databrowse has not seen active development for some time, and this does not +show any sign of changing. There had been a suggestion for a `GSOC project`_ to integrate the functionality of databrowse into the admin, but no progress was made. While Databrowse has been deprecated, an enhancement of ``django.contrib.admin`` providing a similar feature set is still possible. @@ -1301,9 +1305,9 @@ path is needed due to use in existing ``manage.py`` files. ``is_safe`` and ``needs_autoescape`` attributes of template filters ------------------------------------------------------------------- -Two flags, ``is_safe`` and ``needs_autoescape``, define how each template filter -interacts with Django's auto-escaping behavior. They used to be attributes of -the filter function:: +Two flags, ``is_safe`` and ``needs_autoescape``, define how each template +filter interacts with Django's auto-escaping behavior. They used to be +attributes of the filter function:: @register.filter def noop(value): @@ -1321,7 +1325,8 @@ Now, the flags are keyword arguments of :meth:`@register.filter def noop(value): return value -See :ref:`filters and auto-escaping <filters-auto-escaping>` for more information. +See :ref:`filters and auto-escaping <filters-auto-escaping>` for more +information. Wildcard expansion of application names in ``INSTALLED_APPS`` ------------------------------------------------------------- diff --git a/docs/releases/1.5.1.txt b/docs/releases/1.5.1.txt index 66d7899762..e45a0d8260 100644 --- a/docs/releases/1.5.1.txt +++ b/docs/releases/1.5.1.txt @@ -4,8 +4,8 @@ Django 1.5.1 release notes *March 28, 2013* -This is Django 1.5.1, a bugfix release for Django 1.5. It's completely backwards -compatible with Django 1.5, but includes a handful of fixes. +This is Django 1.5.1, a bugfix release for Django 1.5. It's completely +backwards compatible with Django 1.5, but includes a handful of fixes. The biggest fix is for a memory leak introduced in Django 1.5. Under certain circumstances, repeated iteration over querysets could leak memory - sometimes diff --git a/docs/releases/1.5.8.txt b/docs/releases/1.5.8.txt index 53b0c7d486..e4c56588e7 100644 --- a/docs/releases/1.5.8.txt +++ b/docs/releases/1.5.8.txt @@ -23,10 +23,10 @@ types. Therefore, Django would remove the header if the request was made by Internet Explorer. To remedy this, the special behavior for these older Internet Explorer versions -has been removed, and the ``Vary`` header is no longer stripped from the response. -In addition, modifications to the ``Cache-Control`` header for all Internet Explorer -requests with a ``Content-Disposition`` header have also been removed as they -were found to have similar issues. +has been removed, and the ``Vary`` header is no longer stripped from the +response. In addition, modifications to the ``Cache-Control`` header for all +Internet Explorer requests with a ``Content-Disposition`` header have also been +removed as they were found to have similar issues. Malformed redirect URLs from user input not correctly validated =============================================================== @@ -43,5 +43,5 @@ The security checks for these redirects (namely URLs, such as ``http:\\\\\\djangoproject.com``, which are accepted by some browsers with more liberal URL parsing. -To remedy this, the validation in ``is_safe_url()`` has been tightened to be able -to handle and correctly validate these malformed URLs. +To remedy this, the validation in ``is_safe_url()`` has been tightened to be +able to handle and correctly validate these malformed URLs. diff --git a/docs/releases/1.5.9.txt b/docs/releases/1.5.9.txt index a2ccc16567..2b21b43e8f 100644 --- a/docs/releases/1.5.9.txt +++ b/docs/releases/1.5.9.txt @@ -24,20 +24,20 @@ File upload denial-of-service Before this release, Django's file upload handing in its default configuration may degrade to producing a huge number of ``os.stat()`` system calls when a -duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may produce -a huge data-dependent slowdown that slowly worsens over time. The net result is -that given enough time, a user with the ability to upload files can cause poor -performance in the upload handler, eventually causing it to become very slow -simply by uploading 0-byte files. At this point, even a slow network connection -and few HTTP requests would be all that is necessary to make a site unavailable. +duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may +produce a huge data-dependent slowdown that slowly worsens over time. The net +result is that given enough time, a user with the ability to upload files can +cause poor performance in the upload handler, eventually causing it to become +very slow simply by uploading 0-byte files. At this point, even a slow network +connection and few HTTP requests would be all that is necessary to make a site +unavailable. -We've remedied the issue by changing the algorithm for generating file names -if a file with the uploaded name already exists. -:meth:`Storage.get_available_name() +We've remedied the issue by changing the algorithm for generating file names if +a file with the uploaded name already exists. :meth:`Storage.get_available_name <django.core.files.storage.Storage.get_available_name>` now appends an underscore plus a random 7 character alphanumeric string (e.g. ``"_x3a1gho"``), -rather than iterating through an underscore followed by a number (e.g. ``"_1"``, -``"_2"``, etc.). +rather than iterating through an underscore followed by a number (e.g. +``"_1"``, ``"_2"``, etc.). ``RemoteUserMiddleware`` session hijacking ========================================== diff --git a/docs/releases/1.5.txt b/docs/releases/1.5.txt index 9fd9a7cec5..3a2ab6b342 100644 --- a/docs/releases/1.5.txt +++ b/docs/releases/1.5.txt @@ -18,11 +18,11 @@ Overview The biggest new feature in Django 1.5 is the `configurable User model`_. Before Django 1.5, applications that wanted to use Django's auth framework -(:mod:`django.contrib.auth`) were forced to use Django's definition of a "user". -In Django 1.5, you can now swap out the ``User`` model for one that you write -yourself. This could be a simple extension to the existing ``User`` model -- for -example, you could add a Twitter or Facebook ID field -- or you could completely -replace the ``User`` with one totally customized for your site. +(:mod:`django.contrib.auth`) were forced to use Django's definition of a +"user". In Django 1.5, you can now swap out the ``User`` model for one that you +write yourself. This could be a simple extension to the existing ``User`` model +-- for example, you could add a Twitter or Facebook ID field -- or you could +completely replace the ``User`` with one totally customized for your site. Django 1.5 is also the first release with `Python 3 support`_! We're labeling this support "experimental" because we don't yet consider it production-ready, @@ -50,11 +50,11 @@ However, as with previous releases, Django 1.5 ships with some minor :ref:`backwards incompatible changes <backwards-incompatible-1.5>`; people upgrading from previous versions of Django should read that list carefully. -One deprecated feature worth noting is the shift to "new-style" :ttag:`url` tag. -Prior to Django 1.3, syntax like ``{% url myview %}`` was interpreted +One deprecated feature worth noting is the shift to "new-style" :ttag:`url` +tag. Prior to Django 1.3, syntax like ``{% url myview %}`` was interpreted incorrectly (Django considered ``"myview"`` to be a literal name of a view, not -a template variable named ``myview``). Django 1.3 and above introduced the -``{% load url from future %}`` syntax to bring in the corrected behavior where +a template variable named ``myview``). Django 1.3 and above introduced the ``{% +load url from future %}`` syntax to bring in the corrected behavior where ``myview`` was seen as a variable. The upshot of this is that if you are not using ``{% load url from future %}`` @@ -69,16 +69,16 @@ Django 1.5 requires Python 2.6.5 or above, though we **highly recommend** Python 2.7.3 or above. Support for Python 2.5 and below has been dropped. This change should affect only a small number of Django users, as most -operating-system vendors today are shipping Python 2.6 or newer as their default -version. If you're still using Python 2.5, however, you'll need to stick to -Django 1.4 until you can upgrade your Python version. Per :doc:`our support -policy </internals/release-process>`, Django 1.4 will continue to receive -security support until the release of Django 1.6. +operating-system vendors today are shipping Python 2.6 or newer as their +default version. If you're still using Python 2.5, however, you'll need to +stick to Django 1.4 until you can upgrade your Python version. Per :doc:`our +support policy </internals/release-process>`, Django 1.4 will continue to +receive security support until the release of Django 1.6. Django 1.5 does not run on a Jython final release, because Jython's latest release doesn't currently support Python 2.6. However, Jython currently does -offer an alpha release featuring 2.7 support, and Django 1.5 supports that alpha -release. +offer an alpha release featuring 2.7 support, and Django 1.5 supports that +alpha release. Python 3 support ---------------- @@ -200,28 +200,30 @@ tag's content. Retrieval of ``ContentType`` instances associated with proxy models ------------------------------------------------------------------- -The methods :meth:`ContentTypeManager.get_for_model() <django.contrib.contenttypes.models.ContentTypeManager.get_for_model()>` -and :meth:`ContentTypeManager.get_for_models() <django.contrib.contenttypes.models.ContentTypeManager.get_for_models()>` -have a new keyword argument – respectively ``for_concrete_model`` and ``for_concrete_models``. -By passing ``False`` using this argument it is now possible to retrieve the -:class:`ContentType <django.contrib.contenttypes.models.ContentType>` -associated with proxy models. +The methods :meth:`ContentTypeManager.get_for_model() +<django.contrib.contenttypes.models.ContentTypeManager.get_for_model()>` +and :meth:`ContentTypeManager.get_for_models() +<django.contrib.contenttypes.models.ContentTypeManager.get_for_models()>` +have a new keyword argument – respectively ``for_concrete_model`` and +``for_concrete_models``. By passing ``False`` using this argument it is now +possible to retrieve the :class:`ContentType +<django.contrib.contenttypes.models.ContentType>` associated with proxy models. New ``view`` variable in class-based views context -------------------------------------------------- In all :doc:`generic class-based views </topics/class-based-views/index>` -(or any class-based view inheriting from ``ContextMixin``), the context dictionary -contains a ``view`` variable that points to the ``View`` instance. +(or any class-based view inheriting from ``ContextMixin``), the context +dictionary contains a ``view`` variable that points to the ``View`` instance. GeoDjango --------- * :class:`~django.contrib.gis.geos.LineString` and - :class:`~django.contrib.gis.geos.MultiLineString` GEOS objects now support the - :meth:`~django.contrib.gis.geos.GEOSGeometry.interpolate` and - :meth:`~django.contrib.gis.geos.GEOSGeometry.project` methods - (so-called linear referencing). + :class:`~django.contrib.gis.geos.MultiLineString` GEOS objects now support + the :meth:`~django.contrib.gis.geos.GEOSGeometry.interpolate` and + :meth:`~django.contrib.gis.geos.GEOSGeometry.project` methods (so-called + linear referencing). * The ``wkb`` and ``hex`` properties of :class:`~django.contrib.gis.geos.GEOSGeometry` objects preserve the Z @@ -305,10 +307,10 @@ Django 1.5 also includes several smaller improvements worth noting: in templates. * It's not required any more to have ``404.html`` and ``500.html`` templates in - the root templates directory. Django will output some basic error messages for - both situations when those templates are not found. It's still recommended as - good practice to provide those templates in order to present pretty error - pages to the user. + the root templates directory. Django will output some basic error messages + for both situations when those templates are not found. It's still + recommended as good practice to provide those templates in order to present + pretty error pages to the user. * :mod:`django.contrib.auth` provides a new signal that is emitted whenever a user fails to login successfully. See @@ -425,8 +427,8 @@ Non-form data in HTTP requests ------------------------------ :attr:`request.POST <django.http.HttpRequest.POST>` will no longer include data -posted via HTTP requests with non form-specific content-types in the header. -In prior versions, data posted with content-types other than +posted via HTTP requests with non form-specific content-types in the header. In +prior versions, data posted with content-types other than :mimetype:`multipart/form-data` or :mimetype:`application/x-www-form-urlencoded` would still end up represented in the :attr:`request.POST <django.http.HttpRequest.POST>` attribute. Developers @@ -606,8 +608,8 @@ tests are now executed in the following order: * First, all unit tests (including :class:`unittest.TestCase`, :class:`~django.test.SimpleTestCase`, :class:`~django.test.TestCase` and - :class:`~django.test.TransactionTestCase`) are run with no particular ordering - guaranteed nor enforced among them. + :class:`~django.test.TransactionTestCase`) are run with no particular + ordering guaranteed nor enforced among them. * Then any other tests (e.g. doctests) that may alter the database without restoring it to its original state are run. @@ -679,8 +681,8 @@ Miscellaneous needs. The new default value is ``0o666`` (octal) and the current umask value is first masked out. -* The :class:`F expressions <django.db.models.F>` supported bitwise operators by - ``&`` and ``|``. These operators are now available using ``.bitand()`` and +* The :class:`F expressions <django.db.models.F>` supported bitwise operators + by ``&`` and ``|``. These operators are now available using ``.bitand()`` and ``.bitor()`` instead. The removal of ``&`` and ``|`` was done to be consistent with :ref:`Q() expressions <complex-lookups-with-q>` and ``QuerySet`` combining where the operators are used as boolean AND and OR @@ -692,9 +694,9 @@ Miscellaneous and now F() expressions will always use the same relations as other lookups within the same ``filter()`` call. -* The :ttag:`csrf_token` template tag is no longer enclosed in a div. If you need - HTML validation against pre-HTML5 Strict DTDs, you should add a div around it - in your pages. +* The :ttag:`csrf_token` template tag is no longer enclosed in a div. If you + need HTML validation against pre-HTML5 Strict DTDs, you should add a div + around it in your pages. * The template tags library ``adminmedia``, which only contained the deprecated template tag ``{% admin_media_prefix %}``, was removed. diff --git a/docs/releases/1.6.1.txt b/docs/releases/1.6.1.txt index 081772b404..26876603ae 100644 --- a/docs/releases/1.6.1.txt +++ b/docs/releases/1.6.1.txt @@ -50,10 +50,11 @@ Bug fixes (#21530). * Re-added missing search result count and reset link in changelist admin view (#21510). -* The current language is no longer saved to the session by ``LocaleMiddleware`` - on every response, but rather only after a logout (#21473). -* Fixed a crash when executing ``runserver`` on non-English systems and when the - formatted date in its output contained non-ASCII characters (#21358). +* The current language is no longer saved to the session by + ``LocaleMiddleware`` on every response, but rather only after a logout + (#21473). +* Fixed a crash when executing ``runserver`` on non-English systems and when + the formatted date in its output contained non-ASCII characters (#21358). * Fixed a crash in the debug view after an exception occurred on Python ≥ 3.3 (#21443). * Fixed a crash in :class:`~django.db.models.ImageField` on some platforms diff --git a/docs/releases/1.6.3.txt b/docs/releases/1.6.3.txt index 0b5dbd549b..c7de4a72d8 100644 --- a/docs/releases/1.6.3.txt +++ b/docs/releases/1.6.3.txt @@ -172,8 +172,8 @@ Other bugfixes and changes * Wrapped database exceptions in ``_set_autocommit`` (:ticket:`22321`). -* Fixed atomicity when closing a database connection or when the database server - disconnects (:ticket:`21239` and :ticket:`21202`) +* Fixed atomicity when closing a database connection or when the database + server disconnects (:ticket:`21239` and :ticket:`21202`) * Fixed regression in ``prefetch_related`` that caused the related objects query to include an unnecessary join diff --git a/docs/releases/1.6.5.txt b/docs/releases/1.6.5.txt index 4c466f9fc6..79707c07fe 100644 --- a/docs/releases/1.6.5.txt +++ b/docs/releases/1.6.5.txt @@ -23,10 +23,10 @@ types. Therefore, Django would remove the header if the request was made by Internet Explorer. To remedy this, the special behavior for these older Internet Explorer versions -has been removed, and the ``Vary`` header is no longer stripped from the response. -In addition, modifications to the ``Cache-Control`` header for all Internet Explorer -requests with a ``Content-Disposition`` header have also been removed as they -were found to have similar issues. +has been removed, and the ``Vary`` header is no longer stripped from the +response. In addition, modifications to the ``Cache-Control`` header for all +Internet Explorer requests with a ``Content-Disposition`` header have also been +removed as they were found to have similar issues. Issue: Malformed redirect URLs from user input not correctly validated ====================================================================== @@ -43,8 +43,8 @@ The security checks for these redirects (namely URLs, such as ``http:\\\\\\djangoproject.com``, which are accepted by some browsers with more liberal URL parsing. -To remedy this, the validation in ``is_safe_url()`` has been tightened to be able -to handle and correctly validate these malformed URLs. +To remedy this, the validation in ``is_safe_url()`` has been tightened to be +able to handle and correctly validate these malformed URLs. Bugfixes ======== @@ -55,8 +55,8 @@ Bugfixes * Fixed ``pgettext_lazy`` crash when receiving bytestring content on Python 2 (:ticket:`22565`). -* Fixed the SQL generated when filtering by a negated ``Q`` object that contains - a ``F`` object. (:ticket:`22429`). +* Fixed the SQL generated when filtering by a negated ``Q`` object that + contains a ``F`` object. (:ticket:`22429`). * Avoided overwriting data fetched by ``select_related()`` in certain cases which could cause minor performance regressions diff --git a/docs/releases/1.6.6.txt b/docs/releases/1.6.6.txt index 38e2304c5d..474c1ee993 100644 --- a/docs/releases/1.6.6.txt +++ b/docs/releases/1.6.6.txt @@ -24,20 +24,21 @@ File upload denial-of-service Before this release, Django's file upload handing in its default configuration may degrade to producing a huge number of ``os.stat()`` system calls when a -duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may produce -a huge data-dependent slowdown that slowly worsens over time. The net result is -that given enough time, a user with the ability to upload files can cause poor -performance in the upload handler, eventually causing it to become very slow -simply by uploading 0-byte files. At this point, even a slow network connection -and few HTTP requests would be all that is necessary to make a site unavailable. +duplicate filename is uploaded. Since ``stat()`` may invoke IO, this may +produce a huge data-dependent slowdown that slowly worsens over time. The net +result is that given enough time, a user with the ability to upload files can +cause poor performance in the upload handler, eventually causing it to become +very slow simply by uploading 0-byte files. At this point, even a slow network +connection and few HTTP requests would be all that is necessary to make a site +unavailable. We've remedied the issue by changing the algorithm for generating file names if a file with the uploaded name already exists. :meth:`Storage.get_available_name() <django.core.files.storage.Storage.get_available_name>` now appends an underscore plus a random 7 character alphanumeric string (e.g. ``"_x3a1gho"``), -rather than iterating through an underscore followed by a number (e.g. ``"_1"``, -``"_2"``, etc.). +rather than iterating through an underscore followed by a number (e.g. +``"_1"``, ``"_2"``, etc.). ``RemoteUserMiddleware`` session hijacking ========================================== @@ -90,8 +91,8 @@ Bugfixes * Prevented ``UnicodeDecodeError`` in ``runserver`` with non-UTF-8 and non-English locale (:ticket:`23265`). -* Fixed JavaScript errors while editing multi-geometry objects in the OpenLayers - widget (:ticket:`23137`, :ticket:`23293`). +* Fixed JavaScript errors while editing multi-geometry objects in the + OpenLayers widget (:ticket:`23137`, :ticket:`23293`). * Prevented a crash on Python 3 with query strings containing unencoded non-ASCII characters (:ticket:`22996`). diff --git a/docs/releases/1.6.txt b/docs/releases/1.6.txt index 794dddad8f..cf6b10cadd 100644 --- a/docs/releases/1.6.txt +++ b/docs/releases/1.6.txt @@ -1,6 +1,6 @@ -========================= - Django 1.6 release notes -========================= +======================== +Django 1.6 release notes +======================== .. note:: @@ -10,11 +10,11 @@ a very dear friend and developer. Malcolm was a long-time contributor to Django, a model community member, a - brilliant mind, and a friend. His contributions to Django — and to many other - open source projects — are nearly impossible to enumerate. Many on the core - Django team had their first patches reviewed by him; his mentorship enriched - us. His consideration, patience, and dedication will always be an inspiration - to us. + brilliant mind, and a friend. His contributions to Django — and to many + other open source projects — are nearly impossible to enumerate. Many on + the core Django team had their first patches reviewed by him; his + mentorship enriched us. His consideration, patience, and dedication will + always be an inspiration to us. This release of Django is for Malcolm. @@ -126,9 +126,10 @@ binary data in the database. GeoDjango form widgets ---------------------- -GeoDjango now provides :doc:`form fields and widgets </ref/contrib/gis/forms-api>` -for its geo-specialized fields. They are OpenLayers-based by default, but they -can be customized to use any other JS framework. +GeoDjango now provides :doc:`form fields and widgets +</ref/contrib/gis/forms-api>` for its geo-specialized fields. They are +OpenLayers-based by default, but they can be customized to use any other JS +framework. ``check`` management command added for verifying compatibility -------------------------------------------------------------- @@ -341,10 +342,11 @@ Minor features :ref:`see the updated recommendation <raising-validation-error>` for raising a ``ValidationError``. -* :class:`~django.contrib.admin.ModelAdmin` now preserves filters on the list view - after creating, editing or deleting an object. It's possible to restore the previous - behavior of clearing filters by setting the - :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to ``False``. +* :class:`~django.contrib.admin.ModelAdmin` now preserves filters on the list + view after creating, editing or deleting an object. It's possible to restore + the previous behavior of clearing filters by setting the + :attr:`~django.contrib.admin.ModelAdmin.preserve_filters` attribute to + ``False``. * Added :meth:`FormMixin.get_prefix<django.views.generic.edit.FormMixin.get_prefix>` @@ -450,8 +452,8 @@ Custom user models in tests --------------------------- The introduction of the new test runner has also slightly changed the way that -test models are imported. As a result, any test that overrides ``AUTH_USER_MODEL`` -to test behavior with one of Django's test user models ( +test models are imported. As a result, any test that overrides +``AUTH_USER_MODEL`` to test behavior with one of Django's test user models ( ``django.contrib.auth.tests.custom_user.CustomUser`` and ``django.contrib.auth.tests.custom_user.ExtensionUser``) must now explicitly import the User model in your test module:: @@ -471,7 +473,8 @@ error reporting: .. code-block:: pytb - ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.CustomUser' that has not been installed + ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.CustomUser' that + has not been installed Time zone-aware ``day``, ``month``, and ``week_day`` lookups ------------------------------------------------------------ @@ -652,10 +655,11 @@ hardcoded sentence: *Hold down "Control", or "Command" on a Mac, to select more than one.* -(or its translation to the active locale) imposed as the help legend shown along -them if neither :attr:`model <django.db.models.Field.help_text>` nor :attr:`form -<django.forms.Field.help_text>` ``help_text`` attributes were specified by the -user (or this string was appended to any ``help_text`` that was provided). +(or its translation to the active locale) imposed as the help legend shown +along them if neither :attr:`model <django.db.models.Field.help_text>` nor +:attr:`form <django.forms.Field.help_text>` ``help_text`` attributes were +specified by the user (or this string was appended to any ``help_text`` that +was provided). Since this happened at the model layer, there was no way to prevent the text from appearing in cases where it wasn't applicable such as form fields that @@ -871,8 +875,8 @@ Miscellaneous corresponding field type. * Form field's :attr:`~django.forms.Field.error_messages` that contain a - placeholder should now always use a named placeholder (``"Value '%(value)s' is - too big"`` instead of ``"Value '%s' is too big"``). See the corresponding + placeholder should now always use a named placeholder (``"Value '%(value)s' + is too big"`` instead of ``"Value '%s' is too big"``). See the corresponding field documentation for details about the names of the placeholders. The changes in 1.6 particularly affect :class:`~django.forms.DecimalField` and :class:`~django.forms.ModelMultipleChoiceField`. @@ -949,10 +953,10 @@ Miscellaneous release: blank passwords are now valid. * The admin :attr:`~django.contrib.admin.ModelAdmin.changelist_view` previously - accepted a ``pop`` GET parameter to signify it was to be displayed in a popup. - This parameter has been renamed to ``_popup`` to be consistent with the rest - of the admin views. You should update your custom templates if they use the - previous parameter name. + accepted a ``pop`` GET parameter to signify it was to be displayed in a + popup. This parameter has been renamed to ``_popup`` to be consistent with + the rest of the admin views. You should update your custom templates if they + use the previous parameter name. * :meth:`~django.core.validators.validate_email` now accepts email addresses with ``localhost`` as the domain. @@ -964,11 +968,12 @@ Miscellaneous been removed. Use ``socket.error`` provided by the standard library instead. This change was also released in Django 1.5.5. -* The signature of :meth:`django.views.generic.base.RedirectView.get_redirect_url` - has changed and now accepts positional arguments as well (``*args, **kwargs``). - Any unnamed captured group will now be passed to ``get_redirect_url()`` - which may result in a ``TypeError`` if you don't update the signature of your - custom method. +* The signature of + :meth:`django.views.generic.base.RedirectView.get_redirect_url` has changed + and now accepts positional arguments as well (``*args, **kwargs``). Any + unnamed captured group will now be passed to ``get_redirect_url()`` which may + result in a ``TypeError`` if you don't update the signature of your custom + method. .. _deprecated-features-1.6: @@ -992,7 +997,8 @@ current APIs are deprecated: Django's comment framework has been deprecated and is no longer supported. It will be available in Django 1.6 and 1.7, and removed in Django 1.8. Most users -will be better served with a custom solution, or a hosted product like Disqus__. +will be better served with a custom solution, or a hosted product like +Disqus__. The code formerly known as ``django.contrib.comments`` is `still available in an external repository`__. @@ -1131,9 +1137,10 @@ must support old Django versions, you should write:: return get_queryset() # etc In the general case of a custom manager that both implements its own -``get_queryset`` method and calls that method, and needs to work with older Django -versions, and libraries that have not been updated yet, it is useful to define -a ``get_queryset_compat`` method as below and use it internally to your manager:: +``get_queryset`` method and calls that method, and needs to work with older +Django versions, and libraries that have not been updated yet, it is useful to +define a ``get_queryset_compat`` method as below and use it internally to your +manager:: class YourCustomManager(models.Manager): def get_queryset(self): @@ -1152,8 +1159,8 @@ a ``get_queryset_compat`` method as below and use it internally to your manager: return get_queryset() This helps to minimize the changes that are needed, but also works correctly in -the case of subclasses (such as ``RelatedManagers`` from Django 1.5) which might -override either ``get_query_set`` or ``get_queryset``. +the case of subclasses (such as ``RelatedManagers`` from Django 1.5) which +might override either ``get_query_set`` or ``get_queryset``. ``shortcut`` view and URLconf @@ -1179,23 +1186,23 @@ with:: ``ModelForm`` without ``fields`` or ``exclude`` ----------------------------------------------- -Previously, if you wanted a :class:`~django.forms.ModelForm` to use all fields on -the model, you could simply omit the ``Meta.fields`` attribute, and all fields -would be used. +Previously, if you wanted a :class:`~django.forms.ModelForm` to use all fields +on the model, you could simply omit the ``Meta.fields`` attribute, and all +fields would be used. This can lead to security problems where fields are added to the model and, unintentionally, automatically become editable by end users. In some cases, -particular with boolean fields, it is possible for this problem to be completely -invisible. This is a form of `Mass assignment vulnerability +particular with boolean fields, it is possible for this problem to be +completely invisible. This is a form of `Mass assignment vulnerability <https://en.wikipedia.org/wiki/Mass_assignment_vulnerability>`_. For this reason, this behavior is deprecated, and using the ``Meta.exclude`` option is strongly discouraged. Instead, all fields that are intended for inclusion in the form should be listed explicitly in the ``fields`` attribute. -If this security concern really does not apply in your case, there is a shortcut -to explicitly indicate that all fields should be used - use the special value -``"__all__"`` for the fields attribute:: +If this security concern really does not apply in your case, there is a +shortcut to explicitly indicate that all fields should be used - use the +special value ``"__all__"`` for the fields attribute:: class MyModelForm(ModelForm): class Meta: @@ -1220,9 +1227,9 @@ The generic views :class:`~django.views.generic.edit.CreateView` and security problem described in the section above, because they can automatically create a ``ModelForm`` that uses all fields for a model. -For this reason, if you use these views for editing models, you must also supply -the ``fields`` attribute (new in Django 1.6), which is a list of model fields -and works in the same way as the :class:`~django.forms.ModelForm` +For this reason, if you use these views for editing models, you must also +supply the ``fields`` attribute (new in Django 1.6), which is a list of model +fields and works in the same way as the :class:`~django.forms.ModelForm` ``Meta.fields`` attribute. Alternatively, you can set the ``form_class`` attribute to a ``ModelForm`` that explicitly defines the fields to be used. Defining an ``UpdateView`` or ``CreateView`` subclass to be used with a model @@ -1233,10 +1240,10 @@ but without an explicit list of fields is deprecated. Munging of help text of model form fields for ``ManyToManyField`` fields ------------------------------------------------------------------------ -All special handling of the ``help_text`` attribute of ``ManyToManyField`` model -fields performed by standard model or model form fields as described in +All special handling of the ``help_text`` attribute of ``ManyToManyField`` +model fields performed by standard model or model form fields as described in :ref:`m2m-help_text` above is deprecated and will be removed in Django 1.8. -Help text of these fields will need to be handled either by applications, custom -form fields or widgets, just like happens with the rest of the model field -types. +Help text of these fields will need to be handled either by applications, +custom form fields or widgets, just like happens with the rest of the model +field types. diff --git a/docs/releases/1.7.1.txt b/docs/releases/1.7.1.txt index 9783921659..2c527ef185 100644 --- a/docs/releases/1.7.1.txt +++ b/docs/releases/1.7.1.txt @@ -15,7 +15,8 @@ Bugfixes * Added a more helpful error message if you try to migrate an app without first creating the ``contenttypes`` table (:ticket:`22411`). -* Modified migrations dependency algorithm to avoid possible infinite recursion. +* Modified migrations dependency algorithm to avoid possible infinite + recursion. * Fixed a ``UnicodeDecodeError`` when the ``flush`` error message contained Unicode characters (:ticket:`22882`). diff --git a/docs/releases/1.7.2.txt b/docs/releases/1.7.2.txt index d057295017..3bad6feb44 100644 --- a/docs/releases/1.7.2.txt +++ b/docs/releases/1.7.2.txt @@ -19,8 +19,8 @@ Bugfixes SQLite (:ticket:`23702`). * Added a warning for duplicate models when a module is reloaded. Previously a - ``RuntimeError`` was raised every time two models clashed in the app registry. - (:ticket:`23621`). + ``RuntimeError`` was raised every time two models clashed in the app + registry. (:ticket:`23621`). * Prevented :djadmin:`flush` from loading initial data for migrated apps (:ticket:`23699`). @@ -87,8 +87,8 @@ Bugfixes * Fixed a regression with dynamically generated inlines and allowed field references in the admin (:ticket:`23754`). -* Fixed an infinite loop bug for certain cyclic migration dependencies, and made - the error message for cyclic dependencies much more helpful. +* Fixed an infinite loop bug for certain cyclic migration dependencies, and + made the error message for cyclic dependencies much more helpful. * Added missing ``index_together`` handling for SQLite (:ticket:`23880`). @@ -137,9 +137,9 @@ Bugfixes * Fixed ``timesince`` filter translations in Korean (:ticket:`23989`). * Fixed the SQLite ``SchemaEditor`` to properly add defaults in the absence of - a user specified ``default``. For example, a ``CharField`` with ``blank=True`` - didn't set existing rows to an empty string which resulted in a crash when - adding the ``NOT NULL`` constraint (:ticket:`23987`). + a user specified ``default``. For example, a ``CharField`` with + ``blank=True`` didn't set existing rows to an empty string which resulted in + a crash when adding the ``NOT NULL`` constraint (:ticket:`23987`). * ``makemigrations`` no longer prompts for a default value when adding ``TextField()`` or ``CharField()`` without a ``default`` (:ticket:`23405`). @@ -163,10 +163,10 @@ Bugfixes * Fixed admindocs crash on apps installed as eggs (:ticket:`23525`). -* Changed migrations autodetector to generate an ``AlterModelOptions`` operation - instead of ``DeleteModel`` and ``CreateModel`` operations when changing - ``Meta.managed``. This prevents data loss when changing ``managed`` from - ``False`` to ``True`` and vice versa (:ticket:`24037`). +* Changed migrations autodetector to generate an ``AlterModelOptions`` + operation instead of ``DeleteModel`` and ``CreateModel`` operations when + changing ``Meta.managed``. This prevents data loss when changing ``managed`` + from ``False`` to ``True`` and vice versa (:ticket:`24037`). * Enabled the ``sqlsequencereset`` command on apps with migrations (:ticket:`24054`). @@ -187,8 +187,8 @@ Bugfixes * Restored the ability to use more than five levels of subqueries (:ticket:`23758`). -* Fixed crash when ``ValidationError`` is initialized with a ``ValidationError`` - that is initialized with a dictionary (:ticket:`24008`). +* Fixed crash when ``ValidationError`` is initialized with a + ``ValidationError`` that is initialized with a dictionary (:ticket:`24008`). * Prevented a crash on apps without migrations when running ``migrate --list`` (:ticket:`23366`). diff --git a/docs/releases/1.7.9.txt b/docs/releases/1.7.9.txt index 1661f2fdb8..dfb5876d21 100644 --- a/docs/releases/1.7.9.txt +++ b/docs/releases/1.7.9.txt @@ -46,10 +46,10 @@ unexpected newlines. :func:`~django.core.validators.validate_ipv4_address`, :func:`~django.core.validators.validate_slug`, and :class:`~django.core.validators.URLValidator` are also affected, however, as -of Django 1.6 the ``GenericIPAddresseField``, ``IPAddressField``, ``SlugField``, -and ``URLField`` form fields which use these validators all strip the input, so -the possibility of newlines entering your data only exists if you are using -these validators outside of the form fields. +of Django 1.6 the ``GenericIPAddresseField``, ``IPAddressField``, +``SlugField``, and ``URLField`` form fields which use these validators all +strip the input, so the possibility of newlines entering your data only exists +if you are using these validators outside of the form fields. The undocumented, internally unused ``validate_integer()`` function is now stricter as it validates using a regular expression instead of simply casting diff --git a/docs/releases/1.7.txt b/docs/releases/1.7.txt index 3ab1b0b52a..dd1b13367a 100644 --- a/docs/releases/1.7.txt +++ b/docs/releases/1.7.txt @@ -23,11 +23,11 @@ The Django 1.6 series is the last to support Python 2.6. Django 1.7 is the first release to support Python 3.4. This change should affect only a small number of Django users, as most -operating-system vendors today are shipping Python 2.7 or newer as their default -version. If you're still using Python 2.6, however, you'll need to stick to -Django 1.6 until you can upgrade your Python version. Per :doc:`our support -policy </internals/release-process>`, Django 1.6 will continue to receive -security support until the release of Django 1.8. +operating-system vendors today are shipping Python 2.7 or newer as their +default version. If you're still using Python 2.6, however, you'll need to +stick to Django 1.6 until you can upgrade your Python version. Per :doc:`our +support policy </internals/release-process>`, Django 1.6 will continue to +receive security support until the release of Django 1.8. .. _whats-new-1.7: @@ -37,9 +37,9 @@ What's new in Django 1.7 Schema migrations ----------------- -Django now has built-in support for schema migrations. It allows models -to be updated, changed, and deleted by creating migration files that represent -the model changes and which can be run on any development, staging or production +Django now has built-in support for schema migrations. It allows models to be +updated, changed, and deleted by creating migration files that represent the +model changes and which can be run on any development, staging or production database. Migrations are covered in :doc:`their own documentation</topics/migrations>`, @@ -58,15 +58,18 @@ but a few of the key features are: new signals have slightly different arguments. Check the documentation for details. -* The ``allow_syncdb`` method on database routers is now called ``allow_migrate``, - but still performs the same function. Routers with ``allow_syncdb`` methods - will still work, but that method name is deprecated and you should change - it as soon as possible (nothing more than renaming is required). +* The ``allow_syncdb`` method on database routers is now called + ``allow_migrate``, but still performs the same function. Routers with + ``allow_syncdb`` methods will still work, but that method name is deprecated + and you should change it as soon as possible (nothing more than renaming is + required). * ``initial_data`` fixtures are no longer loaded for apps with migrations; if - you want to load initial data for an app, we suggest you create a migration for - your application and define a :class:`~django.db.migrations.operations.RunPython` - or :class:`~django.db.migrations.operations.RunSQL` operation in the ``operations`` section of the migration. + you want to load initial data for an app, we suggest you create a migration + for your application and define a + :class:`~django.db.migrations.operations.RunPython` or + :class:`~django.db.migrations.operations.RunSQL` operation in the + ``operations`` section of the migration. * Test rollback behavior is different for apps with migrations; in particular, Django will no longer emulate rollbacks on non-transactional databases or @@ -129,18 +132,20 @@ This method takes no arguments, and returns a tuple of four items: * ``name``: The field's attribute name on its parent model, or ``None`` if it is not part of a model -* ``path``: A dotted, Python path to the class of this field, including the class name. +* ``path``: A dotted, Python path to the class of this field, including the + class name. * ``args``: Positional arguments, as a list * ``kwargs``: Keyword arguments, as a dict These four values allow any field to be serialized into a file, as well as -allowing the field to be copied safely, both essential parts of these new features. +allowing the field to be copied safely, both essential parts of these new +features. This change should not affect you unless you write custom Field subclasses; if you do, you may need to reimplement the ``deconstruct()`` method if your subclass changes the method signature of ``__init__`` in any way. If your -field just inherits from a built-in Django field and doesn't override ``__init__``, -no changes are necessary. +field just inherits from a built-in Django field and doesn't override +``__init__``, no changes are necessary. If you do need to override ``deconstruct()``, a good place to start is the built-in Django fields (``django/db/models/fields/__init__.py``) as several @@ -507,7 +512,8 @@ Minor features subclassed to override the permissions that collected static files and directories receive by setting the :attr:`~django.core.files.storage.FileSystemStorage.file_permissions_mode` - and :attr:`~django.core.files.storage.FileSystemStorage.directory_permissions_mode` + and + :attr:`~django.core.files.storage.FileSystemStorage.directory_permissions_mode` parameters. See :djadmin:`collectstatic` for example usage. * The ``CachedStaticFilesStorage`` backend gets a sibling class called @@ -519,8 +525,9 @@ Minor features when running the :djadmin:`collectstatic` management command and should be a less expensive alternative for remote storages such as Amazon S3. - See the :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` - docs for more information. + See the + :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` docs + for more information. * :djadmin:`findstatic` now accepts verbosity flag level 2, meaning it will show the relative paths of the directories it searched. See @@ -608,9 +615,9 @@ Forms * The ``<label>`` and ``<input>`` tags rendered by :class:`~django.forms.RadioSelect` and :class:`~django.forms.CheckboxSelectMultiple` when looping over the radio - buttons or checkboxes now include ``for`` and ``id`` attributes, respectively. - Each radio button or checkbox includes an ``id_for_label`` attribute to - output the element's ID. + buttons or checkboxes now include ``for`` and ``id`` attributes, + respectively. Each radio button or checkbox includes an ``id_for_label`` + attribute to output the element's ID. * The ``<textarea>`` tags rendered by :class:`~django.forms.Textarea` now include a ``maxlength`` attribute if the :class:`~django.db.models.TextField` @@ -784,20 +791,22 @@ Models * Custom intermediate models having more than one foreign key to any of the models participating in a many-to-many relationship are now permitted, provided you explicitly specify which foreign keys should be used by setting - the new :attr:`ManyToManyField.through_fields <django.db.models.ManyToManyField.through_fields>` - argument. + the new :attr:`ManyToManyField.through_fields + <django.db.models.ManyToManyField.through_fields>` argument. * Assigning a model instance to a non-relation field will now throw an error. Previously this used to work if the field accepted integers as input as it took the primary key. * Integer fields are now validated against database backend specific min and - max values based on their :meth:`internal_type <django.db.models.Field.get_internal_type>`. - Previously model field validation didn't prevent values out of their associated - column data type range from being saved resulting in an integrity error. + max values based on their :meth:`internal_type + <django.db.models.Field.get_internal_type>`. Previously model field + validation didn't prevent values out of their associated column data type + range from being saved resulting in an integrity error. -* It is now possible to explicitly :meth:`~django.db.models.query.QuerySet.order_by` - a relation ``_id`` field by using its attribute name. +* It is now possible to explicitly + :meth:`~django.db.models.query.QuerySet.order_by` a relation ``_id`` field by + using its attribute name. Signals ~~~~~~~ @@ -824,8 +833,8 @@ Templates * ``Context`` objects can now be compared for equality (internally, this uses :meth:`Context.flatten() <django.template.Context.flatten>` so the - internal structure of each ``Context``'s stack doesn't matter as long as their - flattened version is identical). + internal structure of each ``Context``'s stack doesn't matter as long as + their flattened version is identical). * The :ttag:`widthratio` template tag now accepts an ``"as"`` parameter to capture the result in a variable. @@ -877,7 +886,8 @@ Requests and Responses relative URLs. * The new :class:`~django.http.JsonResponse` subclass of - :class:`~django.http.HttpResponse` helps easily create JSON-encoded responses. + :class:`~django.http.HttpResponse` helps easily create JSON-encoded + responses. Tests ~~~~~ @@ -919,11 +929,11 @@ Validators * :class:`~django.core.validators.RegexValidator` now accepts the optional :attr:`~django.core.validators.RegexValidator.flags` and - Boolean :attr:`~django.core.validators.RegexValidator.inverse_match` arguments. - The :attr:`~django.core.validators.RegexValidator.inverse_match` attribute - determines if the :exc:`~django.core.exceptions.ValidationError` should - be raised when the regular expression pattern matches (``True``) or does not - match (``False``, by default) the provided ``value``. The + Boolean :attr:`~django.core.validators.RegexValidator.inverse_match` + arguments. The :attr:`~django.core.validators.RegexValidator.inverse_match` + attribute determines if the :exc:`~django.core.exceptions.ValidationError` + should be raised when the regular expression pattern matches (``True``) or + does not match (``False``, by default) the provided ``value``. The :attr:`~django.core.validators.RegexValidator.flags` attribute sets the flags used when compiling a regular expression string. @@ -955,17 +965,18 @@ should be renamed to ``allow_migrate``, there is a subtle difference in which models get passed to these methods. For apps with migrations, ``allow_migrate`` will now get passed -:ref:`historical models <historical-models>`, which are special versioned models -without custom attributes, methods or managers. Make sure your ``allow_migrate`` -methods are only referring to fields or other items in ``model._meta``. +:ref:`historical models <historical-models>`, which are special versioned +models without custom attributes, methods or managers. Make sure your +``allow_migrate`` methods are only referring to fields or other items in +``model._meta``. initial_data ------------ Apps with migrations will not load ``initial_data`` fixtures when they have -finished migrating. Apps without migrations will continue to load these fixtures -during the phase of ``migrate`` which emulates the old ``syncdb`` behavior, -but any new apps will not have this support. +finished migrating. Apps without migrations will continue to load these +fixtures during the phase of ``migrate`` which emulates the old ``syncdb`` +behavior, but any new apps will not have this support. Instead, you are encouraged to load initial data in migrations if you need it (using the ``RunPython`` operation and your model classes); @@ -1218,8 +1229,8 @@ model implemented a custom ``get_queryset()``). Fixing the issues introduced some backward incompatible changes: -- The default implementation of ``remove()`` for ``ForeignKey`` related managers - changed from a series of ``Model.save()`` calls to a single +- The default implementation of ``remove()`` for ``ForeignKey`` related + managers changed from a series of ``Model.save()`` calls to a single ``QuerySet.update()`` call. The change means that ``pre_save`` and ``post_save`` signals aren't sent anymore. You can use the ``bulk=False`` keyword argument to revert to the previous behavior. @@ -1326,9 +1337,9 @@ Miscellaneous two ``Model`` instances without primary key values won't be considered equal (unless they are the same instance). -* The :meth:`django.db.models.Model.__hash__` method will now raise ``TypeError`` - when called on an instance without a primary key value. This is done to - avoid mutable ``__hash__`` values in containers. +* The :meth:`django.db.models.Model.__hash__` method will now raise + ``TypeError`` when called on an instance without a primary key value. This is + done to avoid mutable ``__hash__`` values in containers. * :class:`~django.db.models.AutoField` columns in SQLite databases will now be created using the ``AUTOINCREMENT`` option, which guarantees monotonic @@ -1357,9 +1368,9 @@ Miscellaneous (similarly to what one gets with :setting:`DEBUG = True <DEBUG>` at development-time) has been moved to a new class that lives in the ``staticfiles`` application (the one actually in charge of such feature): - :class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`. In other - words, ``LiveServerTestCase`` itself is less powerful but at the same time - has less magic. + :class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`. In + other words, ``LiveServerTestCase`` itself is less powerful but at the same + time has less magic. Rationale behind this is removal of dependency of non-contrib code on contrib applications. @@ -1431,7 +1442,8 @@ Miscellaneous * As part of the :doc:`System check framework </ref/checks>`, :ref:`fields, models, and model managers <field-checking>` all implement a ``check()`` method that is registered with the check framework. If you have an existing - method called ``check()`` on one of these objects, you will need to rename it. + method called ``check()`` on one of these objects, you will need to rename + it. * As noted above in the "Cache" section of "Minor Features", defining the :setting:`TIMEOUT <CACHES-TIMEOUT>` argument of the @@ -1535,11 +1547,10 @@ Custom SQL location for models package Previously, if models were organized in a package (``myapp/models/``) rather than simply ``myapp/models.py``, Django would look for initial SQL data in -``myapp/models/sql/``. This bug has been fixed so that Django -will search ``myapp/sql/`` as documented. After this issue was fixed, migrations -were added which deprecates initial SQL data. Thus, while this change still -exists, the deprecation is irrelevant as the entire feature will be removed in -Django 1.9. +``myapp/models/sql/``. This bug has been fixed so that Django will search +``myapp/sql/`` as documented. After this issue was fixed, migrations were added +which deprecates initial SQL data. Thus, while this change still exists, the +deprecation is irrelevant as the entire feature will be removed in Django 1.9. Reorganization of ``django.contrib.sites`` ------------------------------------------ @@ -1566,9 +1577,10 @@ Reorganization of ``django.contrib.contenttypes`` ------------------------------------------------- Since ``django.contrib.contenttypes.generic`` defined both admin and model -related objects, an import of this module could trigger unexpected side effects. -As a consequence, its contents were split into :mod:`~django.contrib.contenttypes` -submodules and the ``django.contrib.contenttypes.generic`` module is deprecated: +related objects, an import of this module could trigger unexpected side +effects. As a consequence, its contents were split into +:mod:`~django.contrib.contenttypes` submodules and the +``django.contrib.contenttypes.generic`` module is deprecated: * :class:`~django.contrib.contenttypes.fields.GenericForeignKey` and :class:`~django.contrib.contenttypes.fields.GenericRelation` now live in @@ -1584,9 +1596,10 @@ submodules and the ``django.contrib.contenttypes.generic`` module is deprecated: ``syncdb`` ---------- -The ``syncdb`` command has been deprecated in favor of the new :djadmin:`migrate` -command. ``migrate`` takes the same arguments as ``syncdb`` used to plus a few -more, so it's safe to just change the name you're calling and nothing else. +The ``syncdb`` command has been deprecated in favor of the new +:djadmin:`migrate` command. ``migrate`` takes the same arguments as ``syncdb`` +used to plus a few more, so it's safe to just change the name you're calling +and nothing else. ``util`` modules renamed to ``utils`` ------------------------------------- @@ -1725,9 +1738,9 @@ The ``django.contrib.admin.validation`` module is deprecated. ``django.db.backends.DatabaseValidation.validate_field`` -------------------------------------------------------- -This method is deprecated in favor of a new ``check_field`` method. -The functionality required by ``check_field()`` is the same as that provided -by ``validate_field()``, but the output format is different. Third-party database +This method is deprecated in favor of a new ``check_field`` method. The +functionality required by ``check_field()`` is the same as that provided by +``validate_field()``, but the output format is different. Third-party database backends needing this functionality should provide an implementation of ``check_field()``. @@ -1743,9 +1756,9 @@ will be removed in Django 1.9. You can simply remove the ``django.utils.text.javascript_quote`` -------------------------------------- -``javascript_quote()`` was an undocumented function present in ``django.utils.text``. -It was used internally in the ``javascript_catalog()`` view -whose implementation was changed to make use of ``json.dumps()`` instead. +``javascript_quote()`` was an undocumented function present in +``django.utils.text``. It was used internally in the ``javascript_catalog()`` +view whose implementation was changed to make use of ``json.dumps()`` instead. If you were relying on this function to provide safe output from untrusted strings, you should use ``django.utils.html.escapejs`` or the :tfilter:`escapejs` template filter. @@ -1756,14 +1769,14 @@ If all you need is to generate valid JavaScript strings, you can simply use --------------------------------------------------- The ``django.utils.html.fix_ampersands`` method and the ``fix_ampersands`` -template filter are deprecated, as the escaping of ampersands is already taken care -of by Django's standard HTML escaping features. Combining this with ``fix_ampersands`` -would either result in double escaping, or, if the output is assumed to be safe, -a risk of introducing XSS vulnerabilities. Along with ``fix_ampersands``, -``django.utils.html.clean_html`` is deprecated, an undocumented function that calls -``fix_ampersands``. -As this is an accelerated deprecation, ``fix_ampersands`` and ``clean_html`` -will be removed in Django 1.8. +template filter are deprecated, as the escaping of ampersands is already taken +care of by Django's standard HTML escaping features. Combining this with +``fix_ampersands`` would either result in double escaping, or, if the output is +assumed to be safe, a risk of introducing XSS vulnerabilities. Along with +``fix_ampersands``, ``django.utils.html.clean_html`` is deprecated, an +undocumented function that calls ``fix_ampersands``. As this is an accelerated +deprecation, ``fix_ampersands`` and ``clean_html`` will be removed in Django +1.8. Reorganization of database test settings ---------------------------------------- diff --git a/docs/releases/1.8.1.txt b/docs/releases/1.8.1.txt index 709a478d9e..123ce1661d 100644 --- a/docs/releases/1.8.1.txt +++ b/docs/releases/1.8.1.txt @@ -51,9 +51,10 @@ Bugfixes ``django.conf.urls.url()`` which is deprecated in Django 1.8 (:ticket:`24635`). -* Fixed queries where an expression was referenced in ``order_by()``, but wasn't - part of the select clause. An example query is - ``qs.annotate(foo=F('field')).values('pk').order_by('foo'))`` (:ticket:`24615`). +* Fixed queries where an expression was referenced in ``order_by()``, but + wasn't part of the select clause. An example query is + ``qs.annotate(foo=F('field')).values('pk').order_by('foo'))`` + (:ticket:`24615`). * Fixed a database table name quoting regression (:ticket:`24605`). diff --git a/docs/releases/1.8.3.txt b/docs/releases/1.8.3.txt index ccdb31b7f3..a1b600e1ac 100644 --- a/docs/releases/1.8.3.txt +++ b/docs/releases/1.8.3.txt @@ -51,10 +51,10 @@ unexpected newlines. :func:`~django.core.validators.validate_ipv4_address`, :func:`~django.core.validators.validate_slug`, and :class:`~django.core.validators.URLValidator` are also affected, however, as -of Django 1.6 the ``GenericIPAddresseField``, ``IPAddressField``, ``SlugField``, -and ``URLField`` form fields which use these validators all strip the input, so -the possibility of newlines entering your data only exists if you are using -these validators outside of the form fields. +of Django 1.6 the ``GenericIPAddresseField``, ``IPAddressField``, +``SlugField``, and ``URLField`` form fields which use these validators all +strip the input, so the possibility of newlines entering your data only exists +if you are using these validators outside of the form fields. The undocumented, internally unused ``validate_integer()`` function is now stricter as it validates using a regular expression instead of simply casting @@ -64,8 +64,8 @@ Denial-of-service possibility in URL validation =============================================== :class:`~django.core.validators.URLValidator` included a regular expression -that was extremely slow to evaluate against certain invalid inputs. This regular -expression has been simplified and optimized. +that was extremely slow to evaluate against certain invalid inputs. This +regular expression has been simplified and optimized. Bugfixes ======== diff --git a/docs/releases/1.8.txt b/docs/releases/1.8.txt index 14f928486f..a63f14ca51 100644 --- a/docs/releases/1.8.txt +++ b/docs/releases/1.8.txt @@ -165,7 +165,8 @@ Minor features * You can now specify :attr:`ModelAdmin.show_full_result_count <django.contrib.admin.ModelAdmin.show_full_result_count>` to control whether - or not the full count of objects should be displayed on a filtered admin page. + or not the full count of objects should be displayed on a filtered admin + page. * The ``AdminSite.password_change()`` method now has an ``extra_context`` parameter. @@ -219,7 +220,8 @@ Minor features available. * It is now allowed to include a subquery as a geographic lookup argument, for - example ``City.objects.filter(point__within=Country.objects.filter(continent='Africa').values('mpoly'))``. + example + ``City.objects.filter(point__within=Country.objects.filter(continent='Africa').values('mpoly'))``. * The SpatiaLite backend now supports ``Collect`` and ``Extent`` aggregates when the database version is 3.0 or later. @@ -280,10 +282,10 @@ Database backends * The MySQL backend no longer strips microseconds from ``datetime`` values as MySQL 5.6.4 and up supports fractional seconds depending on the declaration - of the datetime field (when ``DATETIME`` includes fractional precision greater - than 0). New datetime database columns created with Django 1.8 and MySQL 5.6.4 - and up will support microseconds. See the :ref:`MySQL database notes - <mysql-fractional-seconds>` for more details. + of the datetime field (when ``DATETIME`` includes fractional precision + greater than 0). New datetime database columns created with Django 1.8 and + MySQL 5.6.4 and up will support microseconds. See the :ref:`MySQL database + notes <mysql-fractional-seconds>` for more details. * The MySQL backend no longer creates explicit indexes for foreign keys when using the InnoDB storage engine, as MySQL already creates them automatically. @@ -350,11 +352,11 @@ Forms override the top list choice label when :class:`~django.forms.DateField` is not required. -* After an :class:`~django.forms.ImageField` has been cleaned and validated, the - ``UploadedFile`` object will have an additional ``image`` attribute containing - the Pillow ``Image`` instance used to check if the file was a valid image. It - will also update ``UploadedFile.content_type`` with the image's content type - as determined by Pillow. +* After an :class:`~django.forms.ImageField` has been cleaned and validated, + the ``UploadedFile`` object will have an additional ``image`` attribute + containing the Pillow ``Image`` instance used to check if the file was a + valid image. It will also update ``UploadedFile.content_type`` with the + image's content type as determined by Pillow. * You can now pass a callable that returns an iterable of choices when instantiating a :class:`~django.forms.ChoiceField`. @@ -362,8 +364,9 @@ Forms Generic Views ~~~~~~~~~~~~~ -* Generic views that use :class:`~django.views.generic.list.MultipleObjectMixin` - may now specify the ordering applied to the +* Generic views that use + :class:`~django.views.generic.list.MultipleObjectMixin` may now specify the + ordering applied to the :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` by setting :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` or overriding :meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`. @@ -375,12 +378,13 @@ Generic Views so that it'll perform its lookup using both the primary key and the slug. * The :meth:`~django.views.generic.edit.FormMixin.get_form` method doesn't - require a ``form_class`` to be provided anymore. If not provided ``form_class`` - defaults to :meth:`~django.views.generic.edit.FormMixin.get_form_class`. + require a ``form_class`` to be provided anymore. If not provided + ``form_class`` defaults to + :meth:`~django.views.generic.edit.FormMixin.get_form_class`. * Placeholders in :attr:`ModelFormMixin.success_url - <django.views.generic.edit.ModelFormMixin.success_url>` now support the Python - :py:meth:`str.format` syntax. The legacy ``%(<foo>)s`` syntax is still + <django.views.generic.edit.ModelFormMixin.success_url>` now support the + Python :py:meth:`str.format` syntax. The legacy ``%(<foo>)s`` syntax is still supported but will be removed in Django 1.10. Internationalization @@ -455,8 +459,8 @@ Middleware attribute allows you to customize the redirects issued by the middleware. * A debug message will be logged to the ``django.request`` logger when a - middleware raises a :exc:`~django.core.exceptions.MiddlewareNotUsed` exception - in :setting:`DEBUG` mode. + middleware raises a :exc:`~django.core.exceptions.MiddlewareNotUsed` + exception in :setting:`DEBUG` mode. Migrations ~~~~~~~~~~ @@ -528,7 +532,8 @@ Models <django.db.models.Model.refresh_from_db>`. * You can now get the set of deferred fields for a model using - :meth:`Model.get_deferred_fields() <django.db.models.Model.get_deferred_fields>`. + :meth:`Model.get_deferred_fields() + <django.db.models.Model.get_deferred_fields>`. * Model field ``default``’s are now used when primary key field's are set to ``None``. @@ -556,8 +561,8 @@ System Check Framework Templates ~~~~~~~~~ -* :tfilter:`urlize` now supports domain-only links that include characters after - the top-level domain (e.g. ``djangoproject.com/`` and +* :tfilter:`urlize` now supports domain-only links that include characters + after the top-level domain (e.g. ``djangoproject.com/`` and ``djangoproject.com/download/``). * :tfilter:`urlize` doesn't treat exclamation marks at the end of a domain or @@ -648,8 +653,8 @@ Tests * Added test client support for file uploads with file-like objects. -* A shared cache is now used when testing with an SQLite in-memory database when - using Python 3.4+ and SQLite 3.7.13+. This allows sharing the database +* A shared cache is now used when testing with an SQLite in-memory database + when using Python 3.4+ and SQLite 3.7.13+. This allows sharing the database between threads. Validators @@ -694,7 +699,8 @@ Assigning unsaved objects to relations raises an error .. note:: To more easily allow in-memory usage of models, this change was reverted in - Django 1.8.4 and replaced with a check during ``model.save()``. For example: + Django 1.8.4 and replaced with a check during ``model.save()``. For + example: .. code-block:: pycon @@ -840,8 +846,8 @@ your current fields). A migration for Support for PostgreSQL versions older than 9.0 ---------------------------------------------- -The end of upstream support periods was reached in July 2014 for PostgreSQL 8.4. -As a consequence, Django 1.8 sets 9.0 as the minimum PostgreSQL version it +The end of upstream support periods was reached in July 2014 for PostgreSQL +8.4. As a consequence, Django 1.8 sets 9.0 as the minimum PostgreSQL version it officially supports. This also includes dropping support for PostGIS 1.3 and 1.4 as these versions @@ -877,11 +883,12 @@ creating a test user). The exact privileges required now are detailed in ``AbstractUser.last_login`` allows null values ---------------------------------------------- -The :attr:`AbstractUser.last_login <django.contrib.auth.models.User.last_login>` -field now allows null values. Previously, it defaulted to the time when the user -was created which was misleading if the user never logged in. If you are using -the default user (:class:`django.contrib.auth.models.User`), run the database -migration included in ``contrib.auth``. +The :attr:`AbstractUser.last_login +<django.contrib.auth.models.User.last_login>` field now allows null values. +Previously, it defaulted to the time when the user was created which was +misleading if the user never logged in. If you are using the default user +(:class:`django.contrib.auth.models.User`), run the database migration included +in ``contrib.auth``. If you are using a custom user model that inherits from ``AbstractUser``, you'll need to run :djadmin:`makemigrations` and generate a migration for your @@ -917,14 +924,14 @@ for users who haven't logged in, you can run this query:: Priority of context processors for ``TemplateResponse`` brought in line with ``render`` --------------------------------------------------------------------------------------- -The :class:`~django.template.response.TemplateResponse` constructor is designed to be a -drop-in replacement for the :func:`~django.shortcuts.render` function. However, -it had a slight incompatibility, in that for ``TemplateResponse``, context data -from the passed in context dictionary could be shadowed by context data returned -from context processors, whereas for ``render`` it was the other way -around. This was a bug, and the behavior of ``render`` is more appropriate, -since it allows the globally defined context processors to be overridden locally -in the view. If you were relying on the fact context data in a +The :class:`~django.template.response.TemplateResponse` constructor is designed +to be a drop-in replacement for the :func:`~django.shortcuts.render` function. +However, it had a slight incompatibility, in that for ``TemplateResponse``, +context data from the passed in context dictionary could be shadowed by context +data returned from context processors, whereas for ``render`` it was the other +way around. This was a bug, and the behavior of ``render`` is more appropriate, +since it allows the globally defined context processors to be overridden +locally in the view. If you were relying on the fact context data in a ``TemplateResponse`` could be overridden using a context processor, you will need to change your code. @@ -1281,9 +1288,9 @@ written (and is better written) as:: url("^other/$", views.otherview), ) -Thus ``patterns()`` serves little purpose and is a burden when teaching new users -(answering the newbie's question "why do I need this empty string as the first -argument to ``patterns()``?"). For these reasons, we are deprecating it. +Thus ``patterns()`` serves little purpose and is a burden when teaching new +users (answering the newbie's question "why do I need this empty string as the +first argument to ``patterns()``?"). For these reasons, we are deprecating it. Updating your code is as simple as ensuring that ``urlpatterns`` is a list of ``django.conf.urls.url()`` instances. For example:: @@ -1362,10 +1369,12 @@ the ``url`` that references :func:`django.contrib.sitemaps.views.sitemap`:: name="django.contrib.sitemaps.views.sitemap", ) -to ensure compatibility when reversing by Python path is removed in Django 1.10. +to ensure compatibility when reversing by Python path is removed in Django +1.10. -Similarly for GIS sitemaps, add ``name='django.contrib.gis.sitemaps.views.kml'`` -or ``name='django.contrib.gis.sitemaps.views.kmz'``. +Similarly for GIS sitemaps, add +``name='django.contrib.gis.sitemaps.views.kml'`` or +``name='django.contrib.gis.sitemaps.views.kmz'``. If you are using a Python path for the :setting:`LOGIN_URL` or :setting:`LOGIN_REDIRECT_URL` setting, use the name of the ``url()`` instead. @@ -1376,10 +1385,10 @@ Aggregate methods and modules ----------------------------- The ``django.db.models.sql.aggregates`` and -``django.contrib.gis.db.models.sql.aggregates`` modules (both private API), have -been deprecated as ``django.db.models.aggregates`` and -``django.contrib.gis.db.models.aggregates`` are now also responsible -for SQL generation. The old modules will be removed in Django 1.10. +``django.contrib.gis.db.models.sql.aggregates`` modules (both private API), +have been deprecated as ``django.db.models.aggregates`` and +``django.contrib.gis.db.models.aggregates`` are now also responsible for SQL +generation. The old modules will be removed in Django 1.10. If you were using the old modules, see :doc:`Query Expressions </ref/models/expressions>` for instructions on rewriting custom aggregates @@ -1487,9 +1496,9 @@ It's a legacy option that should no longer be necessary. ---------------- ``django.db.models.fields.subclassing.SubfieldBase`` has been deprecated and -will be removed in Django 1.10. Historically, it was used to handle fields where -type conversion was needed when loading from the database, but it was not used -in ``.values()`` calls or in aggregates. It has been replaced with +will be removed in Django 1.10. Historically, it was used to handle fields +where type conversion was needed when loading from the database, but it was not +used in ``.values()`` calls or in aggregates. It has been replaced with :meth:`~django.db.models.Field.from_db_value`. The new approach doesn't call the :meth:`~django.db.models.Field.to_python` @@ -1522,7 +1531,7 @@ sure to provide a default value for the ``form_class`` argument since it's now optional. Rendering templates loaded by :func:`~django.template.loader.get_template` with a :class:`~django.template.Context` ---------------------------------------------------------------------------------------------------------------------- +------------------------------------------------------------------------------------------------------------------- The return type of :func:`~django.template.loader.get_template` has changed in Django 1.8: instead of a :class:`django.template.Template`, it returns a @@ -1638,21 +1647,21 @@ deprecated: you should rename your ``qn`` arguments to ``compiler``, and call Default value of ``RedirectView.permanent`` ------------------------------------------- -The default value of the -:attr:`RedirectView.permanent <django.views.generic.base.RedirectView.permanent>` -attribute will change from ``True`` to ``False`` in Django 1.9. +The default value of the :attr:`RedirectView.permanent +<django.views.generic.base.RedirectView.permanent>` attribute will change from +``True`` to ``False`` in Django 1.9. Using ``AuthenticationMiddleware`` without ``SessionAuthenticationMiddleware`` ------------------------------------------------------------------------------ -``django.contrib.auth.middleware.SessionAuthenticationMiddleware`` was -added in Django 1.7. In Django 1.7.2, its functionality was moved to -``auth.get_user()`` and, for backwards compatibility, enabled only if +``django.contrib.auth.middleware.SessionAuthenticationMiddleware`` was added in +Django 1.7. In Django 1.7.2, its functionality was moved to ``auth.get_user()`` +and, for backwards compatibility, enabled only if ``'django.contrib.auth.middleware.SessionAuthenticationMiddleware'`` appears in ``MIDDLEWARE_CLASSES``. -In Django 1.10, session verification will be enabled regardless of whether or not -``SessionAuthenticationMiddleware`` is enabled (at which point +In Django 1.10, session verification will be enabled regardless of whether or +not ``SessionAuthenticationMiddleware`` is enabled (at which point ``SessionAuthenticationMiddleware`` will have no significance). You can add it to your ``MIDDLEWARE_CLASSES`` sometime before then to opt-in. Please read the :ref:`upgrade considerations <session-invalidation-on-password-change>` first. @@ -1784,8 +1793,8 @@ remove usage of these features. deprecation warning in the latter class. * Usage of the hardcoded *Hold down "Control", or "Command" on a Mac, to select - more than one.* string to override or append to user-provided ``help_text`` in - forms for ``ManyToMany`` model fields is not performed by Django anymore + more than one.* string to override or append to user-provided ``help_text`` + in forms for ``ManyToMany`` model fields is not performed by Django anymore either at the model or forms layer. * The ``Model._meta.get_(add|change|delete)_permission`` methods are removed. diff --git a/docs/releases/1.9.2.txt b/docs/releases/1.9.2.txt index 77bef25fdb..f97db929a1 100644 --- a/docs/releases/1.9.2.txt +++ b/docs/releases/1.9.2.txt @@ -95,8 +95,8 @@ Bugfixes * Fixed a regression in Django 1.8.5 that broke copying a ``SimpleLazyObject`` with ``copy.copy()`` (:ticket:`26122`). -* Always included ``geometry_field`` in the GeoJSON serializer output regardless - of the ``fields`` parameter (:ticket:`26138`). +* Always included ``geometry_field`` in the GeoJSON serializer output + regardless of the ``fields`` parameter (:ticket:`26138`). * Fixed the ``contrib.gis`` map widgets when using ``USE_THOUSAND_SEPARATOR=True`` (:ticket:`20415`). diff --git a/docs/releases/1.9.5.txt b/docs/releases/1.9.5.txt index bf2c303d70..cc9c6a2754 100644 --- a/docs/releases/1.9.5.txt +++ b/docs/releases/1.9.5.txt @@ -47,5 +47,5 @@ Bugfixes * Fixed a migrations crash on SQLite when renaming the primary key of a model containing a ``ForeignKey`` to ``'self'`` (:ticket:`26384`). -* Fixed ``JSONField`` inadvertently escaping its contents when displaying values - after failed form validation (:ticket:`25532`). +* Fixed ``JSONField`` inadvertently escaping its contents when displaying + values after failed form validation (:ticket:`25532`). diff --git a/docs/releases/1.9.txt b/docs/releases/1.9.txt index b16fc61a64..cac25adb3e 100644 --- a/docs/releases/1.9.txt +++ b/docs/releases/1.9.txt @@ -103,16 +103,18 @@ implementation, though: method does not take a ``request`` argument. The current request is available in ``self.request``. -* The custom ``test_func()`` of :class:`~django.contrib.auth.mixins.UserPassesTestMixin` - does not take a ``user`` argument. The current user is available in - ``self.request.user``. +* The custom ``test_func()`` of + :class:`~django.contrib.auth.mixins.UserPassesTestMixin` does not take a + ``user`` argument. The current user is available in ``self.request.user``. -* The :attr:`permission_required <django.contrib.auth.mixins.PermissionRequiredMixin>` +* The + :attr:`permission_required <django.contrib.auth.mixins.PermissionRequiredMixin>` attribute supports a string (defining one permission) or a list/tuple of strings (defining multiple permissions) that need to be fulfilled to grant access. -* The new :attr:`~django.contrib.auth.mixins.AccessMixin.permission_denied_message` +* The new + :attr:`~django.contrib.auth.mixins.AccessMixin.permission_denied_message` attribute allows passing a message to the ``PermissionDenied`` exception. .. _django-braces: https://django-braces.readthedocs.io/en/latest/index.html @@ -210,7 +212,8 @@ Minor features :func:`~django.contrib.auth.decorators.permission_required` accepts all kinds of iterables, not only list and tuples. -* The new :class:`~django.contrib.auth.middleware.PersistentRemoteUserMiddleware` +* The new + :class:`~django.contrib.auth.middleware.PersistentRemoteUserMiddleware` makes it possible to use ``REMOTE_USER`` for setups where the header is only populated on login pages instead of every request in the session. @@ -767,8 +770,9 @@ behavior. Filesystem-based template loaders catch more specific exceptions ---------------------------------------------------------------- -When using the :class:`filesystem.Loader <django.template.loaders.filesystem.Loader>` -or :class:`app_directories.Loader <django.template.loaders.app_directories.Loader>` +When using the +:class:`filesystem.Loader <django.template.loaders.filesystem.Loader>` or +:class:`app_directories.Loader <django.template.loaders.app_directories.Loader>` template loaders, earlier versions of Django raised a :exc:`~django.template.TemplateDoesNotExist` error if a template source existed but was unreadable. This could happen under many circumstances, such as if @@ -935,8 +939,8 @@ define built-in libraries via the ``'builtins'`` key of :setting:`OPTIONS ``simple_tag`` now wraps tag output in ``conditional_escape`` ------------------------------------------------------------- -In general, template tags do not autoescape their contents, and this behavior is -:ref:`documented <tags-auto-escaping>`. For tags like +In general, template tags do not autoescape their contents, and this behavior +is :ref:`documented <tags-auto-escaping>`. For tags like :class:`~django.template.Library.inclusion_tag`, this is not a problem because the included template will perform autoescaping. For ``assignment_tag()``, the output will be escaped when it is used as a variable in the template. @@ -1135,7 +1139,8 @@ Miscellaneous * The ``FlatPage.enable_comments`` field is removed from the ``FlatPageAdmin`` as it's unused by the application. If your project or a third-party app makes - use of it, :ref:`create a custom ModelAdmin <flatpages-admin>` to add it back. + use of it, :ref:`create a custom ModelAdmin <flatpages-admin>` to add it + back. * The return value of :meth:`~django.test.runner.DiscoverRunner.setup_databases` and the first @@ -1349,8 +1354,8 @@ Miscellaneous * The ``check_aggregate_support()`` method of ``django.db.backends.base.BaseDatabaseOperations`` has been deprecated and - will be removed in Django 2.0. The more general ``check_expression_support()`` - should be used instead. + will be removed in Django 2.0. The more general + ``check_expression_support()`` should be used instead. * ``django.forms.extras`` is deprecated. You can find :class:`~django.forms.SelectDateWidget` in ``django.forms.widgets`` diff --git a/docs/releases/2.0.1.txt b/docs/releases/2.0.1.txt index c160c73908..08814b3c60 100644 --- a/docs/releases/2.0.1.txt +++ b/docs/releases/2.0.1.txt @@ -9,8 +9,8 @@ Django 2.0.1 fixes several bugs in 2.0. Bugfixes ======== -* Fixed a regression in Django 1.11 that added newlines between ``MultiWidget``'s - subwidgets (:ticket:`28890`). +* Fixed a regression in Django 1.11 that added newlines between + ``MultiWidget``'s subwidgets (:ticket:`28890`). * Fixed incorrect class-based model index name generation for models with quoted ``db_table`` (:ticket:`28876`). diff --git a/docs/releases/2.0.5.txt b/docs/releases/2.0.5.txt index 460e8775b8..d9b9eae91e 100644 --- a/docs/releases/2.0.5.txt +++ b/docs/releases/2.0.5.txt @@ -21,5 +21,5 @@ Bugfixes * Fixed a regression in Django 2.0.4 where ``QuerySet.values()`` or ``values_list()`` after combining an annotated and unannotated queryset with - ``union()``, ``difference()``, or ``intersection()`` crashed due to mismatching - columns (:ticket:`29286`). + ``union()``, ``difference()``, or ``intersection()`` crashed due to + mismatching columns (:ticket:`29286`). diff --git a/docs/releases/2.0.txt b/docs/releases/2.0.txt index cc30a64769..d1c013b622 100644 --- a/docs/releases/2.0.txt +++ b/docs/releases/2.0.txt @@ -387,8 +387,9 @@ backends. * To enable support for :class:`~django.db.models.expressions.Window` expressions, set ``DatabaseFeatures.supports_over_clause`` to ``True``. You - may need to customize the ``DatabaseOperations.window_start_rows_start_end()`` - and/or ``window_start_range_start_end()`` methods. + may need to customize the + ``DatabaseOperations.window_start_rows_start_end()`` and/or + ``window_start_range_start_end()`` methods. * Third-party database backends should add a ``DatabaseOperations.cast_char_field_without_max_length`` attribute with the @@ -542,11 +543,11 @@ rebuild tables using a script similar to this:: This script hasn't received extensive testing and needs adaption for various cases such as multiple databases. Feel free to contribute improvements. -In addition, because of a table alteration limitation of SQLite, it's prohibited -to perform :class:`~django.db.migrations.operations.RenameModel` and +In addition, because of a table alteration limitation of SQLite, it's +prohibited to perform :class:`~django.db.migrations.operations.RenameModel` and :class:`~django.db.migrations.operations.RenameField` operations on models or -fields referenced by other models in a transaction. In order to allow migrations -containing these operations to be applied, you must set the +fields referenced by other models in a transaction. In order to allow +migrations containing these operations to be applied, you must set the ``Migration.atomic`` attribute to ``False``. Miscellaneous diff --git a/docs/releases/2.1.txt b/docs/releases/2.1.txt index 4c05e5ae3b..d615d1432a 100644 --- a/docs/releases/2.1.txt +++ b/docs/releases/2.1.txt @@ -76,10 +76,11 @@ Minor features per model <admin-templates-overridden-per-app-or-model>` (besides overridden globally). -* The admin change list and change form object tools can now be :ref:`overridden - per app, per model, or globally <admin-templates-overridden-per-app-or-model>` - with ``change_list_object_tools.html`` and - ``change_form_object_tools.html`` templates. +* The admin change list and change form object tools can now be + :ref:`overridden per app, per model, or globally + <admin-templates-overridden-per-app-or-model>` with + ``change_list_object_tools.html`` and ``change_form_object_tools.html`` + templates. * :meth:`.InlineModelAdmin.has_add_permission` is now passed the parent object as the second positional argument, ``obj``. @@ -148,8 +149,8 @@ Management Commands * The :class:`~django.core.management.BaseCommand` class now uses a custom help formatter so that the standard options like ``--verbosity`` or ``--settings`` - appear last in the help output, giving a more prominent position to subclassed - command's options. + appear last in the help output, giving a more prominent position to + subclassed command's options. Migrations ~~~~~~~~~~ @@ -272,9 +273,9 @@ supports PostgreSQL 9.4 and higher. Removed ``BCryptPasswordHasher`` from the default ``PASSWORD_HASHERS`` setting ------------------------------------------------------------------------------ -If you used bcrypt with Django 1.4 or 1.5 (before ``BCryptSHA256PasswordHasher`` -was added in Django 1.6), you might have some passwords that use the -``BCryptPasswordHasher`` hasher. +If you used bcrypt with Django 1.4 or 1.5 (before +``BCryptSHA256PasswordHasher`` was added in Django 1.6), you might have some +passwords that use the ``BCryptPasswordHasher`` hasher. You can check if that's the case like this:: @@ -382,10 +383,11 @@ Miscellaneous conflicts with the class given to model fields named "box". * Since the admin's ``actions.html``, ``change_list_results.html``, - ``date_hierarchy.html``, ``pagination.html``, ``prepopulated_fields_js.html``, - ``search_form.html``, and ``submit_line.html`` templates can now be - overridden per app or per model, you may need to rename existing templates - with those names that were written for a different purpose. + ``date_hierarchy.html``, ``pagination.html``, + ``prepopulated_fields_js.html``, ``search_form.html``, and + ``submit_line.html`` templates can now be overridden per app or per model, + you may need to rename existing templates with those names that were written + for a different purpose. * ``QuerySet.raw()`` now caches its results like regular querysets. Use ``iterator()`` if you don't want caching. diff --git a/docs/releases/2.2.3.txt b/docs/releases/2.2.3.txt index e1df96f216..1e299b99f2 100644 --- a/docs/releases/2.2.3.txt +++ b/docs/releases/2.2.3.txt @@ -18,9 +18,9 @@ requests made via HTTP as using HTTPS. This entails incorrect results for requests would not be redirected to HTTPS in accordance with :setting:`SECURE_SSL_REDIRECT`. -``HttpRequest.scheme`` now respects :setting:`SECURE_PROXY_SSL_HEADER`, if it is -configured, and the appropriate header is set on the request, for both HTTP and -HTTPS requests. +``HttpRequest.scheme`` now respects :setting:`SECURE_PROXY_SSL_HEADER`, if it +is configured, and the appropriate header is set on the request, for both HTTP +and HTTPS requests. If you deploy Django behind a reverse-proxy that forwards HTTP requests, and that connects to Django via HTTPS, be sure to verify that your application diff --git a/docs/releases/3.0.txt b/docs/releases/3.0.txt index 3fa3cd8410..1332a646ae 100644 --- a/docs/releases/3.0.txt +++ b/docs/releases/3.0.txt @@ -358,9 +358,9 @@ Tests new :option:`test -k` option. * HTML comparison, as used by - :meth:`~django.test.SimpleTestCase.assertHTMLEqual`, now treats text, character - references, and entity references that refer to the same character as - equivalent. + :meth:`~django.test.SimpleTestCase.assertHTMLEqual`, now treats text, + character references, and entity references that refer to the same character + as equivalent. * :class:`~django.test.runner.DiscoverRunner` can now spawn a debugger at each error or failure using the :option:`test --pdb` option. diff --git a/docs/releases/4.1.txt b/docs/releases/4.1.txt index 8a3a7984a1..10b9f3728a 100644 --- a/docs/releases/4.1.txt +++ b/docs/releases/4.1.txt @@ -247,8 +247,8 @@ Forms transitional renderers will be deprecated, for removal in Django 6.0. The ``FORM_RENDERER`` declaration can be removed at that time. -* If the new ``<div>`` output style is not appropriate for your project, you should - define a renderer subclass specifying +* If the new ``<div>`` output style is not appropriate for your project, you + should define a renderer subclass specifying :attr:`~django.forms.renderers.BaseRenderer.form_template_name` and :attr:`~django.forms.renderers.BaseRenderer.formset_template_name` for your required style, and set :setting:`FORM_RENDERER` accordingly. diff --git a/docs/releases/5.0.2.txt b/docs/releases/5.0.2.txt index 1da6dc02d9..59524e65f7 100644 --- a/docs/releases/5.0.2.txt +++ b/docs/releases/5.0.2.txt @@ -35,9 +35,9 @@ Bugfixes management command when a base queryset used ``prefetch_related()`` (:ticket:`35159`). -* Fixed a regression in Django 5.0 that caused the ``request_finished`` signal to - sometimes not be fired when running Django through an ASGI server, resulting - in potential resource leaks (:ticket:`35059`). +* Fixed a regression in Django 5.0 that caused the ``request_finished`` signal + to sometimes not be fired when running Django through an ASGI server, + resulting in potential resource leaks (:ticket:`35059`). * Fixed a bug in Django 5.0 that caused a migration crash on MySQL when adding a ``BinaryField``, ``TextField``, ``JSONField``, or ``GeometryField`` with a diff --git a/docs/releases/5.1.txt b/docs/releases/5.1.txt index a57bf60cbd..0a5ececcca 100644 --- a/docs/releases/5.1.txt +++ b/docs/releases/5.1.txt @@ -98,8 +98,9 @@ unauthenticated requests by using the new support setting ``login_url`` or ``redirect_field_name`` via the :class:`~django.contrib.auth.mixins.LoginRequiredMixin`. -To enable this, add ``"django.contrib.auth.middleware.LoginRequiredMiddleware"`` -to your :setting:`MIDDLEWARE` setting. +To enable this, add +``"django.contrib.auth.middleware.LoginRequiredMiddleware"`` to your +:setting:`MIDDLEWARE` setting. Minor features -------------- diff --git a/docs/releases/5.2.4.txt b/docs/releases/5.2.4.txt index 7b10e944bd..505a473a21 100644 --- a/docs/releases/5.2.4.txt +++ b/docs/releases/5.2.4.txt @@ -9,9 +9,10 @@ Django 5.2.4 fixes several bugs in 5.2.3. Bugfixes ======== -* Fixed a regression in Django 5.2.2 where :meth:`HttpRequest.get_preferred_type() - <django.http.HttpRequest.get_preferred_type>` incorrectly preferred more - specific media types with a lower quality (:ticket:`36447`). +* Fixed a regression in Django 5.2.2 where + :meth:`HttpRequest.get_preferred_type() <django.http.HttpRequest.get_preferred_type>` + incorrectly preferred more specific media types with a lower quality + (:ticket:`36447`). * Fixed a regression in Django 5.2.3 where ``Value(None, JSONField())`` used in a :class:`~django.db.models.expressions.When` condition was incorrectly diff --git a/docs/releases/security.txt b/docs/releases/security.txt index 353f1a9b96..46c5dbc49d 100644 --- a/docs/releases/security.txt +++ b/docs/releases/security.txt @@ -713,8 +713,9 @@ Versions affected August 1, 2019 - :cve:`2019-14232` ---------------------------------- -Denial-of-service possibility in ``django.utils.text.Truncator``. `Full -description <https://www.djangoproject.com/weblog/2019/aug/01/security-releases/>`__ +Denial-of-service possibility in ``django.utils.text.Truncator``. +`Full description +<https://www.djangoproject.com/weblog/2019/aug/01/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -726,8 +727,9 @@ Versions affected July 1, 2019 - :cve:`2019-12781` -------------------------------- -Incorrect HTTP detection with reverse-proxy connecting via HTTPS. `Full -description <https://www.djangoproject.com/weblog/2019/jul/01/security-releases/>`__ +Incorrect HTTP detection with reverse-proxy connecting via HTTPS. +`Full description +<https://www.djangoproject.com/weblog/2019/jul/01/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -739,8 +741,9 @@ Versions affected June 3, 2019 - :cve:`2019-12308` -------------------------------- -XSS via "Current URL" link generated by ``AdminURLFieldWidget``. `Full -description <https://www.djangoproject.com/weblog/2019/jun/03/security-releases/>`__ +XSS via "Current URL" link generated by ``AdminURLFieldWidget``. +`Full description +<https://www.djangoproject.com/weblog/2019/jun/03/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -855,8 +858,9 @@ Versions affected September 5, 2017 - :cve:`2017-12794` ------------------------------------- -Possible XSS in traceback section of technical 500 debug page. `Full -description <https://www.djangoproject.com/weblog/2017/sep/05/security-releases/>`__ +Possible XSS in traceback section of technical 500 debug page. +`Full description +<https://www.djangoproject.com/weblog/2017/sep/05/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -867,8 +871,9 @@ Versions affected April 4, 2017 - :cve:`2017-7234` -------------------------------- -Open redirect vulnerability in ``django.views.static.serve()``. `Full -description <https://www.djangoproject.com/weblog/2017/apr/04/security-releases/>`__ +Open redirect vulnerability in ``django.views.static.serve()``. +`Full description +<https://www.djangoproject.com/weblog/2017/apr/04/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -881,7 +886,8 @@ April 4, 2017 - :cve:`2017-7233` -------------------------------- Open redirect and possible XSS attack via user-supplied numeric redirect URLs. -`Full description <https://www.djangoproject.com/weblog/2017/apr/04/security-releases/>`__ +`Full description +<https://www.djangoproject.com/weblog/2017/apr/04/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -906,8 +912,9 @@ Versions affected November 1, 2016 - :cve:`2016-9013` ----------------------------------- -User with hardcoded password created when running tests on Oracle. `Full -description <https://www.djangoproject.com/weblog/2016/nov/01/security-releases/>`__ +User with hardcoded password created when running tests on Oracle. +`Full description +<https://www.djangoproject.com/weblog/2016/nov/01/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -994,7 +1001,8 @@ August 18, 2015 - :cve:`2015-5963` / :cve:`2015-5964` ----------------------------------------------------- Denial-of-service possibility in ``logout()`` view by filling session store. -`Full description <https://www.djangoproject.com/weblog/2015/aug/18/security-releases/>`__ +`Full description +<https://www.djangoproject.com/weblog/2015/aug/18/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -1017,8 +1025,9 @@ Versions affected July 8, 2015 - :cve:`2015-5144` ------------------------------- -Header injection possibility since validators accept newlines in input. `Full -description <https://www.djangoproject.com/weblog/2015/jul/08/security-releases/>`__ +Header injection possibility since validators accept newlines in input. +`Full description +<https://www.djangoproject.com/weblog/2015/jul/08/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -1030,8 +1039,9 @@ Versions affected July 8, 2015 - :cve:`2015-5143` ------------------------------- -Denial-of-service possibility by filling session store. `Full -description <https://www.djangoproject.com/weblog/2015/jul/08/security-releases/>`__ +Denial-of-service possibility by filling session store. +`Full description +<https://www.djangoproject.com/weblog/2015/jul/08/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -1054,8 +1064,9 @@ Versions affected March 18, 2015 - :cve:`2015-2317` --------------------------------- -Mitigated possible XSS attack via user-supplied redirect URLs. `Full -description <https://www.djangoproject.com/weblog/2015/mar/18/security-releases/>`__ +Mitigated possible XSS attack via user-supplied redirect URLs. +`Full description +<https://www.djangoproject.com/weblog/2015/mar/18/security-releases/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -1145,7 +1156,8 @@ August 20, 2014 - :cve:`2014-0483` ---------------------------------- Data leakage via querystring manipulation in admin. -`Full description <https://www.djangoproject.com/weblog/2014/aug/20/security/>`__ +`Full description +<https://www.djangoproject.com/weblog/2014/aug/20/security/>`__ Versions affected ~~~~~~~~~~~~~~~~~ @@ -1276,7 +1288,8 @@ Denial-of-service via large passwords. `Full description Versions affected ~~~~~~~~~~~~~~~~~ -* Django 1.4 :commit:`(patch <3f3d887a6844ec2db743fee64c9e53e04d39a368>` and :commit:`Python compatibility fix) <6903d1690a92aa040adfb0c8eb37cf62e4206714>` +* Django 1.4 :commit:`(patch <3f3d887a6844ec2db743fee64c9e53e04d39a368>` and + :commit:`Python compatibility fix) <6903d1690a92aa040adfb0c8eb37cf62e4206714>` * Django 1.5 :commit:`(patch) <22b74fa09d7ccbc8c52270d648a0da7f3f0fa2bc>` September 10, 2013 - :cve:`2013-4315` diff --git a/docs/topics/async.txt b/docs/topics/async.txt index c5cbabeea7..3c6758bd57 100644 --- a/docs/topics/async.txt +++ b/docs/topics/async.txt @@ -230,8 +230,8 @@ its own thread). The async context can be imposed upon you by the environment in which you are running your Django code. For example, Jupyter_ notebooks and IPython_ -interactive shells both transparently provide an active event loop so that it is -easier to interact with asynchronous APIs. +interactive shells both transparently provide an active event loop so that it +is easier to interact with asynchronous APIs. If you're using an IPython shell, you can disable this event loop by running: diff --git a/docs/topics/auth/customizing.txt b/docs/topics/auth/customizing.txt index 5ef1ea5bbd..505beb5289 100644 --- a/docs/topics/auth/customizing.txt +++ b/docs/topics/auth/customizing.txt @@ -81,8 +81,8 @@ backends that follow. for the duration of that session whenever access to the currently authenticated user is needed. This effectively means that authentication sources are cached on a per-session basis, so if you change - :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if - you need to force users to re-authenticate using different methods. A + :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data + if you need to force users to re-authenticate using different methods. A simple way to do that is to execute ``Session.objects.all().delete()``. Writing an authentication backend @@ -474,8 +474,8 @@ different user model. Instead of referring to :class:`~django.contrib.auth.models.User` directly, you should reference the user model using ``django.contrib.auth.get_user_model()``. This method will return the - currently active user model -- the custom user model if one is specified, or - :class:`~django.contrib.auth.models.User` otherwise. + currently active user model -- the custom user model if one is specified, + or :class:`~django.contrib.auth.models.User` otherwise. When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the :setting:`AUTH_USER_MODEL` @@ -491,8 +491,8 @@ different user model. on_delete=models.CASCADE, ) - When connecting to signals sent by the user model, you should specify - the custom model using the :setting:`AUTH_USER_MODEL` setting. For example:: + When connecting to signals sent by the user model, you should specify the + custom model using the :setting:`AUTH_USER_MODEL` setting. For example:: from django.conf import settings from django.db.models.signals import post_save @@ -682,9 +682,9 @@ The following attributes and methods are available on any subclass of .. attribute:: models.AbstractBaseUser.is_anonymous Read-only attribute which is always ``False``. This is a way of - differentiating :class:`~models.User` and :class:`~models.AnonymousUser` - objects. Generally, you should prefer using - :attr:`~models.User.is_authenticated` to this attribute. + differentiating :class:`~models.User` and + :class:`~models.AnonymousUser` objects. Generally, you should prefer + using :attr:`~models.User.is_authenticated` to this attribute. .. method:: models.AbstractBaseUser.set_password(raw_password) @@ -710,8 +710,8 @@ The following attributes and methods are available on any subclass of Marks the user as having no password set. This isn't the same as having a blank string for a password. - :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password` for this user - will never return ``True``. Doesn't save the + :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password` for + this user will never return ``True``. Doesn't save the :class:`~django.contrib.auth.models.AbstractBaseUser` object. You may need this if authentication for your application takes place @@ -720,8 +720,8 @@ The following attributes and methods are available on any subclass of .. method:: models.AbstractBaseUser.has_usable_password() Returns ``False`` if - :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password` has - been called for this user. + :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password` + has been called for this user. .. method:: models.AbstractBaseUser.get_session_auth_hash() @@ -751,8 +751,9 @@ defines ``username``, ``email``, ``is_staff``, ``is_active``, ``is_superuser``, ``last_login``, and ``date_joined`` fields the same as Django's default user, you can install Django's :class:`~django.contrib.auth.models.UserManager`; however, if your user model defines different fields, you'll need to define a -custom manager that extends :class:`~django.contrib.auth.models.BaseUserManager` -providing two additional methods: +custom manager that extends +:class:`~django.contrib.auth.models.BaseUserManager` providing two additional +methods: .. class:: models.CustomUserManager @@ -808,10 +809,11 @@ utility methods: Extending Django's default ``User`` ----------------------------------- -If you're entirely happy with Django's :class:`~django.contrib.auth.models.User` -model, but you want to add some additional profile information, you could -subclass :class:`django.contrib.auth.models.AbstractUser` and add your custom -profile fields, although we'd recommend a separate model as described in +If you're entirely happy with Django's +:class:`~django.contrib.auth.models.User` model, but you want to add some +additional profile information, you could subclass +:class:`django.contrib.auth.models.AbstractUser` and add your custom profile +fields, although we'd recommend a separate model as described in :ref:`specifying-custom-user-model`. ``AbstractUser`` provides the full implementation of the default :class:`~django.contrib.auth.models.User` as an :ref:`abstract model <abstract-base-classes>`. diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt index 28bc63b739..c4adb1d1fc 100644 --- a/docs/topics/auth/default.txt +++ b/docs/topics/auth/default.txt @@ -1042,8 +1042,8 @@ arguments in the URLconf, these will be passed on to the view. For example:: ), ] -All views are :doc:`class-based </topics/class-based-views/index>`, which allows -you to easily customize them by subclassing. +All views are :doc:`class-based </topics/class-based-views/index>`, which +allows you to easily customize them by subclassing. .. _all-authentication-views: @@ -1155,8 +1155,8 @@ implementation details see :ref:`using-the-views`. For more on sites, see :doc:`/ref/contrib/sites`. If you'd prefer not to call the template :file:`registration/login.html`, - you can pass the ``template_name`` parameter via the extra arguments to - the ``as_view`` method in your URLconf. For example, this URLconf line would + you can pass the ``template_name`` parameter via the extra arguments to the + ``as_view`` method in your URLconf. For example, this URLconf line would use :file:`myapp/login.html` instead:: path("accounts/login/", auth_views.LoginView.as_view(template_name="myapp/login.html")), @@ -1799,8 +1799,8 @@ the logged-in user has any permissions in the ``foo`` app: {% if perms.foo %} Evaluating a two-level-attribute lookup as a boolean is a proxy to -:meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For example, -to check if the logged-in user has the permission ``foo.add_vote``: +:meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For +example, to check if the logged-in user has the permission ``foo.add_vote``: .. code-block:: html+django diff --git a/docs/topics/auth/passwords.txt b/docs/topics/auth/passwords.txt index ca25f9ddb6..0976ae4fa2 100644 --- a/docs/topics/auth/passwords.txt +++ b/docs/topics/auth/passwords.txt @@ -211,8 +211,8 @@ hashing. This deliberately slows down attackers, making attacks against hashed passwords harder. However, as computing power increases, the number of iterations needs to be increased. We've chosen a reasonable default (and will increase it with each release of Django), but you may wish to tune it up or -down, depending on your security needs and available processing power. To do so, -you'll subclass the appropriate algorithm and override the ``iterations`` +down, depending on your security needs and available processing power. To do +so, you'll subclass the appropriate algorithm and override the ``iterations`` parameter (use the ``rounds`` parameter when subclassing a bcrypt hasher). For example, to increase the number of iterations used by the default PBKDF2 algorithm: diff --git a/docs/topics/cache.txt b/docs/topics/cache.txt index a0aba96863..6e562f8b7e 100644 --- a/docs/topics/cache.txt +++ b/docs/topics/cache.txt @@ -92,8 +92,8 @@ To use Memcached with Django: port on which Memcached is running, or to a ``unix:path`` value, where ``path`` is the path to a Memcached Unix socket file. -In this example, Memcached is running on localhost (127.0.0.1) port 11211, using -the ``pymemcache`` binding:: +In this example, Memcached is running on localhost (127.0.0.1) port 11211, +using the ``pymemcache`` binding:: CACHES = { "default": { @@ -188,7 +188,7 @@ To use Redis as your cache backend with Django: * Set :setting:`LOCATION <CACHES-LOCATION>` to the URL pointing to your Redis instance, using the appropriate scheme. See the ``redis-py`` docs for `details on the available schemes - <https://redis-py.readthedocs.io/en/stable/connections.html#redis.connection.ConnectionPool.from_url>`_. + <https://redis-py.readthedocs.io/en/stable/connections.html#redis.connection.ConnectionPool.from_url>`__. For example, if Redis is running on localhost (127.0.0.1) port 6379:: @@ -391,11 +391,11 @@ Local-memory caching -------------------- This is the default cache if another is not specified in your settings file. If -you want the speed advantages of in-memory caching but don't have the capability -of running Memcached, consider the local-memory cache backend. This cache is -per-process (see below) and thread-safe. To use it, set :setting:`BACKEND -<CACHES-BACKEND>` to ``"django.core.cache.backends.locmem.LocMemCache"``. For -example:: +you want the speed advantages of in-memory caching but don't have the +capability of running Memcached, consider the local-memory cache backend. This +cache is per-process (see below) and thread-safe. To use it, set +:setting:`BACKEND <CACHES-BACKEND>` to +``"django.core.cache.backends.locmem.LocMemCache"``. For example:: CACHES = { "default": { @@ -470,10 +470,10 @@ behavior. These arguments are provided as additional keys in the :setting:`CACHES` setting. Valid arguments are as follows: * :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in - seconds, to use for the cache. This argument defaults to ``300`` seconds (5 minutes). - You can set ``TIMEOUT`` to ``None`` so that, by default, cache keys never - expire. A value of ``0`` causes keys to immediately expire (effectively - "don't cache"). + seconds, to use for the cache. This argument defaults to ``300`` seconds + (5 minutes). You can set ``TIMEOUT`` to ``None`` so that, by default, cache + keys never expire. A value of ``0`` causes keys to immediately expire + (effectively "don't cache"). * :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be passed to the cache backend. The list of valid options will vary @@ -623,11 +623,11 @@ Then, add the following required settings to your Django settings file: prevent key collisions. Use an empty string if you don't care. ``FetchFromCacheMiddleware`` caches GET and HEAD responses with status 200, -where the request and response headers allow. Responses to requests for the same -URL with different query parameters are considered to be unique pages and are -cached separately. This middleware expects that a HEAD request is answered with -the same response headers as the corresponding GET request; in which case it can -return a cached GET response for HEAD request. +where the request and response headers allow. Responses to requests for the +same URL with different query parameters are considered to be unique pages and +are cached separately. This middleware expects that a HEAD request is answered +with the same response headers as the corresponding GET request; in which case +it can return a cached GET response for HEAD request. Additionally, ``UpdateCacheMiddleware`` automatically sets a few headers in each :class:`~django.http.HttpResponse` which affect :ref:`downstream caches @@ -732,8 +732,8 @@ approach couples your view to the cache system, which is not ideal for several reasons. For instance, you might want to reuse the view functions on another, cache-less site, or you might want to distribute the views to people who might want to use them without being cached. The solution to these problems is to -specify the per-view cache in the URLconf rather than next to the view functions -themselves. +specify the per-view cache in the URLconf rather than next to the view +functions themselves. You can do so by wrapping the view function with ``cache_page`` when you refer to it in the URLconf. Here's the old URLconf from earlier:: @@ -773,11 +773,11 @@ example: {% endcache %} Sometimes you might want to cache multiple copies of a fragment depending on -some dynamic data that appears inside the fragment. For example, you might want a -separate cached copy of the sidebar used in the previous example for every user -of your site. Do this by passing one or more additional arguments, which may be -variables with or without filters, to the ``{% cache %}`` template tag to -uniquely identify the cache fragment: +some dynamic data that appears inside the fragment. For example, you might want +a separate cached copy of the sidebar used in the previous example for every +user of your site. Do this by passing one or more additional arguments, which +may be variables with or without filters, to the ``{% cache %}`` template tag +to uniquely identify the cache fragment: .. code-block:: html+django @@ -816,10 +816,10 @@ equivalent: This feature is useful in avoiding repetition in templates. You can set the timeout in a variable, in one place, and reuse that value. -By default, the cache tag will try to use the cache called "template_fragments". -If no such cache exists, it will fall back to using the default cache. You may -select an alternate cache backend to use with the ``using`` keyword argument, -which must be the last argument to the tag. +By default, the cache tag will try to use the cache called +"template_fragments". If no such cache exists, it will fall back to using the +default cache. You may select an alternate cache backend to use with the +``using`` keyword argument, which must be the last argument to the tag. .. code-block:: html+django @@ -830,10 +830,10 @@ It is considered an error to specify a cache name that is not configured. .. function:: django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None) If you want to obtain the cache key used for a cached fragment, you can use -``make_template_fragment_key``. ``fragment_name`` is the same as second argument -to the ``cache`` template tag; ``vary_on`` is a list of all additional arguments -passed to the tag. This function can be useful for invalidating or overwriting -a cached item, for example: +``make_template_fragment_key``. ``fragment_name`` is the same as second +argument to the ``cache`` template tag; ``vary_on`` is a list of all additional +arguments passed to the tag. This function can be useful for invalidating or +overwriting a cached item, for example: .. code-block:: pycon @@ -1013,8 +1013,8 @@ actually exist in the cache (and haven't expired): .. method:: cache.set_many(dict, timeout) -To set multiple values more efficiently, use ``set_many()`` to pass a dictionary -of key-value pairs: +To set multiple values more efficiently, use ``set_many()`` to pass a +dictionary of key-value pairs: .. code-block:: pycon @@ -1382,8 +1382,9 @@ are equivalent:: The headers you pass to ``vary_on_headers`` are not case sensitive; ``"User-Agent"`` is the same thing as ``"user-agent"``. -You can also use a helper function, :func:`django.utils.cache.patch_vary_headers`, -directly. This function sets, or adds to, the ``Vary header``. For example:: +You can also use a helper function, +:func:`django.utils.cache.patch_vary_headers`, directly. This function sets, or +adds to, the ``Vary header``. For example:: from django.shortcuts import render from django.utils.cache import patch_vary_headers diff --git a/docs/topics/checks.txt b/docs/topics/checks.txt index f936ecb00f..626f40a3b1 100644 --- a/docs/topics/checks.txt +++ b/docs/topics/checks.txt @@ -15,9 +15,10 @@ WSGI stack that is used in deployment. If you need to run system checks on your deployment server, trigger them explicitly using :djadmin:`check`. Serious errors will prevent Django commands (such as :djadmin:`runserver`) from -running at all. Minor problems are reported to the console. If you have inspected -the cause of a warning and are happy to ignore it, you can hide specific warnings -using the :setting:`SILENCED_SYSTEM_CHECKS` setting in your project settings file. +running at all. Minor problems are reported to the console. If you have +inspected the cause of a warning and are happy to ignore it, you can hide +specific warnings using the :setting:`SILENCED_SYSTEM_CHECKS` setting in your +project settings file. A full list of all checks that can be raised by Django can be found in the :doc:`System check reference </ref/checks>`. @@ -61,8 +62,8 @@ The ``**kwargs`` argument is required for future expansion. Messages -------- -The function must return a list of messages. If no problems are found as a result -of the check, the check function must return an empty list. +The function must return a list of messages. If no problems are found as a +result of the check, the check function must return an empty list. The warnings and errors raised by the check method must be instances of :class:`~django.core.checks.CheckMessage`. An instance of @@ -145,9 +146,9 @@ delegate each check to separate methods. Consider an example where you are implementing a custom field named ``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the -constructor of ``IntegerField``. You may want to add a check to ensure that users -provide a min value that is less than or equal to the max value. The following -code snippet shows how you can implement this check:: +constructor of ``IntegerField``. You may want to add a check to ensure that +users provide a min value that is less than or equal to the max value. The +following code snippet shows how you can implement this check:: from django.core import checks from django.db import models @@ -186,7 +187,8 @@ If you wanted to add checks to a model manager, you would take the same approach on your subclass of :class:`~django.db.models.Manager`. If you want to add a check to a model class, the approach is *almost* the same: -the only difference is that the check is a classmethod, not an instance method:: +the only difference is that the check is a classmethod, not an instance +method:: class MyModel(models.Model): @classmethod diff --git a/docs/topics/class-based-views/generic-display.txt b/docs/topics/class-based-views/generic-display.txt index e72fe5cfe6..aa39716611 100644 --- a/docs/topics/class-based-views/generic-display.txt +++ b/docs/topics/class-based-views/generic-display.txt @@ -4,8 +4,8 @@ Built-in class-based generic views Writing web applications can be monotonous, because we repeat certain patterns again and again. Django tries to take away some of that monotony at the model -and template layers, but web developers also experience this boredom at the view -level. +and template layers, but web developers also experience this boredom at the +view level. Django's *generic views* were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that @@ -229,8 +229,8 @@ you can override it to send more:: Generally, ``get_context_data`` will merge the context data of all parent classes with those of the current class. To preserve this behavior in your own classes where you want to alter the context, you should be sure to call - ``get_context_data`` on the super class. When no two classes try to define the - same key, this will give the expected results. However if any class + ``get_context_data`` on the super class. When no two classes try to define + the same key, this will give the expected results. However if any class attempts to override a key after parent classes have set it (after the call to super), any children of that class will also need to explicitly set it after super if they want to be sure to override all parents. If you're @@ -295,8 +295,8 @@ list of books by a particular publisher, you can use the same technique:: template_name = "books/acme_list.html" Notice that along with a filtered ``queryset``, we're also using a custom -template name. If we didn't, the generic view would use the same template as the -"vanilla" object list, which might not be what we want. +template name. If we didn't, the generic view would use the same template as +the "vanilla" object list, which might not be what we want. Also notice that this isn't a very elegant way of doing publisher-specific books. If we want to add another publisher page, we'd need another handful of @@ -317,8 +317,8 @@ Dynamic filtering Another common need is to filter down the objects given in a list page by some key in the URL. Earlier we hardcoded the publisher's name in the URLconf, but -what if we wanted to write a view that displayed all the books by some arbitrary -publisher? +what if we wanted to write a view that displayed all the books by some +arbitrary publisher? Handily, the ``ListView`` has a :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method we diff --git a/docs/topics/class-based-views/generic-editing.txt b/docs/topics/class-based-views/generic-editing.txt index 45c36409ce..2e200b35ff 100644 --- a/docs/topics/class-based-views/generic-editing.txt +++ b/docs/topics/class-based-views/generic-editing.txt @@ -84,7 +84,8 @@ special requirements; see below for examples. You don't even need to provide a ``success_url`` for :class:`~django.views.generic.edit.CreateView` or :class:`~django.views.generic.edit.UpdateView` - they will use -:meth:`~django.db.models.Model.get_absolute_url` on the model object if available. +:meth:`~django.db.models.Model.get_absolute_url` on the model object if +available. If you want to use a custom :class:`~django.forms.ModelForm` (for instance to add extra validation), set @@ -146,8 +147,9 @@ inner ``Meta`` class on :class:`~django.forms.ModelForm`. Unless you define the form class in another way, the attribute is required and the view will raise an :exc:`~django.core.exceptions.ImproperlyConfigured` exception if it's not. -If you specify both the :attr:`~django.views.generic.edit.ModelFormMixin.fields` -and :attr:`~django.views.generic.edit.FormMixin.form_class` attributes, an +If you specify both the +:attr:`~django.views.generic.edit.ModelFormMixin.fields` and +:attr:`~django.views.generic.edit.FormMixin.form_class` attributes, an :exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised. Finally, we hook these new views into the URLconf: diff --git a/docs/topics/class-based-views/index.txt b/docs/topics/class-based-views/index.txt index f69f70cf5a..6af39bca9a 100644 --- a/docs/topics/class-based-views/index.txt +++ b/docs/topics/class-based-views/index.txt @@ -23,8 +23,8 @@ Basic examples ============== Django provides base view classes which will suit a wide range of applications. -All views inherit from the :class:`~django.views.generic.base.View` class, which -handles linking the view into the URLs, HTTP method dispatching and other +All views inherit from the :class:`~django.views.generic.base.View` class, +which handles linking the view into the URLs, HTTP method dispatching and other common features. :class:`~django.views.generic.base.RedirectView` provides a HTTP redirect, and :class:`~django.views.generic.base.TemplateView` extends the base class to make it also render a template. @@ -84,7 +84,8 @@ method instead, which provides a function-like entry to class-based views:: For more information on how to use the built in generic views, consult the next -topic on :doc:`generic class-based views</topics/class-based-views/generic-display>`. +topic on +:doc:`generic class-based views</topics/class-based-views/generic-display>`. .. _supporting-other-http-methods: diff --git a/docs/topics/class-based-views/intro.txt b/docs/topics/class-based-views/intro.txt index ab84c8c9ac..429ca38a65 100644 --- a/docs/topics/class-based-views/intro.txt +++ b/docs/topics/class-based-views/intro.txt @@ -17,7 +17,8 @@ The relationship and history of generic views, class-based views, and class-base In the beginning there was only the view function contract, Django passed your function an :class:`~django.http.HttpRequest` and expected back an -:class:`~django.http.HttpResponse`. This was the extent of what Django provided. +:class:`~django.http.HttpResponse`. This was the extent of what Django +provided. Early on it was recognized that there were common idioms and patterns found in view development. Function-based generic views were introduced to abstract diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt index bb1a6349dc..6b2c435e1b 100644 --- a/docs/topics/class-based-views/mixins.txt +++ b/docs/topics/class-based-views/mixins.txt @@ -112,11 +112,10 @@ context data for template renders. To then make a :class:`~django.template.response.TemplateResponse`, :class:`DetailView` uses -:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`, -which extends :class:`~django.views.generic.base.TemplateResponseMixin`, -overriding -:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names` -as discussed above. It actually provides a fairly sophisticated set of options, +:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`, which +extends :class:`~django.views.generic.base.TemplateResponseMixin`, overriding +:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names` as +discussed above. It actually provides a fairly sophisticated set of options, but the main one that most people are going to use is ``<app_label>/<model_name>_detail.html``. The ``_detail`` part can be changed by setting @@ -135,20 +134,18 @@ paginated) list of objects, typically a using that list of objects. To get the objects, :class:`~django.views.generic.list.ListView` uses -:class:`~django.views.generic.list.MultipleObjectMixin`, which -provides both -:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` -and -:meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`. Unlike -with :class:`~django.views.generic.detail.SingleObjectMixin`, there's no need -to key off parts of the URL to figure out the queryset to work with, so the -default uses the +:class:`~django.views.generic.list.MultipleObjectMixin`, which provides both +:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` and +:meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`. +Unlike with :class:`~django.views.generic.detail.SingleObjectMixin`, there's no +need to key off parts of the URL to figure out the queryset to work with, so +the default uses the :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` or -:attr:`~django.views.generic.list.MultipleObjectMixin.model` attribute -on the view class. A common reason to override -:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` -here would be to dynamically vary the objects, such as depending on -the current user or to exclude posts in the future for a blog. +:attr:`~django.views.generic.list.MultipleObjectMixin.model` attribute on the +view class. A common reason to override +:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` here would +be to dynamically vary the objects, such as depending on the current user or to +exclude posts in the future for a blog. :class:`~django.views.generic.list.MultipleObjectMixin` also overrides :meth:`~django.views.generic.base.ContextMixin.get_context_data` to @@ -159,13 +156,12 @@ it. To make a :class:`~django.template.response.TemplateResponse`, :class:`ListView` then uses -:class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`; -as with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin` +:class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`; as +with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin` above, this overrides ``get_template_names()`` to provide :meth:`a range of -options <django.views.generic.list.MultipleObjectTemplateResponseMixin>`, -with the most commonly-used being -``<app_label>/<model_name>_list.html``, with the ``_list`` part again -being taken from the +options <django.views.generic.list.MultipleObjectTemplateResponseMixin>`, with +the most commonly-used being ``<app_label>/<model_name>_list.html``, with the +``_list`` part again being taken from the :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix` attribute. (The date based generic views use suffixes such as ``_archive``, ``_archive_year`` and so on to use different templates for the various @@ -635,8 +631,9 @@ For example, a JSON mixin might look something like this:: information on how to correctly transform Django models and querysets into JSON. -This mixin provides a ``render_to_json_response()`` method with the same signature -as :func:`~django.views.generic.base.TemplateResponseMixin.render_to_response`. +This mixin provides a ``render_to_json_response()`` method with the same +signature as +:func:`~django.views.generic.base.TemplateResponseMixin.render_to_response`. To use it, we need to mix it into a ``TemplateView`` for example, and override ``render_to_response()`` to call ``render_to_json_response()`` instead:: diff --git a/docs/topics/conditional-view-processing.txt b/docs/topics/conditional-view-processing.txt index 2929acd9c6..e2aef9bc54 100644 --- a/docs/topics/conditional-view-processing.txt +++ b/docs/topics/conditional-view-processing.txt @@ -11,8 +11,9 @@ used for all HTTP methods (``POST``, ``PUT``, ``DELETE``, etc.). For each page (response) that Django sends back from a view, it might provide two HTTP headers: the ``ETag`` header and the ``Last-Modified`` header. These headers are optional on HTTP responses. They can be set by your view function, -or you can rely on the :class:`~django.middleware.http.ConditionalGetMiddleware` -middleware to set the ``ETag`` header. +or you can rely on the +:class:`~django.middleware.http.ConditionalGetMiddleware` middleware to set the +``ETag`` header. When the client next requests the same resource, it might send along a header such as either :rfc:`If-Modified-Since <9110#section-13.1.3>` or diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt index bd90c4b5fe..5383ba5687 100644 --- a/docs/topics/db/aggregation.txt +++ b/docs/topics/db/aggregation.txt @@ -4,12 +4,12 @@ Aggregation .. currentmodule:: django.db.models -The topic guide on :doc:`Django's database-abstraction API </topics/db/queries>` -described the way that you can use Django queries that create, -retrieve, update and delete individual objects. However, sometimes you will -need to retrieve values that are derived by summarizing or *aggregating* a -collection of objects. This topic guide describes the ways that aggregate values -can be generated and returned using Django queries. +The topic guide on :doc:`Django's database-abstraction API +</topics/db/queries>` described the way that you can use Django queries that +create, retrieve, update and delete individual objects. However, sometimes you +will need to retrieve values that are derived by summarizing or *aggregating* a +collection of objects. This topic guide describes the ways that aggregate +values can be generated and returned using Django queries. Throughout this guide, we'll refer to the following models. These models are used to track the inventory for a series of online bookstores: @@ -322,12 +322,14 @@ We can also ask for the oldest book of any of those managed by every publisher: >>> Publisher.objects.aggregate(oldest_pubdate=Min("book__pubdate")) (The resulting dictionary will have a key called ``'oldest_pubdate'``. If no -such alias were specified, it would be the rather long ``'book__pubdate__min'``.) +such alias were specified, it would be the rather long +``'book__pubdate__min'``.) This doesn't apply just to foreign keys. It also works with many-to-many relations. For example, we can ask for every author, annotated with the total -number of pages considering all the books the author has (co-)authored (note how we -use ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop): +number of pages considering all the books the author has (co-)authored (note +how we use ``'book'`` to specify the ``Author`` -> ``Book`` reverse +many-to-many hop): .. code-block:: pycon @@ -345,7 +347,8 @@ file: >>> Author.objects.aggregate(average_rating=Avg("book__rating")) (The resulting dictionary will have a key called ``'average_rating'``. If no -such alias were specified, it would be the rather long ``'book__rating__avg'``.) +such alias were specified, it would be the rather long +``'book__rating__avg'``.) Aggregations and other ``QuerySet`` clauses =========================================== @@ -527,7 +530,8 @@ rating of books written by each author: This will return one result for each author in the database, annotated with their average book rating. -However, the result will be slightly different if you use a ``values()`` clause: +However, the result will be slightly different if you use a ``values()`` +clause: .. code-block:: pycon diff --git a/docs/topics/db/examples/many_to_many.txt b/docs/topics/db/examples/many_to_many.txt index 38838bb1b8..f91489a42f 100644 --- a/docs/topics/db/examples/many_to_many.txt +++ b/docs/topics/db/examples/many_to_many.txt @@ -161,8 +161,8 @@ The :meth:`~django.db.models.query.QuerySet.count` function respects >>> Article.objects.filter(publications__in=[p1, p2]).distinct() <QuerySet [<Article: Django lets you build web apps easily>, <Article: NASA uses Python>]> -Reverse m2m queries are supported (i.e., starting at the table that doesn't have -a :class:`~django.db.models.ManyToManyField`): +Reverse m2m queries are supported (i.e., starting at the table that doesn't +have a :class:`~django.db.models.ManyToManyField`): .. code-block:: pycon diff --git a/docs/topics/db/examples/many_to_one.txt b/docs/topics/db/examples/many_to_one.txt index 7b84a553fb..455a9dd830 100644 --- a/docs/topics/db/examples/many_to_one.txt +++ b/docs/topics/db/examples/many_to_one.txt @@ -2,7 +2,8 @@ Many-to-one relationships ========================= -To define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`. +To define a many-to-one relationship, use +:class:`~django.db.models.ForeignKey`. In this example, a ``Reporter`` can be associated with many ``Article`` objects, but an ``Article`` can only have one ``Reporter`` object:: @@ -229,8 +230,8 @@ Queries can go round in circles: <QuerySet [<Reporter: John Smith>]> If you delete a reporter, their articles will be deleted (assuming that the -ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to -``CASCADE``, which is the default): +ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set +to ``CASCADE``, which is the default): .. code-block:: pycon diff --git a/docs/topics/db/examples/one_to_one.txt b/docs/topics/db/examples/one_to_one.txt index b579e43652..ecb8a93a82 100644 --- a/docs/topics/db/examples/one_to_one.txt +++ b/docs/topics/db/examples/one_to_one.txt @@ -139,7 +139,8 @@ Restaurants: >>> Place.objects.order_by("name") <QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]> -You can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`: +You can query the models using :ref:`lookups across relationships +<lookups-that-span-relationships>`: .. code-block:: pycon diff --git a/docs/topics/db/instrumentation.txt b/docs/topics/db/instrumentation.txt index 8a08bd9a4f..75adb995c1 100644 --- a/docs/topics/db/instrumentation.txt +++ b/docs/topics/db/instrumentation.txt @@ -12,7 +12,8 @@ The wrappers are modeled after :doc:`middleware </topics/http/middleware>` -- they are callables which take another callable as one of their arguments. They call that callable to invoke the (possibly wrapped) database query, and they can do what they want around that call. They are, however, created and -installed by user code, and so don't need a separate factory like middleware do. +installed by user code, and so don't need a separate factory like middleware +do. Installing a wrapper is done in a context manager -- so the wrappers are temporary and specific to some flow in your code. diff --git a/docs/topics/db/managers.txt b/docs/topics/db/managers.txt index 1cd3ba962f..4766ca3870 100644 --- a/docs/topics/db/managers.txt +++ b/docs/topics/db/managers.txt @@ -159,8 +159,9 @@ For example:: authors = AuthorManager() editors = EditorManager() -This example allows you to request ``Person.authors.all()``, ``Person.editors.all()``, -and ``Person.people.all()``, yielding predictable results. +This example allows you to request ``Person.authors.all()``, +``Person.editors.all()``, and ``Person.people.all()``, yielding predictable +results. .. _default-managers: @@ -260,8 +261,8 @@ custom ``QuerySet`` if you also implement them on the ``Manager``:: role = models.CharField(max_length=1, choices={"A": _("Author"), "E": _("Editor")}) people = PersonManager() -This example allows you to call both ``authors()`` and ``editors()`` directly from -the manager ``Person.people``. +This example allows you to call both ``authors()`` and ``editors()`` directly +from the manager ``Person.people``. .. _create-manager-with-queryset-methods: @@ -290,7 +291,8 @@ Methods are copied according to the following rules: - Public methods are copied by default. - Private methods (starting with an underscore) are not copied by default. -- Methods with a ``queryset_only`` attribute set to ``False`` are always copied. +- Methods with a ``queryset_only`` attribute set to ``False`` are always + copied. - Methods with a ``queryset_only`` attribute set to ``True`` are never copied. For example:: @@ -401,10 +403,10 @@ still available, since it's inherited, but isn't used as the default. Finally for this example, suppose you want to add extra managers to the child class, but still use the default from ``AbstractBase``. You can't add the new -manager directly in the child class, as that would override the default and you would -have to also explicitly include all the managers from the abstract base class. -The solution is to put the extra managers in another base class and introduce -it into the inheritance hierarchy *after* the defaults:: +manager directly in the child class, as that would override the default and you +would have to also explicitly include all the managers from the abstract base +class. The solution is to put the extra managers in another base class and +introduce it into the inheritance hierarchy *after* the defaults:: class ExtraManager(models.Model): extra_manager = OtherManager() @@ -431,8 +433,8 @@ is legal, but:: will raise an exception. This is because managers are intended to encapsulate logic for managing collections of objects. Since you can't have a collection of abstract objects, it doesn't make sense to be managing them. If you have -functionality that applies to the abstract model, you should put that functionality -in a ``staticmethod`` or ``classmethod`` on the abstract model. +functionality that applies to the abstract model, you should put that +functionality in a ``staticmethod`` or ``classmethod`` on the abstract model. Implementation concerns ----------------------- diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt index bafc10f44c..89870adb32 100644 --- a/docs/topics/db/models.txt +++ b/docs/topics/db/models.txt @@ -61,8 +61,8 @@ Some technical notes: Using models ============ -Once you have defined your models, you need to tell Django you're going to *use* -those models. Do this by editing your settings file and changing the +Once you have defined your models, you need to tell Django you're going to +*use* those models. Do this by editing your settings file and changing the :setting:`INSTALLED_APPS` setting to add the name of the module that contains your ``models.py``. @@ -117,15 +117,15 @@ determine a few things: * The column type, which tells the database what kind of data to store (e.g. ``INTEGER``, ``VARCHAR``, ``TEXT``). -* The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form - field (e.g. ``<input type="text">``, ``<select>``). +* The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a + form field (e.g. ``<input type="text">``, ``<select>``). * The minimal validation requirements, used in Django's admin and in automatically-generated forms. -Django ships with dozens of built-in field types; you can find the complete list -in the :ref:`model field reference <model-field-types>`. You can easily write -your own fields if Django's built-in ones don't do the trick; see +Django ships with dozens of built-in field types; you can find the complete +list in the :ref:`model field reference <model-field-types>`. You can easily +write your own fields if Django's built-in ones don't do the trick; see :doc:`/howto/custom-model-fields`. Field options @@ -134,13 +134,13 @@ Field options Each field takes a certain set of field-specific arguments (documented in the :ref:`model field reference <model-field-types>`). For example, :class:`~django.db.models.CharField` (and its subclasses) require a -:attr:`~django.db.models.CharField.max_length` argument which specifies the size -of the ``VARCHAR`` database field used to store the data. +:attr:`~django.db.models.CharField.max_length` argument which specifies the +size of the ``VARCHAR`` database field used to store the data. There's also a set of common arguments available to all field types. All are optional. They're fully explained in the :ref:`reference -<common-model-field-options>`, but here's a quick summary of the most often-used -ones: +<common-model-field-options>`, but here's a quick summary of the most +often-used ones: :attr:`~Field.null` If ``True``, Django will store empty values as ``NULL`` in the database. @@ -284,10 +284,9 @@ type specified per app in :attr:`AppConfig.default_auto_field id = models.BigAutoField(primary_key=True) -If you'd like to specify a custom primary key, specify -:attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django -sees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic -``id`` column. +If you'd like to specify a custom primary key, specify :attr:`primary_key=True +<Field.primary_key>` on one of your fields. If Django sees you've explicitly +set :attr:`Field.primary_key`, it won't add the automatic ``id`` column. Each model requires exactly one field to have :attr:`primary_key=True <Field.primary_key>` (either explicitly declared or automatically added). @@ -301,8 +300,8 @@ Each field type, except for :class:`~django.db.models.ForeignKey`, :class:`~django.db.models.ManyToManyField` and :class:`~django.db.models.OneToOneField`, takes an optional first positional argument -- a verbose name. If the verbose name isn't given, Django will -automatically create it using the field's attribute name, converting underscores -to spaces. +automatically create it using the field's attribute name, converting +underscores to spaces. In this example, the verbose name is ``"person's first name"``:: @@ -366,9 +365,9 @@ For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) # ... -You can also create :ref:`recursive relationships <recursive-relationships>` (an -object with a many-to-one relationship to itself) and :ref:`relationships to -models not yet defined <lazy-relationships>`; see :ref:`the model field +You can also create :ref:`recursive relationships <recursive-relationships>` +(an object with a many-to-one relationship to itself) and :ref:`relationships +to models not yet defined <lazy-relationships>`; see :ref:`the model field reference <ref-foreignkey>` for details. It's suggested, but not required, that the name of a @@ -390,8 +389,8 @@ want. For example:: <foreign-key-arguments>`. These options help define how the relationship should work; all are optional. - For details on accessing backwards-related objects, see the - :ref:`Following relationships backward example <backwards-related-objects>`. + For details on accessing backwards-related objects, see the :ref:`Following + relationships backward example <backwards-related-objects>`. For sample code, see the :doc:`Many-to-one relationship model example </topics/db/examples/many_to_one>`. @@ -465,8 +464,8 @@ matching pizzas and toppings, a standard you may need to associate data with the relationship between two models. For example, consider the case of an application tracking the musical groups -which musicians belong to. There is a many-to-many relationship between a person -and the groups of which they are a member, so you could use a +which musicians belong to. There is a many-to-many relationship between a +person and the groups of which they are a member, so you could use a :class:`~django.db.models.ManyToManyField` to represent this relationship. However, there is a lot of detail about the membership that you might want to collect, such as the date at which the person joined the group. @@ -524,11 +523,11 @@ There are a few restrictions on the intermediate model: * Your intermediate model must contain one - and *only* one - foreign key to the source model (this would be ``Group`` in our example), or you must explicitly specify the foreign keys Django should use for the relationship - using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`. - If you have more than one foreign key and ``through_fields`` is not - specified, a validation error will be raised. A similar restriction applies - to the foreign key to the target model (this would be ``Person`` in our - example). + using :attr:`ManyToManyField.through_fields + <ManyToManyField.through_fields>`. If you have more than one foreign key and + ``through_fields`` is not specified, a validation error will be raised. A + similar restriction applies to the foreign key to the target model (this + would be ``Person`` in our example). * For a model which has a many-to-many relationship to itself through an intermediary model, two foreign keys to the same model are permitted, but @@ -800,13 +799,13 @@ Give your model metadata by using an inner ``class Meta``, like so:: verbose_name_plural = "oxen" Model metadata is "anything that's not a field", such as ordering options -(:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or -human-readable singular and plural names (:attr:`~Options.verbose_name` and +(:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), +or human-readable singular and plural names (:attr:`~Options.verbose_name` and :attr:`~Options.verbose_name_plural`). None are required, and adding ``class Meta`` to a model is completely optional. -A complete list of all possible ``Meta`` options can be found in the :doc:`model -option reference </ref/models/options>`. +A complete list of all possible ``Meta`` options can be found in the +:doc:`model option reference </ref/models/options>`. .. _model-attributes: @@ -827,9 +826,10 @@ Model attributes Model methods ============= -Define custom methods on a model to add custom "row-level" functionality to your -objects. Whereas :class:`~django.db.models.Manager` methods are intended to do -"table-wide" things, model methods should act on a particular model instance. +Define custom methods on a model to add custom "row-level" functionality to +your objects. Whereas :class:`~django.db.models.Manager` methods are intended +to do "table-wide" things, model methods should act on a particular model +instance. This is a valuable technique for keeping business logic in one place -- the model. @@ -1059,11 +1059,12 @@ still only creating one database table per child model at the database level. ``Meta`` inheritance ~~~~~~~~~~~~~~~~~~~~ -When an abstract base class is created, Django makes any :ref:`Meta <meta-options>` -inner class you declared in the base class available as an -attribute. If a child class does not declare its own :ref:`Meta <meta-options>` -class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to -extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example:: +When an abstract base class is created, Django makes any +:ref:`Meta <meta-options>` inner class you declared in the base class available +as an attribute. If a child class does not declare its own +:ref:`Meta <meta-options>` class, it will inherit the parent's +:ref:`Meta <meta-options>`. If the child wants to extend the parent's +:ref:`Meta <meta-options>` class, it can subclass it. For example:: from django.db import models @@ -1087,10 +1088,11 @@ base classes don't automatically become abstract classes themselves. To make an abstract base class that inherits from another abstract base class, you need to explicitly set ``abstract=True`` on the child. -Some attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an -abstract base class. For example, including ``db_table`` would mean that all -the child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use -the same database table, which is almost certainly not what you want. +Some attributes won't make sense to include in the :ref:`Meta <meta-options>` +class of an abstract base class. For example, including ``db_table`` would mean +that all the child classes (the ones that don't specify their own +:ref:`Meta <meta-options>`) would use the same database table, which is almost +certainly not what you want. Due to the way Python inheritance works, if a child class inherits from multiple abstract base classes, only the :ref:`Meta <meta-options>` options @@ -1181,15 +1183,15 @@ Along with another app ``rare/models.py``:: pass The reverse name of the ``common.ChildA.m2m`` field will be -``common_childa_related`` and the reverse query name will be ``common_childas``. -The reverse name of the ``common.ChildB.m2m`` field will be +``common_childa_related`` and the reverse query name will be +``common_childas``. The reverse name of the ``common.ChildB.m2m`` field will be ``common_childb_related`` and the reverse query name will be ``common_childbs``. Finally, the reverse name of the ``rare.ChildB.m2m`` field will be ``rare_childb_related`` and the reverse query name will be ``rare_childbs``. It's up to you how you use the ``'%(class)s'`` and -``'%(app_label)s'`` portion to construct your related name or related query name -but if you forget to use it, Django will raise errors when you perform system -checks (or run :djadmin:`migrate`). +``'%(app_label)s'`` portion to construct your related name or related query +name but if you forget to use it, Django will raise errors when you perform +system checks (or run :djadmin:`migrate`). If you don't specify a :attr:`~django.db.models.ForeignKey.related_name` attribute for a field in an abstract base class, the default reverse name will @@ -1269,11 +1271,11 @@ You can override that field by declaring your own ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the multi-table inheritance situation, it doesn't make sense for a child -class to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options -have already been applied to the parent class and applying them again would -normally only lead to contradictory behavior (this is in contrast with the -abstract base class case, where the base class doesn't exist in its own -right). +class to inherit from its parent's :ref:`Meta <meta-options>` class. All the +:ref:`Meta <meta-options>` options have already been applied to the parent +class and applying them again would normally only lead to contradictory +behavior (this is in contrast with the abstract base class case, where the base +class doesn't exist in its own right). So a child model does not have access to its parent's :ref:`Meta <meta-options>` class. However, there are a few limited cases where the child @@ -1359,7 +1361,8 @@ Proxy models are declared like normal models. You tell Django that it's a proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of the ``Meta`` class to ``True``. -For example, suppose you want to add a method to the ``Person`` model. You can do it like this:: +For example, suppose you want to add a method to the ``Person`` model. You can +do it like this:: from django.db import models diff --git a/docs/topics/db/multi-db.txt b/docs/topics/db/multi-db.txt index 11be913f4c..38f91c2800 100644 --- a/docs/topics/db/multi-db.txt +++ b/docs/topics/db/multi-db.txt @@ -587,7 +587,8 @@ solution is to use ``db_manager()``, like this:: User.objects.db_manager("new_users").create_user(...) -``db_manager()`` returns a copy of the manager bound to the database you specify. +``db_manager()`` returns a copy of the manager bound to the database you +specify. Using ``get_queryset()`` with multiple databases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/topics/db/optimization.txt b/docs/topics/db/optimization.txt index c40456d3f2..bb70efa362 100644 --- a/docs/topics/db/optimization.txt +++ b/docs/topics/db/optimization.txt @@ -21,8 +21,8 @@ your requirements. Sometimes optimizing for one will be detrimental to the other, but sometimes they will help each other. Also, work that is done by the database process might not have the same cost (to you) as the same amount of work done in your Python process. It is up to you to decide what your -priorities are, where the balance must lie, and profile all of these as required -since this will depend on your application and server. +priorities are, where the balance must lie, and profile all of these as +required since this will depend on your application and server. With everything that follows, remember to profile after every change to ensure that the change is a benefit, and a big enough benefit given the decrease in @@ -202,8 +202,8 @@ Retrieve everything at once if you know you will need it Hitting the database multiple times for different parts of a single 'set' of data that you will need all parts of is, in general, less efficient than retrieving it all in one query. This is particularly important if you have a -query that is executed in a loop, and could therefore end up doing many database -queries, when only one was needed. So: +query that is executed in a loop, and could therefore end up doing many +database queries, when only one was needed. So: Use ``QuerySet.select_related()`` and ``prefetch_related()`` ------------------------------------------------------------ @@ -332,9 +332,9 @@ anything driven from the normal database object :doc:`signals </ref/signals>`. Use foreign key values directly ------------------------------- -If you only need a foreign key value, use the foreign key value that is already on -the object you've got, rather than getting the whole related object and taking -its primary key. i.e. do:: +If you only need a foreign key value, use the foreign key value that is already +on the object you've got, rather than getting the whole related object and +taking its primary key. i.e. do:: entry.blog_id diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt index 519d152589..a2e6172f7a 100644 --- a/docs/topics/db/queries.txt +++ b/docs/topics/db/queries.txt @@ -518,8 +518,8 @@ probably use: case-insensitive versions called :lookup:`istartswith` and :lookup:`iendswith`. -Again, this only scratches the surface. A complete reference can be found in the -:ref:`field lookup reference <field-lookups>`. +Again, this only scratches the surface. A complete reference can be found in +the :ref:`field lookup reference <field-lookups>`. .. _lookups-that-span-relationships: @@ -706,10 +706,10 @@ and use that ``F()`` object in the query: >>> from django.db.models import F >>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks")) -Django supports the use of addition, subtraction, multiplication, -division, modulo, and power arithmetic with ``F()`` objects, both with constants -and with other ``F()`` objects. To find all the blog entries with more than -*twice* as many comments as pingbacks, we modify the query: +Django supports the use of addition, subtraction, multiplication, division, +modulo, and power arithmetic with ``F()`` objects, both with constants and with +other ``F()`` objects. To find all the blog entries with more than *twice* as +many comments as pingbacks, we modify the query: .. code-block:: pycon @@ -1370,7 +1370,8 @@ Complex lookups with ``Q`` objects Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`, etc. -- are "AND"ed together. If you need to execute more complex queries (for -example, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`. +example, queries with ``OR`` statements), you can use +:class:`Q objects <django.db.models.Q>`. A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object used to encapsulate a collection of keyword arguments. These keyword arguments @@ -1688,9 +1689,9 @@ When you define a relationship in a model (i.e., a :class:`~django.db.models.ManyToManyField`), instances of that model will have a convenient API to access the related object(s). -Using the models at the top of this page, for example, an ``Entry`` object ``e`` -can get its associated ``Blog`` object by accessing the ``blog`` attribute: -``e.blog``. +Using the models at the top of this page, for example, an ``Entry`` object +``e`` can get its associated ``Blog`` object by accessing the ``blog`` +attribute: ``e.blog``. (Behind the scenes, this functionality is implemented by Python :doc:`descriptors <python:howto/descriptor>`. This shouldn't really matter to @@ -1805,9 +1806,9 @@ Using a custom reverse manager ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default the :class:`~django.db.models.fields.related.RelatedManager` used -for reverse relations is a subclass of the :ref:`default manager <manager-names>` -for that model. If you would like to specify a different manager for a given -query you can use the following syntax:: +for reverse relations is a subclass of the :ref:`default manager +<manager-names>` for that model. If you would like to specify a different +manager for a given query you can use the following syntax:: from django.db import models @@ -1941,9 +1942,9 @@ For example:: ed.entry # Returns the related Entry object. The difference comes in "reverse" queries. The related model in a one-to-one -relationship also has access to a :class:`~django.db.models.Manager` object, but -that :class:`~django.db.models.Manager` represents a single object, rather than -a collection of objects:: +relationship also has access to a :class:`~django.db.models.Manager` object, +but that :class:`~django.db.models.Manager` represents a single object, rather +than a collection of objects:: e = Entry.objects.get(id=2) e.entrydetail # returns the related EntryDetail object diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt index 4504eb6fce..6aafa2c3b5 100644 --- a/docs/topics/db/sql.txt +++ b/docs/topics/db/sql.txt @@ -49,7 +49,8 @@ This method takes a raw SQL query, executes it, and returns a can be iterated over like a normal :class:`~django.db.models.query.QuerySet` to provide object instances. -This is best illustrated with an example. Suppose you have the following model:: +This is best illustrated with an example. Suppose you have the following +model:: class Person(models.Model): first_name = models.CharField(...) @@ -93,13 +94,13 @@ make it very powerful. .. warning:: - If you are performing queries on MySQL, note that MySQL's silent type coercion - may cause unexpected results when mixing types. If you query on a string - type column, but with an integer value, MySQL will coerce the types of all values - in the table to an integer before performing the comparison. For example, if your - table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``, - both rows will match. To prevent this, perform the correct typecasting - before using the value in a query. + If you are performing queries on MySQL, note that MySQL's silent type + coercion may cause unexpected results when mixing types. If you query on a + string type column, but with an integer value, MySQL will coerce the types + of all values in the table to an integer before performing the comparison. + For example, if your table contains the values ``'abc'``, ``'def'`` and you + query for ``WHERE mycolumn=0``, both rows will match. To prevent this, + perform the correct typecasting before using the value in a query. Mapping query fields to model fields ------------------------------------ @@ -302,8 +303,8 @@ For example:: To protect against SQL injection, you must not include quotes around the ``%s`` placeholders in the SQL string. -Note that if you want to include literal percent signs in the query, you have to -double them in the case you are passing parameters:: +Note that if you want to include literal percent signs in the query, you have +to double them in the case you are passing parameters:: cursor.execute("SELECT foo FROM bar WHERE baz = '30%'") cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id]) diff --git a/docs/topics/db/tablespaces.txt b/docs/topics/db/tablespaces.txt index 480d3a10c8..1be57702a3 100644 --- a/docs/topics/db/tablespaces.txt +++ b/docs/topics/db/tablespaces.txt @@ -21,10 +21,10 @@ the :attr:`~django.db.models.Options.db_tablespace` option inside the model's ``class Meta``. This option also affects tables automatically created for :class:`~django.db.models.ManyToManyField`\ s in the model. -You can use the :setting:`DEFAULT_TABLESPACE` setting to specify a default value -for :attr:`~django.db.models.Options.db_tablespace`. This is useful for setting -a tablespace for the built-in Django apps and other applications whose code you -cannot control. +You can use the :setting:`DEFAULT_TABLESPACE` setting to specify a default +value for :attr:`~django.db.models.Options.db_tablespace`. This is useful for +setting a tablespace for the built-in Django apps and other applications whose +code you cannot control. Declaring tablespaces for indexes ================================= diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 2f6fbde168..3ffd7c37b5 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -45,10 +45,10 @@ either all or none of the changes will be committed. .. warning:: - While the simplicity of this transaction model is appealing, it also makes it - inefficient when traffic increases. Opening a transaction for every view has - some overhead. The impact on performance depends on the query patterns of your - application and on how well your database handles locking. + While the simplicity of this transaction model is appealing, it also makes + it inefficient when traffic increases. Opening a transaction for every view + has some overhead. The impact on performance depends on the query patterns + of your application and on how well your database handles locking. .. admonition:: Per-request transactions and streaming responses diff --git a/docs/topics/email.txt b/docs/topics/email.txt index 945d5d8794..bcb8737f4c 100644 --- a/docs/topics/email.txt +++ b/docs/topics/email.txt @@ -108,8 +108,8 @@ if used. If unspecified, an instance of the default backend will be used. See the documentation on :ref:`Email backends <topic-email-backends>` for more details. -* ``html_message``: If ``html_message`` is provided, the resulting email will be a - :mimetype:`multipart/alternative` email with ``message`` as the +* ``html_message``: If ``html_message`` is provided, the resulting email will + be a :mimetype:`multipart/alternative` email with ``message`` as the :mimetype:`text/plain` content type and ``html_message`` as the :mimetype:`text/html` content type. @@ -535,8 +535,8 @@ Django's email library, you can do this using the .. attribute:: alternatives - A list of :class:`~django.core.mail.EmailAlternative` named tuples. This - is particularly useful in tests:: + A list of :class:`~django.core.mail.EmailAlternative` named tuples. + This is particularly useful in tests:: self.assertEqual(len(msg.alternatives), 1) self.assertEqual(msg.alternatives[0].content, html_content) diff --git a/docs/topics/files.txt b/docs/topics/files.txt index bee04e1d75..e220dfac5f 100644 --- a/docs/topics/files.txt +++ b/docs/topics/files.txt @@ -8,8 +8,8 @@ them for other purposes. If you want to handle "static files" (JS, CSS, etc.), see :doc:`/howto/static-files/index`. By default, Django stores files locally, using the :setting:`MEDIA_ROOT` and -:setting:`MEDIA_URL` settings. The examples below assume that you're using these -defaults. +:setting:`MEDIA_URL` settings. The examples below assume that you're using +these defaults. However, Django provides ways to write custom `file storage systems`_ that allow you to completely customize where and how Django stores files. The @@ -21,8 +21,8 @@ Using files in models ===================== When you use a :class:`~django.db.models.FileField` or -:class:`~django.db.models.ImageField`, Django provides a set of APIs you can use -to deal with that file. +:class:`~django.db.models.ImageField`, Django provides a set of APIs you can +use to deal with that file. Consider the following model, using an :class:`~django.db.models.ImageField` to store a photo:: @@ -51,13 +51,13 @@ the details of the attached photo: >>> car.photo.url 'https://media.example.com/cars/chevy.jpg' -This object -- ``car.photo`` in the example -- is a ``File`` object, which means -it has all the methods and attributes described below. +This object -- ``car.photo`` in the example -- is a ``File`` object, which +means it has all the methods and attributes described below. .. note:: - The file is saved as part of saving the model in the database, so the actual - file name used on disk cannot be relied on until after the model has been - saved. + The file is saved as part of saving the model in the database, so the + actual file name used on disk cannot be relied on until after the model has + been saved. For example, you can change the file name by setting the file's :attr:`~django.core.files.File.name` to a path relative to the file storage's @@ -168,9 +168,9 @@ may lead to the following error: File storage ============ -Behind the scenes, Django delegates decisions about how and where to store files -to a file storage system. This is the object that actually understands things -like file systems, opening and reading files, etc. +Behind the scenes, Django delegates decisions about how and where to store +files to a file storage system. This is the object that actually understands +things like file systems, opening and reading files, etc. Django's default file storage is ``'``:class:`django.core.files.storage.FileSystemStorage`\ ``'``. If you don't @@ -184,10 +184,10 @@ storage system. Storage objects --------------- -Though most of the time you'll want to use a ``File`` object (which delegates to -the proper storage for that file), you can use file storage systems directly. -You can create an instance of some custom file storage class, or -- often more -useful -- you can use the global default storage system: +Though most of the time you'll want to use a ``File`` object (which delegates +to the proper storage for that file), you can use file storage systems +directly. You can create an instance of some custom file storage class, or -- +often more useful -- you can use the global default storage system: .. code-block:: pycon diff --git a/docs/topics/forms/formsets.txt b/docs/topics/forms/formsets.txt index 585a42469f..d4441ce138 100644 --- a/docs/topics/forms/formsets.txt +++ b/docs/topics/forms/formsets.txt @@ -274,12 +274,13 @@ provide this management data, the formset will be invalid: >>> formset.is_valid() False -It is used to keep track of how many form instances are being displayed. If -you are adding new forms via JavaScript, you should increment the count fields -in this form as well. On the other hand, if you are using JavaScript to allow +It is used to keep track of how many form instances are being displayed. If you +are adding new forms via JavaScript, you should increment the count fields in +this form as well. On the other hand, if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including ``form-#-DELETE`` in the ``POST`` -data. It is expected that all forms are present in the ``POST`` data regardless. +data. It is expected that all forms are present in the ``POST`` data +regardless. The management form is available as an attribute of the formset itself. When rendering a formset in a template, you can include all diff --git a/docs/topics/forms/index.txt b/docs/topics/forms/index.txt index b54231d48e..13f2870106 100644 --- a/docs/topics/forms/index.txt +++ b/docs/topics/forms/index.txt @@ -192,9 +192,9 @@ the user's name. You'd need something like this in your template: <input type="submit" value="OK"> </form> -This tells the browser to return the form data to the URL ``/your-name/``, using -the ``POST`` method. It will display a text field, labeled "Your name:", and a -button marked "OK". If the template context contains a ``current_name`` +This tells the browser to return the form data to the URL ``/your-name/``, +using the ``POST`` method. It will display a text field, labeled "Your name:", +and a button marked "OK". If the template context contains a ``current_name`` variable, that will be used to pre-fill the ``your_name`` field. You'll need a view that renders the template containing the HTML form, and @@ -203,8 +203,9 @@ that can supply the ``current_name`` field as appropriate. When the form is submitted, the ``POST`` request which is sent to the server will contain the form data. -Now you'll also need a view corresponding to that ``/your-name/`` URL which will -find the appropriate key/value pairs in the request, and then process them. +Now you'll also need a view corresponding to that ``/your-name/`` URL which +will find the appropriate key/value pairs in the request, and then process +them. This is a very simple form. In practice, a form might contain dozens or hundreds of fields, many of which might need to be prepopulated, and we might @@ -343,12 +344,12 @@ from that ``{{ form }}`` by Django's template language. .. admonition:: Forms and Cross Site Request Forgery protection - Django ships with an easy-to-use :doc:`protection against Cross Site Request - Forgeries </ref/csrf>`. When submitting a form via ``POST`` with - CSRF protection enabled you must use the :ttag:`csrf_token` template tag - as in the preceding example. However, since CSRF protection is not - directly tied to forms in templates, this tag is omitted from the - following examples in this document. + Django ships with an easy-to-use :doc:`protection against Cross Site + Request Forgeries </ref/csrf>`. When submitting a form via ``POST`` with + CSRF protection enabled you must use the :ttag:`csrf_token` template tag as + in the preceding example. However, since CSRF protection is not directly + tied to forms in templates, this tag is omitted from the following examples + in this document. .. admonition:: HTML5 input types and browser validation @@ -381,8 +382,8 @@ detail is rarely important. In fact if your form is going to be used to directly add or edit a Django model, a :doc:`ModelForm </topics/forms/modelforms>` can save you a great - deal of time, effort, and code, because it will build a form, along with the - appropriate fields and their attributes, from a ``Model`` class. + deal of time, effort, and code, because it will build a form, along with + the appropriate fields and their attributes, from a ``Model`` class. Bound and unbound form instances -------------------------------- diff --git a/docs/topics/forms/media.txt b/docs/topics/forms/media.txt index 96408fb4e7..25de33f65f 100644 --- a/docs/topics/forms/media.txt +++ b/docs/topics/forms/media.txt @@ -117,7 +117,8 @@ requirements:: "print": ["newspaper.css"], } -If this last CSS definition were to be rendered, it would become the following HTML: +If this last CSS definition were to be rendered, it would become the following +HTML: .. code-block:: html+django diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index a5deeb324a..611dc83439 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -311,7 +311,8 @@ the form level. You can override the error messages from ``NON_FIELD_ERRORS`` raised by model validation by adding the :data:`~django.core.exceptions.NON_FIELD_ERRORS` key -to the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class:: +to the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` +class:: from django.core.exceptions import NON_FIELD_ERRORS from django.forms import ModelForm @@ -440,9 +441,10 @@ fields, especially when new fields are added to a model. Depending on how the form is rendered, the problem may not even be visible on the web page. The alternative approach would be to include all fields automatically, or -remove only some. This fundamental approach is known to be much less secure -and has led to serious exploits on major websites (e.g. `GitHub -<https://github.blog/2012-03-04-public-key-security-vulnerability-and-mitigation/>`_). +remove only some. This fundamental approach is known to be much less secure and +has led to serious exploits on major websites (e.g. `GitHub +<https://github.blog/2012-03-04-public-key-security-vulnerability-and-mitigation/>`__ +). There are, however, two shortcuts available for cases where you can guarantee these security concerns do not apply to you: @@ -472,13 +474,13 @@ these security concerns do not apply to you: ``birth_date``, this will result in the fields ``name`` and ``birth_date`` being present on the form. -If either of these are used, the order the fields appear in the form will be the -order the fields are defined in the model, with ``ManyToManyField`` instances -appearing last. +If either of these are used, the order the fields appear in the form will be +the order the fields are defined in the model, with ``ManyToManyField`` +instances appearing last. -In addition, Django applies the following rule: if you set ``editable=False`` on -the model field, *any* form created from the model via ``ModelForm`` will not -include that field. +In addition, Django applies the following rule: if you set ``editable=False`` +on the model field, *any* form created from the model via ``ModelForm`` will +not include that field. .. note:: @@ -546,11 +548,12 @@ The ``widgets`` dictionary accepts either widget instances (e.g., dictionary is ignored for a model field with a non-empty ``choices`` attribute. In this case, you must override the form field to use a different widget. -Similarly, you can specify the ``labels``, ``help_texts`` and ``error_messages`` -attributes of the inner ``Meta`` class if you want to further customize a field. +Similarly, you can specify the ``labels``, ``help_texts`` and +``error_messages`` attributes of the inner ``Meta`` class if you want to +further customize a field. -For example if you wanted to customize the wording of all user facing strings for -the ``name`` field:: +For example if you wanted to customize the wording of all user facing strings +for the ``name`` field:: from django.utils.translation import gettext_lazy as _ @@ -633,14 +636,14 @@ the field declaratively and setting its ``validators`` parameter:: ``ModelForm`` is a regular ``Form`` which can automatically generate certain fields. The fields that are automatically generated depend on the content of the ``Meta`` class and on which fields have already been - defined declaratively. Basically, ``ModelForm`` will **only** generate fields - that are **missing** from the form, or in other words, fields that weren't - defined declaratively. + defined declaratively. Basically, ``ModelForm`` will **only** generate + fields that are **missing** from the form, or in other words, fields that + weren't defined declaratively. Fields defined declaratively are left as-is, therefore any customizations - made to ``Meta`` attributes such as ``widgets``, ``labels``, ``help_texts``, - or ``error_messages`` are ignored; these only apply to fields that are - generated automatically. + made to ``Meta`` attributes such as ``widgets``, ``labels``, + ``help_texts``, or ``error_messages`` are ignored; these only apply to + fields that are generated automatically. Similarly, fields defined declaratively do not draw their attributes like ``max_length`` or ``required`` from the corresponding model. If you want to @@ -677,8 +680,8 @@ the field declaratively and setting its ``validators`` parameter:: contents of the corresponding model field. When they are not compatible, you will get a ``ValueError`` as no implicit conversion takes place. - See the :doc:`form field documentation </ref/forms/fields>` for more information - on fields and their arguments. + See the :doc:`form field documentation </ref/forms/fields>` for more + information on fields and their arguments. Enabling localization of fields ------------------------------- @@ -739,12 +742,12 @@ There are a couple of things to note, however. because these classes rely on different metaclasses and a class can only have one metaclass. -* It's possible to declaratively remove a ``Field`` inherited from a parent class by - setting the name to be ``None`` on the subclass. +* It's possible to declaratively remove a ``Field`` inherited from a parent + class by setting the name to be ``None`` on the subclass. You can only use this technique to opt out from a field defined declaratively - by a parent class; it won't prevent the ``ModelForm`` metaclass from generating - a default field. To opt-out from default fields, see + by a parent class; it won't prevent the ``ModelForm`` metaclass from + generating a default field. To opt-out from default fields, see :ref:`modelforms-selecting-fields`. Providing initial values @@ -1279,7 +1282,8 @@ a particular author, you could do this: .. seealso:: - :ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`. + :ref:`Manually rendered can_delete and can_order + <manually-rendered-can-delete-and-can-order>`. Overriding methods on an ``InlineFormSet`` ------------------------------------------ diff --git a/docs/topics/http/decorators.txt b/docs/topics/http/decorators.txt index 1c48e667f1..360e243907 100644 --- a/docs/topics/http/decorators.txt +++ b/docs/topics/http/decorators.txt @@ -102,8 +102,8 @@ caching based on specific request headers. .. function:: vary_on_headers(*headers) - The ``Vary`` header defines which request headers a cache mechanism should take - into account when building its cache key. + The ``Vary`` header defines which request headers a cache mechanism should + take into account when building its cache key. See :ref:`using vary headers <using-vary-headers>`. diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt index 9896a6032b..f9327808b5 100644 --- a/docs/topics/http/file-uploads.txt +++ b/docs/topics/http/file-uploads.txt @@ -67,8 +67,9 @@ described in :ref:`binding-uploaded-files`. This would look something like: form = UploadFileForm() return render(request, "upload.html", {"form": form}) -Notice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>` -into the form's constructor; this is how file data gets bound into a form. +Notice that we have to pass :attr:`request.FILES +<django.http.HttpRequest.FILES>` into the form's constructor; this is how file +data gets bound into a form. Here's a common way you might handle an uploaded file:: @@ -259,8 +260,8 @@ involves only a read from memory and a write to disk and thus is very fast. However, if an uploaded file is too large, Django will write the uploaded file to a temporary file stored in your system's temporary directory. On a Unix-like platform this means you can expect Django to generate a file called something -like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this -file grow in size as Django streams the data onto disk. +like ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch +this file grow in size as Django streams the data onto disk. These specifics -- 2.5 megabytes; ``/tmp``; etc. -- are "reasonable defaults" which can be customized as described in the next section. @@ -283,8 +284,8 @@ handlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list as you would any other list. For instance, suppose you've written a ``ProgressBarUploadHandler`` that -provides feedback on upload progress to some sort of AJAX widget. You'd add this -handler to your upload handlers like this:: +provides feedback on upload progress to some sort of AJAX widget. You'd add +this handler to your upload handlers like this:: request.upload_handlers.insert(0, ProgressBarUploadHandler(request)) diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt index 4ec196a2ec..6fb329dd9a 100644 --- a/docs/topics/http/sessions.txt +++ b/docs/topics/http/sessions.txt @@ -131,10 +131,10 @@ and the :setting:`SECRET_KEY` setting. When using the cookies backend the session data can be read by the client. A MAC (Message Authentication Code) is used to protect the data against - changes by the client, so that the session data will be invalidated when being - tampered with. The same invalidation happens if the client storing the - cookie (e.g. your user's browser) can't store all of the session cookie and - drops data. Even though Django compresses the data, it's still entirely + changes by the client, so that the session data will be invalidated when + being tampered with. The same invalidation happens if the client storing + the cookie (e.g. your user's browser) can't store all of the session cookie + and drops data. Even though Django compresses the data, it's still entirely possible to exceed the :rfc:`common limit of 4096 bytes <2965#section-5.3>` per cookie. @@ -578,8 +578,8 @@ calls ``save()`` and loops until an unused ``session_key`` is generated. If you're using the ``django.contrib.sessions.backends.db`` backend, each session is a normal Django model. The ``Session`` model is defined in -:source:`django/contrib/sessions/models.py`. Because it's a normal model, you can -access sessions using the normal Django database API: +:source:`django/contrib/sessions/models.py`. Because it's a normal model, you +can access sessions using the normal Django database API: .. code-block:: pycon @@ -728,11 +728,12 @@ domain. This makes session fixation possible if cookies are permitted from subdomains not controlled by trusted users. For example, an attacker could log into ``good.example.com`` and get a valid -session for their account. If the attacker has control over ``bad.example.com``, -they can use it to send their session key to you since a subdomain is permitted -to set cookies on ``*.example.com``. When you visit ``good.example.com``, -you'll be logged in as the attacker and might inadvertently enter your -sensitive personal data (e.g. credit card info) into the attacker's account. +session for their account. If the attacker has control over +``bad.example.com``, they can use it to send their session key to you since a +subdomain is permitted to set cookies on ``*.example.com``. When you visit +``good.example.com``, you'll be logged in as the attacker and might +inadvertently enter your sensitive personal data (e.g. credit card info) into +the attacker's account. Another possible attack would be if ``good.example.com`` sets its :setting:`SESSION_COOKIE_DOMAIN` to ``"example.com"`` which would cause @@ -839,7 +840,8 @@ You can also customize the model manager by subclassing .. method:: encode(session_dict) - Returns the given session dictionary serialized and encoded as a string. + Returns the given session dictionary serialized and encoded as a + string. Encoding is performed by the session store class tied to a model class. diff --git a/docs/topics/http/urls.txt b/docs/topics/http/urls.txt index 752522818b..0ec48623b7 100644 --- a/docs/topics/http/urls.txt +++ b/docs/topics/http/urls.txt @@ -34,8 +34,8 @@ How Django processes a request When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute: -#. Django determines the root URLconf module to use. Ordinarily, - this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming +#. Django determines the root URLconf module to use. Ordinarily, this is the + value of the :setting:`ROOT_URLCONF` setting, but if the incoming ``HttpRequest`` object has a :attr:`~django.http.HttpRequest.urlconf` attribute (set by middleware), its value will be used in place of the :setting:`ROOT_URLCONF` setting. @@ -86,8 +86,8 @@ Notes: * To capture a value from the URL, use angle brackets. * Captured values can optionally include a converter type. For example, use - ``<int:name>`` to capture an integer parameter. If a converter isn't included, - any string, excluding a ``/`` character, is matched. + ``<int:name>`` to capture an integer parameter. If a converter isn't + included, any string, excluding a ``/`` character, is matched. * There's no need to add a leading slash, because every URL has that. For example, it's ``articles``, not ``/articles``. @@ -107,8 +107,8 @@ Example requests: * ``/articles/2003`` would not match any of these patterns, because each pattern requires that the URL end with a slash. -* ``/articles/2003/03/building-a-django-site/`` would match the final - pattern. Django would call the function +* ``/articles/2003/03/building-a-django-site/`` would match the final pattern. + Django would call the function ``views.article_detail(request, year=2003, month=3, slug="building-a-django-site")``. Path converters @@ -116,8 +116,8 @@ Path converters The following path converters are available by default: -* ``str`` - Matches any non-empty string, excluding the path separator, ``'/'``. - This is the default if a converter isn't included in the expression. +* ``str`` - Matches any non-empty string, excluding the path separator, + ``'/'``. This is the default if a converter isn't included in the expression. * ``int`` - Matches zero or any positive integer. Returns an ``int``. @@ -139,7 +139,8 @@ The following path converters are available by default: Registering custom path converters ================================== -For more complex matching requirements, you can define your own path converters. +For more complex matching requirements, you can define your own path +converters. A converter is a class that includes the following: @@ -260,9 +261,9 @@ positional arguments: ``page-2/`` and ``2``. The second pattern for ``page_number`` set to 2. The outer argument in this case is a non-capturing argument ``(?:...)``. -The ``blog_articles`` view needs the outermost captured argument to be reversed, -``page-2/`` or no arguments in this case, while ``comments`` can be reversed -with either no arguments or a value for ``page_number``. +The ``blog_articles`` view needs the outermost captured argument to be +reversed, ``page-2/`` or no arguments in this case, while ``comments`` can be +reversed with either no arguments or a value for ``page_number``. Nested captured arguments create a strong coupling between the view arguments and the URL as illustrated by ``blog_articles``: the view receives part of the @@ -283,8 +284,8 @@ does not include GET or POST parameters, or the domain name. For example, in a request to ``https://www.example.com/myapp/``, the URLconf will look for ``myapp/``. -In a request to ``https://www.example.com/myapp/?page=3``, the URLconf will look -for ``myapp/``. +In a request to ``https://www.example.com/myapp/?page=3``, the URLconf will +look for ``myapp/``. The URLconf doesn't look at the request method. In other words, all request methods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same @@ -551,15 +552,16 @@ every view in the included URLconf accepts the extra options you're passing. Reverse resolution of URLs ========================== -A common need when working on a Django project is the possibility to obtain URLs -in their final forms either for embedding in generated content (views and assets -URLs, URLs shown to the user, etc.) or for handling of the navigation flow on -the server side (redirections, etc.) +A common need when working on a Django project is the possibility to obtain +URLs in their final forms either for embedding in generated content (views and +assets URLs, URLs shown to the user, etc.) or for handling of the navigation +flow on the server side (redirections, etc.) It is strongly desirable to avoid hardcoding these URLs (a laborious, non-scalable and error-prone strategy). Equally dangerous is devising ad-hoc mechanisms to generate URLs that are parallel to the design described by the -URLconf, which can result in the production of URLs that become stale over time. +URLconf, which can result in the production of URLs that become stale over +time. In other words, what's needed is a DRY mechanism. Among other advantages it would allow evolution of the URL design without having to go over all the @@ -575,8 +577,8 @@ the URL design. You feed it with your URLconf and then it can be used in both directions: * Starting with a URL requested by the user/browser, it calls the right Django - view providing any arguments it might need with their values as extracted from - the URL. + view providing any arguments it might need with their values as extracted + from the URL. * Starting with the identification of the corresponding Django view plus the values of arguments that would be passed to it, obtain the associated URL. @@ -643,8 +645,8 @@ change the entry in the URLconf. In some scenarios where views are of a generic nature, a many-to-one relationship might exist between URLs and views. For these cases the view name -isn't a good enough identifier for it when comes the time of reversing -URLs. Read the next section to know about the solution Django provides for this. +isn't a good enough identifier for it when comes the time of reversing URLs. +Read the next section to know about the solution Django provides for this. .. _naming-url-patterns: @@ -726,8 +728,8 @@ index page of the admin application is referenced using ``'admin:index'``. This indicates a namespace of ``'admin'``, and a named URL of ``'index'``. Namespaces can also be nested. The named URL ``'sports:polls:index'`` would -look for a pattern named ``'index'`` in the namespace ``'polls'`` that is itself -defined within the top-level namespace ``'sports'``. +look for a pattern named ``'index'`` in the namespace ``'polls'`` that is +itself defined within the top-level namespace ``'sports'``. .. _topics-http-reversing-url-namespaces: @@ -771,11 +773,11 @@ resolved into a URL in the namespace that has been found. Example ~~~~~~~ -To show this resolution strategy in action, consider an example of two instances -of the ``polls`` application from the tutorial: one called ``'author-polls'`` -and one called ``'publisher-polls'``. Assume we have enhanced that application -so that it takes the instance namespace into consideration when creating and -displaying polls. +To show this resolution strategy in action, consider an example of two +instances of the ``polls`` application from the tutorial: one called +``'author-polls'`` and one called ``'publisher-polls'``. Assume we have +enhanced that application so that it takes the instance namespace into +consideration when creating and displaying polls. .. code-block:: python :caption: ``urls.py`` @@ -803,10 +805,10 @@ displaying polls. Using this setup, the following lookups are possible: -* If one of the instances is current - say, if we were rendering the detail page - in the instance ``'author-polls'`` - ``'polls:index'`` will resolve to the - index page of the ``'author-polls'`` instance; i.e. both of the following will - result in ``"/author-polls/"``. +* If one of the instances is current - say, if we were rendering the detail + page in the instance ``'author-polls'`` - ``'polls:index'`` will resolve to + the index page of the ``'author-polls'`` instance; i.e. both of the following + will result in ``"/author-polls/"``. In the method of a class-based view:: @@ -825,8 +827,8 @@ Using this setup, the following lookups are possible: registered will be used. This would be ``'publisher-polls'`` since it's declared last in the ``urlpatterns``. -* ``'author-polls:index'`` will always resolve to the index page of the instance - ``'author-polls'`` (and likewise for ``'publisher-polls'``) . +* ``'author-polls:index'`` will always resolve to the index page of the + instance ``'author-polls'`` (and likewise for ``'publisher-polls'``). If there were also a default instance - i.e., an instance named ``'polls'`` - the only change from above would be in the case where there is no current @@ -869,7 +871,8 @@ not the list of ``urlpatterns`` itself. path("polls/", include("polls.urls")), ] -The URLs defined in ``polls.urls`` will have an application namespace ``polls``. +The URLs defined in ``polls.urls`` will have an application namespace +``polls``. Secondly, you can include an object that contains embedded namespace data. If you ``include()`` a list of :func:`~django.urls.path` or diff --git a/docs/topics/http/views.txt b/docs/topics/http/views.txt index feb4eaa4ec..ad5de9b2ba 100644 --- a/docs/topics/http/views.txt +++ b/docs/topics/http/views.txt @@ -2,15 +2,15 @@ Writing views ============= -A view function, or *view* for short, is a Python function that takes a -web request and returns a web response. This response can be the HTML contents -of a web page, or a redirect, or a 404 error, or an XML document, or an image . -. . or anything, really. The view itself contains whatever arbitrary logic is -necessary to return that response. This code can live anywhere you want, as long -as it's on your Python path. There's no other requirement--no "magic," so to -speak. For the sake of putting the code *somewhere*, the convention is to -put views in a file called ``views.py``, placed in your project or -application directory. +A view function, or *view* for short, is a Python function that takes a web +request and returns a web response. This response can be the HTML contents of a +web page, or a redirect, or a 404 error, or an XML document, or an image . . . +or anything, really. The view itself contains whatever arbitrary logic is +necessary to return that response. This code can live anywhere you want, as +long as it's on your Python path. There's no other requirement--no "magic," so +to speak. For the sake of putting the code *somewhere*, the convention is to +put views in a file called ``views.py``, placed in your project or application +directory. A simple view ============= @@ -55,8 +55,8 @@ Mapping URLs to views ===================== So, to recap, this view function returns an HTML page that includes the current -date and time. To display this view at a particular URL, you'll need to create a -*URLconf*; see :doc:`/topics/http/urls` for instructions. +date and time. To display this view at a particular URL, you'll need to create +a *URLconf*; see :doc:`/topics/http/urls` for instructions. Returning errors ================ @@ -107,10 +107,11 @@ you're responsible for defining the HTML of the resulting error page:: return HttpResponseNotFound("<h1>Page not found</h1>") -For convenience, and because it's a good idea to have a consistent 404 error page -across your site, Django provides an ``Http404`` exception. If you raise -``Http404`` at any point in a view function, Django will catch it and return the -standard error page for your application, along with an HTTP error code 404. +For convenience, and because it's a good idea to have a consistent 404 error +page across your site, Django provides an ``Http404`` exception. If you raise +``Http404`` at any point in a view function, Django will catch it and return +the standard error page for your application, along with an HTTP error code +404. Example usage:: diff --git a/docs/topics/i18n/formatting.txt b/docs/topics/i18n/formatting.txt index 15dde5f82d..c670f02b25 100644 --- a/docs/topics/i18n/formatting.txt +++ b/docs/topics/i18n/formatting.txt @@ -28,9 +28,10 @@ in different ways, depending on the formats for their current locale. Locale aware input in forms =========================== -When formatting is enabled, Django can use localized formats when parsing dates, -times and numbers in forms. That means it tries different formats for different -locales when guessing the format used by the user when inputting data on forms. +When formatting is enabled, Django can use localized formats when parsing +dates, times and numbers in forms. That means it tries different formats for +different locales when guessing the format used by the user when inputting data +on forms. .. note:: Django uses different formats for displaying data to those it uses for @@ -92,8 +93,8 @@ To activate or deactivate localization for a template block, use: When localization is disabled, the :ref:`localization settings <settings-l10n>` formats are applied. -See :tfilter:`localize` and :tfilter:`unlocalize` for template filters that will -do the same job on a per-variable basis. +See :tfilter:`localize` and :tfilter:`unlocalize` for template filters that +will do the same job on a per-variable basis. Template filters ---------------- @@ -113,9 +114,9 @@ For example: {{ value|localize }} -To disable localization on a single value, use :tfilter:`unlocalize`. To control -localization over a large section of a template, use the :ttag:`localize` template -tag. +To disable localization on a single value, use :tfilter:`unlocalize`. To +control localization over a large section of a template, use the +:ttag:`localize` template tag. .. templatefilter:: unlocalize diff --git a/docs/topics/i18n/index.txt b/docs/topics/i18n/index.txt index d7b8087640..57b6ab89f1 100644 --- a/docs/topics/i18n/index.txt +++ b/docs/topics/i18n/index.txt @@ -23,8 +23,8 @@ Django has full support for :doc:`translation of text Essentially, Django does two things: -* It allows developers and template authors to specify which parts of their apps - should be translated or formatted for local languages and cultures. +* It allows developers and template authors to specify which parts of their + apps should be translated or formatted for local languages and cultures. * It uses these hooks to localize web apps for particular users according to their preferences. @@ -46,7 +46,8 @@ here's a simplified definition: localization Writing the translations and local formats. Usually done by translators. -More details can be found in the `W3C Web Internationalization FAQ`_, the `Wikipedia article`_ or the `GNU gettext documentation`_. +More details can be found in the `W3C Web Internationalization FAQ`_, the +`Wikipedia article`_ or the `GNU gettext documentation`_. .. _W3C Web Internationalization FAQ: https://www.w3.org/International/questions/qa-i18n .. _GNU gettext documentation: https://www.gnu.org/software/gettext/manual/gettext.html#Concepts @@ -87,5 +88,5 @@ Here are some other terms that will help us to handle a common language: A literal that can be translated. format file - A format file is a Python module that defines the data formats for a given - locale. + A format file is a Python module that defines the data formats for a + given locale. diff --git a/docs/topics/i18n/timezones.txt b/docs/topics/i18n/timezones.txt index dae0209f3a..465605b4db 100644 --- a/docs/topics/i18n/timezones.txt +++ b/docs/topics/i18n/timezones.txt @@ -61,9 +61,9 @@ current time, you would write:: now = datetime.datetime.now() -When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses -time-zone-aware datetime objects. If your code creates datetime objects, they -should be aware too. In this mode, the example above becomes:: +When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django +uses time-zone-aware datetime objects. If your code creates datetime objects, +they should be aware too. In this mode, the example above becomes:: from django.utils import timezone @@ -136,8 +136,9 @@ used. backwards-compatibility with applications that still rely on local time. However, :ref:`as explained above <naive-datetime-objects>`, this isn't entirely reliable, and you should always work with aware datetimes in UTC - in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp` - and set the ``tz`` parameter to :obj:`datetime.UTC`. + in your own code. For instance, use + :meth:`~datetime.datetime.fromtimestamp` and set the ``tz`` parameter to + :obj:`datetime.UTC`. Selecting the current time zone ------------------------------- diff --git a/docs/topics/i18n/translation.txt b/docs/topics/i18n/translation.txt index e3d60d33b5..dd2a9a2890 100644 --- a/docs/topics/i18n/translation.txt +++ b/docs/topics/i18n/translation.txt @@ -294,10 +294,10 @@ these words correctly in different contexts, you can use the :func:`django.utils.translation.npgettext` function if the string needs pluralization. Both take a context string as the first variable. -In the resulting ``.po`` file, the string will then appear as often as there are -different contextual markers for the same string (the context will appear on the -``msgctxt`` line), allowing the translator to give a different translation for -each of them. +In the resulting ``.po`` file, the string will then appear as often as there +are different contextual markers for the same string (the context will appear +on the ``msgctxt`` line), allowing the translator to give a different +translation for each of them. For example:: @@ -571,12 +571,12 @@ Similar access to this information is available for template code. See below. Internationalization: in template code ====================================== -Translations in :doc:`Django templates </ref/templates/language>` uses two template -tags and a slightly different syntax than in Python code. To give your template -access to these tags, put ``{% load i18n %}`` toward the top of your template. -As with all template tags, this tag needs to be loaded in all templates which -use translations, even those templates that extend from other templates which -have already loaded the ``i18n`` tag. +Translations in :doc:`Django templates </ref/templates/language>` uses two +template tags and a slightly different syntax than in Python code. To give your +template access to these tags, put ``{% load i18n %}`` toward the top of your +template. As with all template tags, this tag needs to be loaded in all +templates which use translations, even those templates that extend from other +templates which have already loaded the ``i18n`` tag. .. warning:: @@ -693,8 +693,8 @@ You can use multiple expressions inside a single ``blocktranslate`` tag: .. note:: The previous more verbose format is still supported: ``{% blocktranslate with book|title as book_t and author|title as author_t %}`` -Other block tags (for example :ttag:`{% for %}<for>` or :ttag:`{% if %}<if>`) are -not allowed inside a ``blocktranslate`` tag. +Other block tags (for example :ttag:`{% for %}<for>` or :ttag:`{% if %}<if>`) +are not allowed inside a ``blocktranslate`` tag. If resolving one of the block arguments fails, ``blocktranslate`` will fall back to the default language by deactivating the currently active language @@ -827,7 +827,8 @@ tag: <p>{% blocktranslate %}A multiline translatable literal.{% endblocktranslate %}</p> -or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`: +or with the ``{#`` ... ``#}`` +:ref:`one-line comment constructs <template-comments>`: .. code-block:: html+django @@ -999,7 +1000,8 @@ There are also some filters available for convenience: * ``{{ LANGUAGE_CODE|language_name }}`` ("German") * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch") * ``{{ LANGUAGE_CODE|language_bidi }}`` (False) -* ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech) +* ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active + language is Czech) Internationalization: in JavaScript code ======================================== @@ -1018,8 +1020,8 @@ Django provides an integrated solution for these problems: It passes the translations into JavaScript, so you can call ``gettext``, etc., from within JavaScript. -The main solution to these problems is the following ``JavaScriptCatalog`` view, -which generates a JavaScript code library with functions that mimic the +The main solution to these problems is the following ``JavaScriptCatalog`` +view, which generates a JavaScript code library with functions that mimic the ``gettext`` interface, plus an array of translation strings. The ``JavaScriptCatalog`` view @@ -1262,8 +1264,8 @@ a word or not: In the simplest case, if no custom pluralization is needed, this returns ``false`` for the integer ``1`` and ``true`` for all other numbers. -However, pluralization is not this simple in all languages. If the language does -not support pluralization, an empty value is provided. +However, pluralization is not this simple in all languages. If the language +does not support pluralization, an empty value is provided. Additionally, if there are complex rules around pluralization, the catalog view will render a conditional expression. This will evaluate to either a ``true`` @@ -1545,16 +1547,16 @@ Localization: how to create language files ========================================== Once the string literals of an application have been tagged for later -translation, the translation themselves need to be written (or obtained). Here's -how that works. +translation, the translation themselves need to be written (or obtained). +Here's how that works. Message files ------------- -The first step is to create a :term:`message file` for a new language. A message -file is a plain-text file, representing a single language, that contains all -available translation strings and how they should be represented in the given -language. Message files have a ``.po`` file extension. +The first step is to create a :term:`message file` for a new language. A +message file is a plain-text file, representing a single language, that +contains all available translation strings and how they should be represented +in the given language. Message files have a ``.po`` file extension. Django comes with a tool, :djadmin:`django-admin makemessages <makemessages>`, that automates the creation and upkeep of these files. @@ -1591,12 +1593,12 @@ directory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be ``locale/de/LC_MESSAGES/django.po``. When you run ``makemessages`` from the root directory of your project, the -extracted strings will be automatically distributed to the proper message files. -That is, a string extracted from a file of an app containing a ``locale`` -directory will go in a message file under that directory. A string extracted -from a file of an app without any ``locale`` directory will either go in a -message file under the directory listed first in :setting:`LOCALE_PATHS` or -will generate an error if :setting:`LOCALE_PATHS` is empty. +extracted strings will be automatically distributed to the proper message +files. That is, a string extracted from a file of an app containing a +``locale`` directory will go in a message file under that directory. A string +extracted from a file of an app without any ``locale`` directory will either go +in a message file under the directory listed first in :setting:`LOCALE_PATHS` +or will generate an error if :setting:`LOCALE_PATHS` is empty. By default :djadmin:`django-admin makemessages <makemessages>` examines every file that has the ``.html``, ``.txt`` or ``.py`` file extension. If you want to @@ -1725,13 +1727,13 @@ Compiling message files ----------------------- After you create your message file -- and each time you make changes to it -- -you'll need to compile it into a more efficient form, for use by ``gettext``. Do -this with the :djadmin:`django-admin compilemessages <compilemessages>` +you'll need to compile it into a more efficient form, for use by ``gettext``. +Do this with the :djadmin:`django-admin compilemessages <compilemessages>` utility. -This tool runs over all available ``.po`` files and creates ``.mo`` files, which -are binary files optimized for use by ``gettext``. In the same directory from -which you ran :djadmin:`django-admin makemessages <makemessages>`, run +This tool runs over all available ``.po`` files and creates ``.mo`` files, +which are binary files optimized for use by ``gettext``. In the same directory +from which you ran :djadmin:`django-admin makemessages <makemessages>`, run :djadmin:`django-admin compilemessages <compilemessages>` like this: .. code-block:: shell @@ -1783,11 +1785,11 @@ literals:: Creating message files from JavaScript source code -------------------------------------------------- -You create and update the message files the same way as the other Django message -files -- with the :djadmin:`django-admin makemessages <makemessages>` tool. -The only difference is you need to explicitly specify what in gettext parlance -is known as a domain in this case the ``djangojs`` domain, by providing a ``-d -djangojs`` parameter, like this: +You create and update the message files the same way as the other Django +message files -- with the :djadmin:`django-admin makemessages <makemessages>` +tool. The only difference is you need to explicitly specify what in gettext +parlance is known as a domain in this case the ``djangojs`` domain, by +providing a ``-d djangojs`` parameter, like this: .. code-block:: shell @@ -1802,11 +1804,12 @@ updating message files, run :djadmin:`django-admin compilemessages ``gettext`` on Windows ---------------------- -This is only needed for people who either want to extract message IDs or compile -message files (``.po``). Translation work itself involves editing existing -files of this type, but if you want to create your own message files, or want -to test or compile a changed message file, download `a precompiled binary -installer <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_. +This is only needed for people who either want to extract message IDs or +compile message files (``.po``). Translation work itself involves editing +existing files of this type, but if you want to create your own message files, +or want to test or compile a changed message file, download `a precompiled +binary installer +<https://mlocati.github.io/articles/gettext-iconv-windows.html>`_. You may also use ``gettext`` binaries you have obtained elsewhere, so long as the ``xgettext --version`` command works properly. Do not attempt to use Django @@ -1864,9 +1867,9 @@ The ``set_language`` redirect view .. function:: set_language(request) -As a convenience, Django comes with a view, :func:`django.views.i18n.set_language`, -that sets a user's language preference and redirects to a given URL or, by default, -back to the previous page. +As a convenience, Django comes with a view, +:func:`django.views.i18n.set_language`, that sets a user's language preference +and redirects to a given URL or, by default, back to the previous page. Activate this view by adding the following line to your URLconf:: @@ -1929,12 +1932,12 @@ redirected in the ``redirect_to`` context variable. Explicitly setting the active language -------------------------------------- -You may want to set the active language for the current session explicitly. Perhaps -a user's language preference is retrieved from another system, for example. -You've already been introduced to :func:`django.utils.translation.activate`. That -applies to the current thread only. To persist the language for the entire -session in a cookie, set the :setting:`LANGUAGE_COOKIE_NAME` cookie on the -response:: +You may want to set the active language for the current session explicitly. +Perhaps a user's language preference is retrieved from another system, for +example. You've already been introduced to +:func:`django.utils.translation.activate`. That applies to the current thread +only. To persist the language for the entire session in a cookie, set the +:setting:`LANGUAGE_COOKIE_NAME` cookie on the response:: from django.conf import settings from django.http import HttpResponse @@ -2057,9 +2060,9 @@ prefer, then you also need to use the ``LocaleMiddleware``. ``LocaleMiddleware`` enables language selection based on data from the request. It customizes content for each user. -To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'`` -to your :setting:`MIDDLEWARE` setting. Because middleware order matters, follow -these guidelines: +To use ``LocaleMiddleware``, add +``'django.middleware.locale.LocaleMiddleware'`` to your :setting:`MIDDLEWARE` +setting. Because middleware order matters, follow these guidelines: * Make sure it's one of the first middleware installed. * It should come after ``SessionMiddleware``, because ``LocaleMiddleware`` @@ -2168,11 +2171,11 @@ in ``request.LANGUAGE_CODE``. How Django discovers translations --------------------------------- -At runtime, Django builds an in-memory unified catalog of literals-translations. -To achieve this it looks for translations by following this algorithm regarding -the order in which it examines the different file paths to load the compiled -:term:`message files <message file>` (``.mo``) and the precedence of multiple -translations for the same literal: +At runtime, Django builds an in-memory unified catalog of +literals-translations. To achieve this it looks for translations by following +this algorithm regarding the order in which it examines the different file +paths to load the compiled :term:`message files <message file>` (``.mo``) and +the precedence of multiple translations for the same literal: #. The directories listed in :setting:`LOCALE_PATHS` have the highest precedence, with the ones appearing first having higher precedence than @@ -2180,8 +2183,8 @@ translations for the same literal: #. Then, it looks for and uses if it exists a ``locale`` directory in each of the installed apps listed in :setting:`INSTALLED_APPS`. The ones appearing first have higher precedence than the ones appearing later. -#. Finally, the Django-provided base translation in :source:`django/conf/locale` - is used as a fallback. +#. Finally, the Django-provided base translation in + :source:`django/conf/locale` is used as a fallback. .. seealso:: @@ -2193,11 +2196,11 @@ translations for the same literal: :setting:`LOCALE_PATHS` directories if you also set :setting:`FORMAT_MODULE_PATH`. -In all cases the name of the directory containing the translation is expected to -be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, ``es_AR``, -etc. Untranslated strings for territorial language variants use the translations -of the generic language. For example, untranslated ``pt_BR`` strings use ``pt`` -translations. +In all cases the name of the directory containing the translation is expected +to be named using :term:`locale name` notation. E.g. ``de``, ``pt_BR``, +``es_AR``, etc. Untranslated strings for territorial language variants use the +translations of the generic language. For example, untranslated ``pt_BR`` +strings use ``pt`` translations. This way, you can write applications that include their own translations, and you can override base translations in your project. Or, you can build a big @@ -2211,9 +2214,10 @@ All message file repositories are structured the same way. They are: * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)`` * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)`` -To create message files, you use the :djadmin:`django-admin makemessages <makemessages>` -tool. And you use :djadmin:`django-admin compilemessages <compilemessages>` -to produce the binary ``.mo`` files that are used by ``gettext``. +To create message files, you use the +:djadmin:`django-admin makemessages <makemessages>` tool. And you use +:djadmin:`django-admin compilemessages <compilemessages>` to produce the binary +``.mo`` files that are used by ``gettext``. You can also run :djadmin:`django-admin compilemessages --settings=path.to.settings <compilemessages>` to make the compiler process all @@ -2223,8 +2227,8 @@ Using a non-English base language --------------------------------- Django makes the general assumption that the original strings in a translatable -project are written in English. You can choose another language, but you must be -aware of certain limitations: +project are written in English. You can choose another language, but you must +be aware of certain limitations: * ``gettext`` only provides two plural forms for the original messages, so you will also need to provide a translation for the base language to include all diff --git a/docs/topics/install.txt b/docs/topics/install.txt index 5200b6b80b..b7b3fde286 100644 --- a/docs/topics/install.txt +++ b/docs/topics/install.txt @@ -47,8 +47,8 @@ for information on how to configure mod_wsgi once you have it installed. If you can't use mod_wsgi for some reason, fear not: Django supports many other -deployment options. One is :doc:`uWSGI </howto/deployment/wsgi/uwsgi>`; it works -very well with `nginx`_. Additionally, Django follows the WSGI spec +deployment options. One is :doc:`uWSGI </howto/deployment/wsgi/uwsgi>`; it +works very well with `nginx`_. Additionally, Django follows the WSGI spec (:pep:`3333`), which allows it to run on a variety of server platforms. .. _Apache: https://httpd.apache.org/ @@ -133,8 +133,8 @@ the tables, you can grant Django ``SELECT``, ``INSERT``, ``UPDATE`` and you'll specify the details in your project's settings file, see :setting:`DATABASES` for details. -If you're using Django's :doc:`testing framework</topics/testing/index>` to test -database queries, Django will need permission to create a test database. +If you're using Django's :doc:`testing framework</topics/testing/index>` to +test database queries, Django will need permission to create a test database. .. _PostgreSQL: https://www.postgresql.org/ .. _MariaDB: https://mariadb.org/ @@ -189,8 +189,8 @@ Installing a distribution-specific package Check the :doc:`distribution specific notes </misc/distributions>` to see if your platform/distribution provides official Django packages/installers. Distribution-provided packages will typically allow for automatic installation -of dependencies and supported upgrade paths; however, these packages will rarely -contain the latest release of Django. +of dependencies and supported upgrade paths; however, these packages will +rarely contain the latest release of Django. .. _installing-development-version: diff --git a/docs/topics/migrations.txt b/docs/topics/migrations.txt index 2f848e20ea..90034b0dfe 100644 --- a/docs/topics/migrations.txt +++ b/docs/topics/migrations.txt @@ -203,11 +203,11 @@ a migration that requires something else to run - for example, you add a migration will contain a dependency on a migration in ``authors``. This means that when you run the migrations, the ``authors`` migration runs -first and creates the table the ``ForeignKey`` references, and then the migration -that makes the ``ForeignKey`` column runs afterward and creates the constraint. -If this didn't happen, the migration would try to create the ``ForeignKey`` -column without the table it's referencing existing and your database would -throw an error. +first and creates the table the ``ForeignKey`` references, and then the +migration that makes the ``ForeignKey`` column runs afterward and creates the +constraint. If this didn't happen, the migration would try to create the +``ForeignKey`` column without the table it's referencing existing and your +database would throw an error. This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in @@ -485,8 +485,9 @@ that contains a reference to them. On the plus side, methods and managers from these base classes inherit normally, so if you absolutely need access to these you can opt to move them into a superclass. -To remove old references, you can :ref:`squash migrations <migration-squashing>` -or, if there aren't many references, copy them into the migration files. +To remove old references, you can :ref:`squash migrations +<migration-squashing>` or, if there aren't many references, copy them into the +migration files. .. _migrations-removing-model-fields: @@ -574,8 +575,8 @@ Then, open up the file; it should look something like this:: Now, all you need to do is create a new function and have :class:`~django.db.migrations.operations.RunPython` use it. -:class:`~django.db.migrations.operations.RunPython` expects a callable as its argument -which takes two arguments - the first is an :doc:`app registry +:class:`~django.db.migrations.operations.RunPython` expects a callable as its +argument which takes two arguments - the first is an :doc:`app registry </ref/applications/>` that has the historical versions of all your models loaded into it to match where in your history the migration sits, and the second is a :doc:`SchemaEditor </ref/schema-editor>`, which you can use to @@ -622,8 +623,8 @@ Accessing models from other apps When writing a ``RunPython`` function that uses models from apps other than the one in which the migration is located, the migration's ``dependencies`` attribute should include the latest migration of each app that is involved, -otherwise you may get an error similar to: ``LookupError: No installed app -with label 'myappname'`` when you try to retrieve the model in the ``RunPython`` +otherwise you may get an error similar to: ``LookupError: No installed app with +label 'myappname'`` when you try to retrieve the model in the ``RunPython`` function using ``apps.get_model()``. In the following example, we have a migration in ``app1`` which needs to use @@ -717,8 +718,9 @@ the name of the squashed migration rather than use an autogenerated one. Note that model interdependencies in Django can get very complex, and squashing may result in migrations that do not run; either mis-optimized (in which case -you can try again with ``--no-optimize``, though you should also report an issue), -or with a ``CircularDependencyError``, in which case you can manually resolve it. +you can try again with ``--no-optimize``, though you should also report an +issue), or with a ``CircularDependencyError``, in which case you can manually +resolve it. To manually resolve a ``CircularDependencyError``, break out one of the ForeignKeys in the circular dependency loop into a separate @@ -739,7 +741,8 @@ You can then transition the squashed migration to a normal migration by: - Updating all migrations that depend on the deleted migrations to depend on the squashed migration instead. - Removing the ``replaces`` attribute in the ``Migration`` class of the - squashed migration (this is how Django tells that it is a squashed migration). + squashed migration (this is how Django tells that it is a squashed + migration). .. note:: You can squash squashed migrations themselves without transitioning to @@ -802,7 +805,8 @@ Django can serialize the following: - Unbound methods used from within the class body - Any class reference (must be in module's top-level scope) -- Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`) +- Anything with a custom ``deconstruct()`` method + (:ref:`see below <custom-deconstruct-method>`) .. versionchanged:: 6.0 @@ -848,9 +852,9 @@ the migration. Adding a ``deconstruct()`` method --------------------------------- -You can let Django serialize your own custom class instances by giving the class -a ``deconstruct()`` method. It takes no arguments, and should return a tuple -of three things ``(path, args, kwargs)``: +You can let Django serialize your own custom class instances by giving the +class a ``deconstruct()`` method. It takes no arguments, and should return a +tuple of three things ``(path, args, kwargs)``: * ``path`` should be the Python path to the class, with the class name included as the last part (for example, ``myapp.custom_things.MyClass``). If your diff --git a/docs/topics/performance.txt b/docs/topics/performance.txt index c6231a41c8..042c09f8d3 100644 --- a/docs/topics/performance.txt +++ b/docs/topics/performance.txt @@ -248,7 +248,8 @@ Other database-related tips Enabling :ref:`persistent-database-connections` can speed up connections to the database accounts for a significant part of the request processing time. -This helps a lot on virtualized hosts with limited network performance, for example. +This helps a lot on virtualized hosts with limited network performance, for +example. HTTP performance ================ @@ -272,7 +273,8 @@ needed. Compresses responses for all modern browsers, saving bandwidth and transfer time. Note that GZipMiddleware is currently considered a security risk, and is vulnerable to attacks that nullify the protection provided by TLS/SSL. See the -warning in :class:`~django.middleware.gzip.GZipMiddleware` for more information. +warning in :class:`~django.middleware.gzip.GZipMiddleware` for more +information. Sessions -------- @@ -297,8 +299,8 @@ optimization gains. By taking advantage of web browsers' caching abilities, you can eliminate network hits entirely for a given file after the initial download. -:class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` appends a -content-dependent tag to the filenames of :doc:`static files +:class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` appends +a content-dependent tag to the filenames of :doc:`static files </ref/contrib/staticfiles>` to make it safe for browsers to cache them long-term without missing future changes - when a file changes, so will the tag, so browsers will reload the asset automatically. diff --git a/docs/topics/security.txt b/docs/topics/security.txt index 754be0b495..2e828db0ab 100644 --- a/docs/topics/security.txt +++ b/docs/topics/security.txt @@ -43,9 +43,9 @@ protect the following: .. highlighting as html+django fails due to intentionally missing quotes. -If ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can result -in unauthorized JavaScript execution, depending on how the browser renders -imperfect HTML. (Quoting the attribute value would fix this case.) +If ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can +result in unauthorized JavaScript execution, depending on how the browser +renders imperfect HTML. (Quoting the attribute value would fix this case.) It is also important to be particularly careful when using ``is_safe`` with custom template tags, the :tfilter:`safe` template tag, :mod:`mark_safe @@ -65,13 +65,13 @@ Cross site request forgery (CSRF) protection CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user's knowledge or consent. -Django has built-in protection against most types of CSRF attacks, providing you -have :ref:`enabled and used it <using-csrf>` where appropriate. However, as with -any mitigation technique, there are limitations. For example, it is possible to -disable the CSRF module globally or for particular views. You should only do -this if you know what you are doing. There are other :ref:`limitations -<csrf-limitations>` if your site has subdomains that are outside of your -control. +Django has built-in protection against most types of CSRF attacks, providing +you have :ref:`enabled and used it <using-csrf>` where appropriate. However, as +with any mitigation technique, there are limitations. For example, it is +possible to disable the CSRF module globally or for particular views. You +should only do this if you know what you are doing. There are other +:ref:`limitations <csrf-limitations>` if your site has subdomains that are +outside of your control. :ref:`CSRF protection works <how-csrf-works>` by checking for a secret in each POST request. This ensures that a malicious user cannot "replay" a form POST to @@ -107,8 +107,9 @@ Django also gives developers power to write :ref:`raw queries <executing-raw-queries>` or execute :ref:`custom sql <executing-custom-sql>`. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you -should exercise caution when using :meth:`~django.db.models.query.QuerySet.extra` -and :class:`~django.db.models.expressions.RawSQL`. +should exercise caution when using +:meth:`~django.db.models.query.QuerySet.extra` and +:class:`~django.db.models.expressions.RawSQL`. Clickjacking protection ======================= @@ -117,12 +118,12 @@ Clickjacking is a type of attack where a malicious site wraps another site in a frame. This attack can result in an unsuspecting user being tricked into performing unintended actions on the target site. -Django contains :ref:`clickjacking protection <clickjacking-prevention>` in -the form of the -:mod:`X-Frame-Options middleware <django.middleware.clickjacking.XFrameOptionsMiddleware>` -which in a supporting browser can prevent a site from being rendered inside -a frame. It is possible to disable the protection on a per view basis -or to configure the exact header value sent. +Django contains :ref:`clickjacking protection <clickjacking-prevention>` in the +form of the :mod:`X-Frame-Options middleware +<django.middleware.clickjacking.XFrameOptionsMiddleware>` which in a supporting +browser can prevent a site from being rendered inside a frame. It is possible +to disable the protection on a per view basis or to configure the exact header +value sent. The middleware is strongly recommended for any site that does not need to have its pages wrapped in a frame by third party sites, or only needs to allow that @@ -159,21 +160,21 @@ server, there are some additional steps you may need: If a browser connects initially via HTTP, which is the default for most browsers, it is possible for existing cookies to be leaked. For this reason, you should set your :setting:`SESSION_COOKIE_SECURE` and - :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the browser - to only send these cookies over HTTPS connections. Note that this will mean - that sessions will not work over HTTP, and the CSRF protection will prevent - any POST data being accepted over HTTP (which will be fine if you are + :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the + browser to only send these cookies over HTTPS connections. Note that this + will mean that sessions will not work over HTTP, and the CSRF protection will + prevent any POST data being accepted over HTTP (which will be fine if you are redirecting all HTTP traffic to HTTPS). * Use :ref:`http-strict-transport-security` (HSTS) - HSTS is an HTTP header that informs a browser that all future connections - to a particular site should always use HTTPS. Combined with redirecting - requests over HTTP to HTTPS, this will ensure that connections always enjoy - the added security of SSL provided one successful connection has occurred. - HSTS may either be configured with :setting:`SECURE_HSTS_SECONDS`, - :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`, and :setting:`SECURE_HSTS_PRELOAD`, - or on the web server. + HSTS is an HTTP header that informs a browser that all future connections to + a particular site should always use HTTPS. Combined with redirecting requests + over HTTP to HTTPS, this will ensure that connections always enjoy the added + security of SSL provided one successful connection has occurred. HSTS may + either be configured with :setting:`SECURE_HSTS_SECONDS`, + :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`, and + :setting:`SECURE_HSTS_PRELOAD`, or on the web server. .. _host-headers-virtual-hosting: @@ -198,8 +199,8 @@ For more details see the full :setting:`ALLOWED_HOSTS` documentation. .. warning:: - Previous versions of this document recommended configuring your web server to - ensure it validates incoming HTTP ``Host`` headers. While this is still + Previous versions of this document recommended configuring your web server + to ensure it validates incoming HTTP ``Host`` headers. While this is still recommended, in many common web servers a configuration that seems to validate the ``Host`` header may not in fact do so. For instance, even if Apache is configured such that your Django site is served from a non-default @@ -255,9 +256,9 @@ User-uploaded content can be easily set using the LimitRequestBody_ directive. * If you are serving your own static files, be sure that handlers like Apache's - ``mod_php``, which would execute static files as code, are disabled. You don't - want users to be able to execute arbitrary code by uploading and requesting a - specially crafted file. + ``mod_php``, which would execute static files as code, are disabled. You + don't want users to be able to execute arbitrary code by uploading and + requesting a specially crafted file. * Django's media upload handling poses some vulnerabilities when that media is served in ways that do not follow security best practices. Specifically, an @@ -362,8 +363,8 @@ security protection of the web server, operating system and other components. * It is a good idea to limit the accessibility of your caching system and database using a firewall. * Take a look at the Open Web Application Security Project (OWASP) `Top 10 - list`_ which identifies some common vulnerabilities in web applications. While - Django has tools to address some of the issues, other issues must be + list`_ which identifies some common vulnerabilities in web applications. + While Django has tools to address some of the issues, other issues must be accounted for in the design of your project. * Mozilla discusses various topics regarding `web security`_. Their pages also include security principles that apply to any system. diff --git a/docs/topics/serialization.txt b/docs/topics/serialization.txt index 12cc616a21..eb99283504 100644 --- a/docs/topics/serialization.txt +++ b/docs/topics/serialization.txt @@ -21,8 +21,8 @@ At the highest level, you can serialize data like this:: data = serializers.serialize("xml", SomeModel.objects.all()) -The arguments to the ``serialize`` function are the format to serialize the data -to (see `Serialization formats`_) and a +The arguments to the ``serialize`` function are the format to serialize the +data to (see `Serialization formats`_) and a :class:`~django.db.models.query.QuerySet` to serialize. (Actually, the second argument can be any iterator that yields Django model instances, but it'll almost always be a QuerySet). @@ -61,8 +61,8 @@ specify a ``fields`` argument to the serializer:: data = serializers.serialize("xml", SomeModel.objects.all(), fields=["name", "size"]) In this example, only the ``name`` and ``size`` attributes of each model will -be serialized. The primary key is always serialized as the ``pk`` element in the -resulting output; it never appears in the ``fields`` part. +be serialized. The primary key is always serialized as the ``pk`` element in +the resulting output; it never appears in the ``fields`` part. .. note:: @@ -224,7 +224,8 @@ the ``auth.User`` model has such a relation to the ``auth.Permission`` model: </field> </object> -This example links the given user with the permission models with PKs 46 and 47. +This example links the given user with the permission models with PKs 46 and +47. .. admonition:: Control characters @@ -604,9 +605,9 @@ When ``use_natural_foreign_keys=True`` is specified, Django will use the ``natural_key()`` method to serialize any foreign key reference to objects of the type that defines the method. -When ``use_natural_primary_keys=True`` is specified, Django will not provide the -primary key in the serialized data of this object since it can be calculated -during deserialization:: +When ``use_natural_primary_keys=True`` is specified, Django will not provide +the primary key in the serialized data of this object since it can be +calculated during deserialization:: ... { diff --git a/docs/topics/settings.txt b/docs/topics/settings.txt index b969cd8088..982668b4b1 100644 --- a/docs/topics/settings.txt +++ b/docs/topics/settings.txt @@ -160,7 +160,8 @@ read it. This is especially important in a shared-hosting environment. Available settings ================== -For a full list of available settings, see the :doc:`settings reference </ref/settings>`. +For a full list of available settings, see the +:doc:`settings reference </ref/settings>`. Creating your own settings ========================== diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt index 7f143c6d79..4d32c55a2b 100644 --- a/docs/topics/signals.txt +++ b/docs/topics/signals.txt @@ -83,7 +83,8 @@ function or method:: print("Request finished!") Notice that the function takes a ``sender`` argument, along with wildcard -keyword arguments (``**kwargs``); all signal handlers must take these arguments. +keyword arguments (``**kwargs``); all signal handlers must take these +arguments. We'll look at senders :ref:`a bit later <connecting-to-specific-signals>`, but right now look at the ``**kwargs`` argument. All signals send keyword @@ -181,9 +182,9 @@ Connecting to signals sent by specific senders Some signals get sent many times, but you'll only be interested in receiving a certain subset of those signals. For example, consider the -:data:`django.db.models.signals.pre_save` signal sent before a model gets saved. -Most of the time, you don't need to know when *any* model gets saved -- just -when one *specific* model is saved. +:data:`django.db.models.signals.pre_save` signal sent before a model gets +saved. Most of the time, you don't need to know when *any* model gets saved -- +just when one *specific* model is saved. In these cases, you can register to receive signals sent only by particular senders. In the case of :data:`django.db.models.signals.pre_save`, the sender @@ -201,9 +202,9 @@ signals sent by some model:: The ``my_handler`` function will only be called when an instance of ``MyModel`` is saved. -Different signals use different objects as their senders; you'll need to consult -the :doc:`built-in signal documentation </ref/signals>` for details of each -particular signal. +Different signals use different objects as their senders; you'll need to +consult the :doc:`built-in signal documentation </ref/signals>` for details of +each particular signal. .. _preventing-duplicate-signals: @@ -298,7 +299,8 @@ be notified of a signal in the face of an error. ``send_robust()`` catches all errors derived from Python's ``Exception`` class, and ensures all receivers are notified of the signal. If an error occurs, the -error instance is returned in the tuple pair for the receiver that raised the error. +error instance is returned in the tuple pair for the receiver that raised the +error. The tracebacks are present on the ``__traceback__`` attribute of the errors returned when calling ``send_robust()``. diff --git a/docs/topics/templates.txt b/docs/topics/templates.txt index 06783f8724..c2e2e15a74 100644 --- a/docs/topics/templates.txt +++ b/docs/topics/templates.txt @@ -381,9 +381,10 @@ must provide a ``render()`` method with the following signature: If ``context`` is provided, it must be a :class:`dict`. If it isn't provided, the engine will render the template with an empty context. - If ``request`` is provided, it must be an :class:`~django.http.HttpRequest`. - Then the engine must make it, as well as the CSRF token, available in the - template. How this is achieved is up to each backend. + If ``request`` is provided, it must be an + :class:`~django.http.HttpRequest`. Then the engine must make it, as well as + the CSRF token, available in the template. How this is achieved is up to + each backend. Here's an example of the search algorithm. For this example the :setting:`TEMPLATES` setting is:: @@ -411,8 +412,8 @@ will look for, in order: * ``/home/html/default/story_detail.html`` (``'django'`` engine) * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine) -If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``, -here's what Django will look for: +If you call ``select_template(['story_253_detail.html', +'story_detail.html'])``, here's what Django will look for: * ``/home/html/example.com/story_253_detail.html`` (``'django'`` engine) * ``/home/html/default/story_253_detail.html`` (``'django'`` engine) @@ -634,12 +635,12 @@ adds defaults that differ from Jinja2's for a few options: .. admonition:: Using context processors with Jinja2 templates is discouraged. - Context processors are useful with Django templates because Django templates - don't support calling functions with arguments. Since Jinja2 doesn't have - that limitation, it's recommended to put the function that you would use as a - context processor in the global variables available to the template using - ``jinja2.Environment`` as described below. You can then call that function in - the template: + Context processors are useful with Django templates because Django + templates don't support calling functions with arguments. Since Jinja2 + doesn't have that limitation, it's recommended to put the function that you + would use as a context processor in the global variables available to the + template using ``jinja2.Environment`` as described below. You can then call + that function in the template: .. code-block:: jinja @@ -655,8 +656,8 @@ adds defaults that differ from Jinja2's for a few options: * Needing the result in every template. * Using the result multiple times in each template. - Unless all of these conditions are met, passing a function to the template is - more in line with the design of Jinja2. + Unless all of these conditions are met, passing a function to the template + is more in line with the design of Jinja2. The default configuration is purposefully kept to a minimum. If a template is rendered with a request (e.g. when using :py:func:`~django.shortcuts.render`), diff --git a/docs/topics/testing/overview.txt b/docs/topics/testing/overview.txt index 80e6663f6b..cafd9dd883 100644 --- a/docs/topics/testing/overview.txt +++ b/docs/topics/testing/overview.txt @@ -11,8 +11,8 @@ Writing and running tests reference </topics/testing/tools>`, and the :doc:`advanced testing topics </topics/testing/advanced>`. -This document is split into two primary sections. First, we explain how to write -tests with Django. Then, we explain how to run them. +This document is split into two primary sections. First, we explain how to +write tests with Django. Then, we explain how to run them. Writing tests ============= @@ -187,12 +187,12 @@ test database is created by the user specified by :setting:`USER`, so you'll need to make sure that the given user account has sufficient privileges to create a new database on the system. -For fine-grained control over the character encoding of your test -database, use the :setting:`CHARSET <TEST_CHARSET>` TEST option. If you're using -MySQL, you can also use the :setting:`COLLATION <TEST_COLLATION>` option to -control the particular collation used by the test database. See the -:doc:`settings documentation </ref/settings>` for details of these -and other advanced settings. +For fine-grained control over the character encoding of your test database, use +the :setting:`CHARSET <TEST_CHARSET>` TEST option. If you're using MySQL, you +can also use the :setting:`COLLATION <TEST_COLLATION>` option to control the +particular collation used by the test database. See the :doc:`settings +documentation </ref/settings>` for details of these and other advanced +settings. If using an SQLite in-memory database with SQLite, `shared cache <https://www.sqlite.org/sharedcache.html>`_ is enabled, so you can write tests @@ -212,7 +212,8 @@ with ability to share the database between threads. .. seealso:: - The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`. + The :ref:`advanced multi-db testing topics + <topics-testing-advanced-multidb>`. .. _order-of-tests: diff --git a/docs/topics/testing/tools.txt b/docs/topics/testing/tools.txt index 7943b3dcac..4c93e762c7 100644 --- a/docs/topics/testing/tools.txt +++ b/docs/topics/testing/tools.txt @@ -301,12 +301,12 @@ Use the ``django.test.Client`` class to make requests. ... c.post("/customers/wishes/", {"name": "fred", "attachment": fp}) ... - You may also provide any file-like object (e.g., :class:`~io.StringIO` or - :class:`~io.BytesIO`) as a file handle. If you're uploading to an + You may also provide any file-like object (e.g., :class:`~io.StringIO` + or :class:`~io.BytesIO`) as a file handle. If you're uploading to an :class:`~django.db.models.ImageField`, the object needs a ``name`` attribute that passes the - :data:`~django.core.validators.validate_image_file_extension` validator. - For example: + :data:`~django.core.validators.validate_image_file_extension` + validator. For example: .. code-block:: pycon @@ -341,8 +341,8 @@ Use the ``django.test.Client`` class to make requests. ... "/login/", {"name": "fred", "passwd": "secret"}, query_params={"visitor": "true"} ... ) - ... the view handling this request could interrogate request.POST - to retrieve the username and password, and could interrogate request.GET + ... the view handling this request could interrogate request.POST to + retrieve the username and password, and could interrogate request.GET to determine if the user was a visitor. If you set ``follow`` to ``True`` the client will follow any redirects @@ -417,10 +417,10 @@ Use the ``django.test.Client`` class to make requests. *Asynchronous version*: ``alogin()`` - If your site uses Django's :doc:`authentication system</topics/auth/index>` - and you deal with logging in users, you can use the test client's - ``login()`` method to simulate the effect of a user logging into the - site. + If your site uses Django's + :doc:`authentication system</topics/auth/index>` and you deal with + logging in users, you can use the test client's ``login()`` method to + simulate the effect of a user logging into the site. After you call this method, the test client will have all the cookies and session data required to pass any login-based tests that may form @@ -493,9 +493,10 @@ Use the ``django.test.Client`` class to make requests. *Asynchronous version*: ``alogout()`` - If your site uses Django's :doc:`authentication system</topics/auth/index>`, - the ``logout()`` method can be used to simulate the effect of a user - logging out of your site. + If your site uses Django's + :doc:`authentication system</topics/auth/index>`, the ``logout()`` + method can be used to simulate the effect of a user logging out of your + site. After you call this method, the test client will have all the cookies and session data cleared to defaults. Subsequent requests will appear @@ -525,11 +526,12 @@ Specifically, a ``Response`` object has the following attributes: .. attribute:: context - The template ``Context`` instance that was used to render the template that - produced the response content. + The template ``Context`` instance that was used to render the template + that produced the response content. - If the rendered page used multiple templates, then ``context`` will be a - list of ``Context`` objects, in the order in which they were rendered. + If the rendered page used multiple templates, then ``context`` will be + a list of ``Context`` objects, in the order in which they were + rendered. Regardless of the number of templates used during rendering, you can retrieve context values using the ``[]`` operator. For example, the @@ -646,9 +648,9 @@ The only exceptions that are not visible to the test client are exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check ``response.status_code`` in your test. -If ``Client.raise_request_exception`` is ``False``, the test client will return a -500 response as would be returned to a browser. The response has the attribute -:attr:`~Response.exc_info` to provide information about the unhandled +If ``Client.raise_request_exception`` is ``False``, the test client will return +a 500 response as would be returned to a browser. The response has the +attribute :attr:`~Response.exc_info` to provide information about the unhandled exception. Persistent state @@ -772,7 +774,8 @@ Provided test case classes ========================== Normal Python unit test classes extend a base class of -:class:`unittest.TestCase`. Django provides a few extensions of this base class: +:class:`unittest.TestCase`. Django provides a few extensions of this base +class: .. _testcase_hierarchy_diagram: @@ -811,12 +814,13 @@ A subclass of :class:`unittest.TestCase` that adds this functionality: * Verifying that two :meth:`URLs <SimpleTestCase.assertURLEqual>` are equal. * Verifying an HTTP :meth:`redirect <SimpleTestCase.assertRedirects>` is performed by the app. - * Robustly testing two :meth:`HTML fragments <SimpleTestCase.assertHTMLEqual>` - for equality/inequality or :meth:`containment <SimpleTestCase.assertInHTML>`. + * Robustly testing two :meth:`HTML fragments + <SimpleTestCase.assertHTMLEqual>` for equality/inequality or + :meth:`containment <SimpleTestCase.assertInHTML>`. * Robustly testing two :meth:`XML fragments <SimpleTestCase.assertXMLEqual>` for equality/inequality. - * Robustly testing two :meth:`JSON fragments <SimpleTestCase.assertJSONEqual>` - for equality. + * Robustly testing two :meth:`JSON fragments + <SimpleTestCase.assertJSONEqual>` for equality. * The ability to run tests with :ref:`modified settings <overriding-settings>`. * Using the :attr:`~SimpleTestCase.client` :class:`~django.test.Client`. @@ -901,9 +905,9 @@ to test the effects of commit and rollback: .. warning:: ``TestCase`` running on a database that does not support rollback (e.g. MySQL - with the MyISAM storage engine), and all instances of ``TransactionTestCase``, - will roll back at the end of the test by deleting all data from the test - database. + with the MyISAM storage engine), and all instances of + ``TransactionTestCase``, will roll back at the end of the test by deleting + all data from the test database. Apps :ref:`will not see their data reloaded <test-case-serialized-rollback>`; if you need this functionality (for example, third-party apps should enable @@ -1105,9 +1109,9 @@ out the `full reference`_ for more details. lambda driver: driver.find_element(By.TAG_NAME, "body") ) - The tricky thing here is that there's really no such thing as a "page load," - especially in modern web apps that generate HTML dynamically after the - server generates the initial document. So, checking for the presence of + The tricky thing here is that there's really no such thing as a "page + load," especially in modern web apps that generate HTML dynamically after + the server generates the initial document. So, checking for the presence of ``<body>`` in the response might not necessarily be appropriate for all use cases. Please refer to the `Selenium FAQ`_ and `Selenium documentation`_ for more information. @@ -1335,9 +1339,9 @@ Overriding settings .. warning:: - Use the functions below to temporarily alter the value of settings in tests. - Don't manipulate ``django.conf.settings`` directly as Django won't restore - the original values after such manipulations. + Use the functions below to temporarily alter the value of settings in + tests. Don't manipulate ``django.conf.settings`` directly as Django won't + restore the original values after such manipulations. .. method:: SimpleTestCase.settings() @@ -1595,8 +1599,8 @@ For more detail on email services during tests, see `Email services`_ below. Assertions ---------- -As Python's normal :class:`unittest.TestCase` class implements assertion methods -such as :meth:`~unittest.TestCase.assertTrue` and +As Python's normal :class:`unittest.TestCase` class implements assertion +methods such as :meth:`~unittest.TestCase.assertTrue` and :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class provides a number of custom assertion methods that are useful for testing web applications: @@ -1641,7 +1645,8 @@ your test suite. error messages. :param field_args: the args passed to instantiate the field. :param field_kwargs: the kwargs passed to instantiate the field. - :param empty_value: the expected clean output for inputs in ``empty_values``. + :param empty_value: the expected clean output for inputs in + ``empty_values``. For example, the following code tests that an ``EmailField`` accepts ``a@a.com`` as a valid email address, but rejects ``aaa`` with a reasonable @@ -1660,8 +1665,8 @@ your test suite. validated (``assertFormError()`` will automatically call ``full_clean()`` on the form). - ``field`` is the name of the field on the form to check. To check the form's - :meth:`non-field errors <django.forms.Form.non_field_errors>`, use + ``field`` is the name of the field on the form to check. To check the + form's :meth:`non-field errors <django.forms.Form.non_field_errors>`, use ``field=None``. ``errors`` is a list of all the error strings that the field is expected to @@ -1763,8 +1768,8 @@ your test suite. particularly useful if ``expected_url`` isn't part of your Django app. Scheme is handled correctly when making comparisons between two URLs. If - there isn't any scheme specified in the location where we are redirected to, - the original request's scheme is used. If present, the scheme in + there isn't any scheme specified in the location where we are redirected + to, the original request's scheme is used. If present, the scheme in ``expected_url`` is the one used to make the comparisons to. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None) @@ -1841,8 +1846,8 @@ your test suite. Asserts that the HTML fragment ``needle`` is contained in the ``haystack`` once. - If the ``count`` integer argument is specified, then additionally the number - of ``needle`` occurrences will be strictly verified. + If the ``count`` integer argument is specified, then additionally the + number of ``needle`` occurrences will be strictly verified. Whitespace in most cases is ignored, and attribute ordering is not significant. See :meth:`~SimpleTestCase.assertHTMLEqual` for more details. @@ -1865,8 +1870,8 @@ your test suite. .. method:: SimpleTestCase.assertJSONNotEqual(raw, expected_data, msg=None) - Asserts that the JSON fragments ``raw`` and ``expected_data`` are *not* equal. - See :meth:`~SimpleTestCase.assertJSONEqual` for further details. + Asserts that the JSON fragments ``raw`` and ``expected_data`` are *not* + equal. See :meth:`~SimpleTestCase.assertJSONEqual` for further details. Output in case of error can be customized with the ``msg`` argument. @@ -1880,10 +1885,10 @@ your test suite. By default, the comparison is also ordering dependent. If ``qs`` doesn't provide an implicit ordering, you can set the ``ordered`` parameter to - ``False``, which turns the comparison into a ``collections.Counter`` comparison. - If the order is undefined (if the given ``qs`` isn't ordered and the - comparison is against more than one ordered value), a ``ValueError`` is - raised. + ``False``, which turns the comparison into a ``collections.Counter`` + comparison. If the order is undefined (if the given ``qs`` isn't ordered + and the comparison is against more than one ordered value), a + ``ValueError`` is raised. Output in case of error can be customized with the ``msg`` argument. @@ -2018,9 +2023,9 @@ creates. .. warning:: If you are using test decorators, they must be async-compatible to ensure - they work correctly. Django's built-in decorators will behave correctly, but - third-party ones may appear to not execute (they will "wrap" the wrong part - of the execution flow and not your test). + they work correctly. Django's built-in decorators will behave correctly, + but third-party ones may appear to not execute (they will "wrap" the wrong + part of the execution flow and not your test). If you need to use these decorators, then you should decorate your test methods with :func:`~asgiref.sync.async_to_sync` *inside* of them instead::