Fixed #36329 -- Removed non-code custom link text when cross-referencing Python objects.

Thanks Bruno Alla, Sarah Boyce, and Jacob Walls for reviews.

Co-authored-by: Sarah Boyce <42296566+sarahboyce@users.noreply.github.com>
This commit is contained in:
Clifford Gama 2025-10-29 17:32:12 +02:00 committed by GitHub
parent 1aa69a7491
commit 01f8460653
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 168 additions and 171 deletions

View file

@ -25,10 +25,10 @@ needed.
For a development environment -- if you just want to experiment with Django -- For a development environment -- if you just want to experiment with Django --
you don't need to have a separate web server installed or database server. you don't need to have a separate web server installed or database server.
Django comes with its own :djadmin:`lightweight development server<runserver>`. Django comes with its own lightweight development server
For a production environment, Django follows the WSGI spec, :pep:`3333`, which (:djadmin:`runserver`). For a production environment, Django follows the WSGI
means it can run on a variety of web servers. See :doc:`Deploying Django spec, :pep:`3333`, which means it can run on a variety of web servers. See
</howto/deployment/index>` for more information. :doc:`/howto/deployment/index` for more information.
Django runs `SQLite`_ by default, which is included in Python installations. Django runs `SQLite`_ by default, which is included in Python installations.
For a production environment, we recommend PostgreSQL_; but we also officially For a production environment, we recommend PostgreSQL_; but we also officially

View file

@ -195,7 +195,7 @@ filtered out of error reports in a production environment (that is, where
.. function:: sensitive_post_parameters(*parameters) .. function:: sensitive_post_parameters(*parameters)
If one of your views receives an :class:`~django.http.HttpRequest` object If one of your views receives an :class:`~django.http.HttpRequest` object
with :attr:`POST parameters<django.http.HttpRequest.POST>` susceptible to with :attr:`~django.http.HttpRequest.POST` parameters susceptible to
contain sensitive information, you may prevent the values of those contain sensitive information, you may prevent the values of those
parameters from being included in the error reports using the parameters from being included in the error reports using the
``sensitive_post_parameters`` decorator:: ``sensitive_post_parameters`` decorator::

View file

@ -186,9 +186,9 @@ root of the project.
Configure a formatter Configure a formatter
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
By default, the final log output contains the message part of each :class:`log By default, the final log output contains the message part of each
record <logging.LogRecord>`. Use a formatter if you want to include additional :class:`~logging.LogRecord` object. Use a formatter if you want to include
data. First name and define your formatters - this example defines additional data. First name and define your formatters - this example defines
formatters named ``verbose`` and ``simple``: formatters named ``verbose`` and ``simple``:
.. code-block:: python .. code-block:: python

View file

@ -284,13 +284,16 @@ the scenes, limiting the number of search fields to a reasonable number will
make it easier for your database to do the search. 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 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 default is to display 100 items per page.
<django.contrib.admin.ModelAdmin.list_per_page>`, :attr:`search boxes
<django.contrib.admin.ModelAdmin.search_fields>`, :attr:`filters .. seealso::
<django.contrib.admin.ModelAdmin.list_filter>`, :attr:`date-hierarchies
<django.contrib.admin.ModelAdmin.date_hierarchy>`, and The following :class:`~django.contrib.admin.ModelAdmin` options allow
:attr:`column-header-ordering <django.contrib.admin.ModelAdmin.list_display>` further customization of change lists:
all work together like you think they should. :attr:`~django.contrib.admin.ModelAdmin.list_per_page`,
:attr:`~django.contrib.admin.ModelAdmin.search_fields`,
:attr:`~django.contrib.admin.ModelAdmin.date_hierarchy`, and
:attr:`~django.contrib.admin.ModelAdmin.list_display`.
Customize the admin look and feel Customize the admin look and feel
================================= =================================

View file

@ -646,10 +646,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
.. method:: user_can_authenticate() .. method:: user_can_authenticate()
Returns whether the user is allowed to authenticate. To match the Returns whether the user is allowed to authenticate. To match the
behavior of :class:`~django.contrib.auth.forms.AuthenticationForm` behavior of :meth:`.AuthenticationForm.confirm_login_allowed`, this
which :meth:`prohibits inactive users from logging in method returns ``False`` for users with :attr:`is_active=False
<django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed>`,
this method returns ``False`` for users with :attr:`is_active=False
<django.contrib.auth.models.User.is_active>`. Custom user models that <django.contrib.auth.models.User.is_active>`. Custom user models that
don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active` don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`
field are allowed. field are allowed.

View file

@ -110,8 +110,7 @@ model it represents, or to retrieve objects from that model:
Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
model the :class:`~django.contrib.contenttypes.models.ContentType` model the :class:`~django.contrib.contenttypes.models.ContentType`
represents, and does represents, and does a :meth:`~django.db.models.query.QuerySet.get` lookup
:meth:`a get() lookup <django.db.models.query.QuerySet.get>`
on that model, returning the corresponding object. The ``using`` argument on that model, returning the corresponding object. The ``using`` argument
can be used to specify a different database than the default one. can be used to specify a different database than the default one.
@ -160,11 +159,10 @@ two extremely important use cases:
to get access to those model classes. to get access to those model classes.
Several of Django's bundled applications make use of the latter technique. Several of Django's bundled applications make use of the latter technique.
For example, For example, :ref:`the permissions system <topic-authorization>` in Django's
:class:`the permissions system <django.contrib.auth.models.Permission>` in authentication framework uses a :class:`~django.contrib.auth.models.Permission`
Django's authentication framework uses a model with a foreign key to
:class:`~django.contrib.auth.models.Permission` model with a foreign :class:`~django.contrib.contenttypes.models.ContentType`; this lets
key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
:class:`~django.contrib.auth.models.Permission` represent concepts like :class:`~django.contrib.auth.models.Permission` represent concepts like
"can add blog entry" or "can delete news story". "can add blog entry" or "can delete news story".

View file

@ -338,9 +338,9 @@ than comparing the size of an integer, for example.
In the event that all the fields you're querying on are contained within one In the event that all the fields you're querying on are contained within one
particular model, you can create a functional particular model, you can create a functional
:class:`GIN <django.contrib.postgres.indexes.GinIndex>` or :class:`~django.contrib.postgres.indexes.GinIndex` or
:class:`GiST <django.contrib.postgres.indexes.GistIndex>` index which matches :class:`~django.contrib.postgres.indexes.GistIndex` which matches the search
the search vector you wish to use. For example:: vector you wish to use. For example::
GinIndex( GinIndex(
SearchVector("body_text", "headline", config="english"), SearchVector("body_text", "headline", config="english"),

View file

@ -1337,8 +1337,8 @@ Specifies which directories in the app template should be excluded, in addition
to ``.git`` and ``__pycache__``. If this option is not provided, directories to ``.git`` and ``__pycache__``. If this option is not provided, directories
named ``__pycache__`` or starting with ``.`` will be excluded. named ``__pycache__`` or starting with ``.`` will be excluded.
The :class:`template context <django.template.Context>` used for all matching The template context (see :class:`~django.template.Context`) used for all
files is: matching files is:
- Any option passed to the ``startapp`` command (among the command's supported - Any option passed to the ``startapp`` command (among the command's supported
options) options)
@ -1435,7 +1435,7 @@ Specifies which directories in the project template should be excluded, in
addition to ``.git`` and ``__pycache__``. If this option is not provided, addition to ``.git`` and ``__pycache__``. If this option is not provided,
directories named ``__pycache__`` or starting with ``.`` will be excluded. directories named ``__pycache__`` or starting with ``.`` will be excluded.
The :class:`template context <django.template.Context>` used is: The template context (see :class:`~django.template.Context`) used is:
- Any option passed to the ``startproject`` command (among the command's - Any option passed to the ``startproject`` command (among the command's
supported options) supported options)

View file

@ -111,6 +111,8 @@ Built-in Expressions
``django.db.models.aggregates``, but for convenience they're available and ``django.db.models.aggregates``, but for convenience they're available and
usually imported from :mod:`django.db.models`. usually imported from :mod:`django.db.models`.
.. _f-expressions:
``F()`` expressions ``F()`` expressions
------------------- -------------------
@ -493,7 +495,7 @@ should be invoked for each distinct value of ``expressions`` (or set of
values, for multiple ``expressions``). The argument is only supported on values, for multiple ``expressions``). The argument is only supported on
aggregates that have :attr:`~Aggregate.allow_distinct` set to ``True``. aggregates that have :attr:`~Aggregate.allow_distinct` set to ``True``.
The ``filter`` argument takes a :class:`Q object <django.db.models.Q>` that's The ``filter`` argument takes a :ref:`Q object <q-objects>` that's
used to filter the rows that are aggregated. See :ref:`conditional-aggregation` used to filter the rows that are aggregated. See :ref:`conditional-aggregation`
and :ref:`filtering-on-annotations` for example usage. and :ref:`filtering-on-annotations` for example usage.

View file

@ -561,8 +561,8 @@ The primary key field is read-only. If you change the value of the primary
key on an existing object and then save it, a new object will be created key on an existing object and then save it, a new object will be created
alongside the old one. alongside the old one.
The primary key field is set to ``None`` when The primary key field is set to ``None`` when calling a model instances
:meth:`deleting <django.db.models.Model.delete>` an object. :meth:`~django.db.models.Model.delete` method.
``unique`` ``unique``
---------- ----------
@ -2436,9 +2436,9 @@ Field API reference
Python types to database (:meth:`get_prep_value`) and vice-versa Python types to database (:meth:`get_prep_value`) and vice-versa
(:meth:`from_db_value`). (:meth:`from_db_value`).
A field is thus a fundamental piece in different Django APIs, notably, A field is thus a fundamental piece in different Django APIs, notably the
:class:`models <django.db.models.Model>` and :class:`querysets :class:`~django.db.models.Model` and the
<django.db.models.query.QuerySet>`. :class:`~django.db.models.query.QuerySet` APIs.
In models, a field is instantiated as a class attribute and represents a In models, a field is instantiated as a class attribute and represents a
particular table column, see :doc:`/topics/db/models`. It has attributes particular table column, see :doc:`/topics/db/models`. It has attributes
@ -2598,7 +2598,7 @@ Field API reference
See :ref:`converting-model-field-to-serialization` for usage. See :ref:`converting-model-field-to-serialization` for usage.
When using :class:`model forms <django.forms.ModelForm>`, the ``Field`` When using :doc:`model forms </topics/forms/modelforms>`, the ``Field``
needs to know which form field it should be represented by: needs to know which form field it should be represented by:
.. method:: formfield(form_class=None, choices_form_class=None, **kwargs) .. method:: formfield(form_class=None, choices_form_class=None, **kwargs)

View file

@ -211,10 +211,10 @@ filtering.
See the PostgreSQL documentation for more details about `covering indexes`_. See the PostgreSQL documentation for more details about `covering indexes`_.
.. admonition:: Restrictions on PostgreSQL .. admonition:: PostgreSQL-specific indexes
PostgreSQL supports covering B-Tree, :class:`GiST indexes In addition to B-Tree indexes (via :class:`Index`), PostgreSQL also
<django.contrib.postgres.indexes.GistIndex>`, and :class:`SP-GiST indexes supports :class:`~django.contrib.postgres.indexes.GistIndex` and
<django.contrib.postgres.indexes.SpGistIndex>`. :class:`~django.contrib.postgres.indexes.SpGistIndex` indexes.
.. _covering indexes: https://www.postgresql.org/docs/current/indexes-index-only-scans.html .. _covering indexes: https://www.postgresql.org/docs/current/indexes-index-only-scans.html

View file

@ -632,10 +632,9 @@ the value of 11 will be written back to the database.
The process can be made robust, :ref:`avoiding a race condition The process can be made robust, :ref:`avoiding a race condition
<avoiding-race-conditions-using-f>`, as well as slightly faster by expressing <avoiding-race-conditions-using-f>`, as well as slightly faster by expressing
the update relative to the original field value, rather than as an explicit the update relative to the original field value, rather than as an explicit
assignment of a new value. Django provides :class:`F expressions assignment of a new value. Django provides :ref:`f-expressions` for performing
<django.db.models.F>` for performing this kind of relative update. Using this kind of relative update. Using :ref:`f-expressions`, the previous example
:class:`F expressions <django.db.models.F>`, the previous example is expressed is expressed as:
as:
.. code-block:: pycon .. code-block:: pycon
@ -644,9 +643,8 @@ as:
>>> product.number_sold = F("number_sold") + 1 >>> product.number_sold = F("number_sold") + 1
>>> product.save() >>> product.save()
For more details, see the documentation on :class:`F expressions For more details, see the documentation on :ref:`f-expressions` and their
<django.db.models.F>` and their :ref:`use in update queries :ref:`use in update queries <topics-db-queries-update>`.
<topics-db-queries-update>`.
.. _ref-models-update-fields: .. _ref-models-update-fields:

View file

@ -38,8 +38,8 @@ Retrieving a single field instance of a model by name
user, the :attr:`~.ForeignKey.related_name` set by the user, or the name user, the :attr:`~.ForeignKey.related_name` set by the user, or the name
automatically generated by Django. automatically generated by Django.
:attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved Hidden fields, fields with :attr:`hidden=True
by name. <django.db.models.Field.hidden>`, cannot be retrieved by name.
If a field with the given name is not found a If a field with the given name is not found a
:class:`~django.core.exceptions.FieldDoesNotExist` exception will be :class:`~django.core.exceptions.FieldDoesNotExist` exception will be
@ -80,7 +80,7 @@ Retrieving all field instances of a model
``include_hidden`` ``include_hidden``
``False`` by default. If set to ``True``, ``get_fields()`` will include ``False`` by default. If set to ``True``, ``get_fields()`` will include
:attr:`hidden fields <django.db.models.Field.hidden>`. fields with :attr:`hidden=True <django.db.models.Field.hidden>`.
.. code-block:: pycon .. code-block:: pycon
@ -127,9 +127,8 @@ Retrieving fields composing the primary key of a model
Returns a list of the 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 When a :class:`~django.db.models.CompositePrimaryKey` is defined on a model
<django.db.models.CompositePrimaryKey>` is defined on a model it will it will contain all the fields referenced by it.
contain all the :class:`fields <django.db.models.Field>` referenced by it.
.. code-block:: python .. code-block:: python
@ -149,8 +148,10 @@ Retrieving fields composing the primary key of a model
<django.db.models.fields.IntegerField: id> <django.db.models.fields.IntegerField: id>
] ]
Otherwise it will contain the single field declared as the Otherwise it will contain the single field declared as the primary key of
:attr:`primary key <django.db.models.Field.primary_key>` of the model. the model, either explicitly with :attr:`primary_key=True
<django.db.models.Field.primary_key>` or implicitly as the :ref:`automatic
primary key <automatic-primary-key-fields>`.
.. code-block:: pycon .. code-block:: pycon

View file

@ -209,7 +209,7 @@ The lookup parameters (``**kwargs``) should be in the format described in
underlying SQL statement. underlying SQL statement.
If you need to execute more complex queries (for example, queries with ``OR`` 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``). statements), you can use :ref:`q-objects` (``*args``).
``exclude()`` ``exclude()``
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -259,8 +259,8 @@ statements), you can use :class:`Q objects <django.db.models.Q>` (``*args``).
.. method:: annotate(*args, **kwargs) .. method:: annotate(*args, **kwargs)
Annotates each object in the ``QuerySet`` with the provided list of :doc:`query Annotates each object in the ``QuerySet`` with the provided list of :doc:`query
expressions </ref/models/expressions>` or :class:`~django.db.models.Q` objects. expressions </ref/models/expressions>` or :ref:`q-objects`. Each object can be
Each object can be annotated with: annotated with:
* a simple value, via ``Value()``; * a simple value, via ``Value()``;
* a reference to a field on the model (or any related models), via ``F()``; * a reference to a field on the model (or any related models), via ``F()``;
@ -1276,9 +1276,9 @@ database.
:meth:`~django.db.models.fields.related.RelatedManager.create`, :meth:`~django.db.models.fields.related.RelatedManager.create`,
:meth:`~django.db.models.fields.related.RelatedManager.remove`, :meth:`~django.db.models.fields.related.RelatedManager.remove`,
:meth:`~django.db.models.fields.related.RelatedManager.clear` or :meth:`~django.db.models.fields.related.RelatedManager.clear` or
:meth:`~django.db.models.fields.related.RelatedManager.set`, on :meth:`~django.db.models.fields.related.RelatedManager.set`, on a
:class:`related managers<django.db.models.fields.related.RelatedManager>`, :class:`~django.db.models.fields.related.RelatedManager`, any prefetched
any prefetched cache for the relation will be cleared. cache for the relation will be cleared.
You can also use the normal join syntax to do related fields of related You can also use the normal join syntax to do related fields of related
fields. Suppose we have an additional model to the example above:: fields. Suppose we have an additional model to the example above::
@ -1433,8 +1433,8 @@ where prefetching with a custom ``QuerySet`` is useful:
* You want to prefetch only a subset of the related objects. * You want to prefetch only a subset of the related objects.
* You want to use performance optimization techniques like * You want to use performance optimization techniques like deferring fields,
:meth:`deferred fields <defer()>`: for example, via :meth:`defer` or :meth:`only`:
.. code-block:: pycon .. code-block:: pycon
@ -1797,11 +1797,10 @@ will always be fetched into the resulting queryset.
normalize your models and put the non-loaded data into a separate model normalize your models and put the non-loaded data into a separate model
(and database table). If the columns *must* stay in the one table for some (and database table). If the columns *must* stay in the one table for some
reason, create a model with ``Meta.managed = False`` (see the reason, create a model with ``Meta.managed = False`` (see the
:attr:`managed attribute <django.db.models.Options.managed>` documentation) :attr:`~django.db.models.Options.managed` documentation) containing just
containing just the fields you normally need to load and use that where you the fields you normally need to load and use that where you might otherwise
might otherwise call ``defer()``. This makes your code more explicit to the call ``defer()``. This makes your code more explicit to the reader, is
reader, is slightly faster and consumes a little less memory in the Python slightly faster and consumes a little less memory in the Python process.
process.
For example, both of these models use the same underlying database table:: For example, both of these models use the same underlying database table::
@ -2266,9 +2265,9 @@ found, ``get_or_create()`` returns a tuple of that object and ``False``.
inserted. inserted.
You can specify more complex conditions for the retrieved object by chaining You can specify more complex conditions for the retrieved object by chaining
``get_or_create()`` with ``filter()`` and using :class:`Q objects ``get_or_create()`` with ``filter()`` and using :ref:`q-objects`. For example,
<django.db.models.Q>`. For example, to retrieve Robert or Bob Marley if either to retrieve Robert or Bob Marley if either exists, and create the latter
exists, and create the latter otherwise:: otherwise::
from django.db.models import Q from django.db.models import Q
@ -3963,8 +3962,8 @@ An optional argument that represents the :doc:`model field
``filter`` ``filter``
~~~~~~~~~~ ~~~~~~~~~~
An optional :class:`Q object <django.db.models.Q>` that's used to filter the An optional :ref:`Q object <q-objects>` that's used to filter the rows that
rows that are aggregated. are aggregated.
See :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for See :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for
example usage. example usage.
@ -4178,6 +4177,8 @@ Query-related tools
This section provides reference material for query-related tools not documented This section provides reference material for query-related tools not documented
elsewhere. elsewhere.
.. _q-objects:
``Q()`` objects ``Q()`` objects
--------------- ---------------
@ -4282,7 +4283,7 @@ overridden by using a custom queryset in a related lookup.
.. attribute:: FilteredRelation.condition .. attribute:: FilteredRelation.condition
A :class:`~django.db.models.Q` object to control the filtering. A :ref:`Q object <q-objects>` to control the filtering.
``FilteredRelation`` is used with :meth:`~.QuerySet.annotate` to create an ``FilteredRelation`` is used with :meth:`~.QuerySet.annotate` to create an
``ON`` clause when a ``JOIN`` is performed. It doesn't act on the default ``ON`` clause when a ``JOIN`` is performed. It doesn't act on the default

View file

@ -463,9 +463,9 @@ A list of trusted origins for unsafe requests (e.g. ``POST``).
For requests that include the ``Origin`` header, Django's CSRF protection For requests that include the ``Origin`` header, Django's CSRF protection
requires that header match the origin present in the ``Host`` header. requires that header match the origin present in the ``Host`` header.
For a :meth:`secure <django.http.HttpRequest.is_secure>` unsafe For a secure (determined by :meth:`~django.http.HttpRequest.is_secure`) unsafe
request that doesn't include the ``Origin`` header, the request must have a request that doesn't include the ``Origin`` header, the request must include a
``Referer`` header that matches the origin present in the ``Host`` header. ``Referer`` header that matches the origin in the ``Host`` header.
These checks prevent, for example, a ``POST`` request from These checks prevent, for example, a ``POST`` request from
``subdomain.example.com`` from succeeding against ``api.example.com``. If you ``subdomain.example.com`` from succeeding against ``api.example.com``. If you
@ -1778,9 +1778,10 @@ Default: ``[]`` (Empty list)
List of compiled regular expression objects describing URLs that should be List of compiled regular expression objects describing URLs that should be
ignored when reporting HTTP 404 errors via email (see ignored when reporting HTTP 404 errors via email (see
:doc:`/howto/error-reporting`). Regular expressions are matched against :doc:`/howto/error-reporting`). Regular expressions are matched against
:meth:`request's full paths <django.http.HttpRequest.get_full_path>` (including request's full paths, as returned by
query string, if any). Use this if your site does not provide a commonly :meth:`~django.http.HttpRequest.get_full_path` (including any query strings).
requested file such as ``favicon.ico`` or ``robots.txt``. Use this if your site does not provide a commonly requested file such as
``favicon.ico`` or ``robots.txt``.
This is only used if This is only used if
:class:`~django.middleware.common.BrokenLinkEmailsMiddleware` is enabled (see :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` is enabled (see

View file

@ -37,8 +37,8 @@ The primary attributes of the default user are:
* :attr:`~django.contrib.auth.models.User.first_name` * :attr:`~django.contrib.auth.models.User.first_name`
* :attr:`~django.contrib.auth.models.User.last_name` * :attr:`~django.contrib.auth.models.User.last_name`
See the :class:`full API documentation <django.contrib.auth.models.User>` for See the :class:`~django.contrib.auth.models.User` API documentation for a
full reference, the documentation that follows is more task oriented. complete reference. The documentation that follows is more task-oriented.
.. _topics-auth-creating-users: .. _topics-auth-creating-users:
@ -368,7 +368,7 @@ Authentication in web requests
============================== ==============================
Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the
authentication system into :class:`request objects <django.http.HttpRequest>`. authentication system into :class:`~django.http.HttpRequest` objects.
These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute
and a :meth:`request.auser <django.http.HttpRequest.auser>` async method and a :meth:`request.auser <django.http.HttpRequest.auser>` async method
@ -1619,9 +1619,9 @@ provides several built-in forms located in :mod:`django.contrib.auth.forms`:
.. class:: AdminPasswordChangeForm .. class:: AdminPasswordChangeForm
A form used in the admin interface to change a user's password, including A form used in the admin interface to change a user's password, including
the ability to set an :meth:`unusable password the ability to set an unusable password (via
<django.contrib.auth.models.User.set_unusable_password>`, which blocks the :meth:`~django.contrib.auth.models.User.set_unusable_password`), which
user from logging in with password-based authentication. blocks the user from logging in with password-based authentication.
Takes the ``user`` as the first positional argument. Takes the ``user`` as the first positional argument.

View file

@ -156,12 +156,13 @@ it.
To make a :class:`~django.template.response.TemplateResponse`, To make a :class:`~django.template.response.TemplateResponse`,
:class:`ListView` then uses :class:`ListView` then uses
:class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`; as :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.
with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin` As with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`
above, this overrides ``get_template_names()`` to provide :meth:`a range of above, this overrides
options <django.views.generic.list.MultipleObjectTemplateResponseMixin>`, with :meth:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.get_template_names`
the most commonly-used being ``<app_label>/<model_name>_list.html``, with the to provide a range of options, with the most commonly-used being
``_list`` part again being taken from the ``<app_label>/<model_name>_list.html``, with the ``_list`` part again
being taken from the
:attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix` :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`
attribute. (The date based generic views use suffixes such as ``_archive``, attribute. (The date based generic views use suffixes such as ``_archive``,
``_archive_year`` and so on to use different templates for the various ``_archive_year`` and so on to use different templates for the various

View file

@ -199,8 +199,7 @@ Building composite primary key ready applications
Prior to the introduction of composite primary keys, the single field composing Prior to the introduction of composite primary keys, the single field composing
the primary key of a model could be retrieved by introspecting the the primary key of a model could be retrieved by introspecting the
:attr:`primary key <django.db.models.Field.primary_key>` attribute of its :attr:`~django.db.models.Field.primary_key` attribute of its fields:
fields:
.. code-block:: pycon .. code-block:: pycon
@ -214,10 +213,10 @@ fields:
<django.db.models.fields.AutoField: id> <django.db.models.fields.AutoField: id>
Now that a primary key can be composed of multiple fields the Now that a primary key can be composed of multiple fields the
:attr:`primary key <django.db.models.Field.primary_key>` attribute can no :attr:`~django.db.models.Field.primary_key` attribute can no longer be relied
longer be relied upon to identify members of the primary key as it will be set upon to identify members of the primary key as it will be set to ``False`` to
to ``False`` to maintain the invariant that at most one field per model will maintain the invariant that at most one field per model will have this
have this attribute set to ``True``: attribute set to ``True``:
.. code-block:: pycon .. code-block:: pycon

View file

@ -968,8 +968,8 @@ See :ref:`ref-models-update-fields` for more details.
Note that the :meth:`~Model.delete` method for an object is not Note that the :meth:`~Model.delete` method for an object is not
necessarily called when :ref:`deleting objects in bulk using a necessarily called when :ref:`deleting objects in bulk using a
QuerySet <topics-db-queries-delete>` or as a result of a :attr:`cascading QuerySet <topics-db-queries-delete>` or as a result of a cascading delete
delete <django.db.models.ForeignKey.on_delete>`. To ensure customized (see :attr:`~django.db.models.ForeignKey.on_delete`). To ensure customized
delete logic gets executed, you can use delete logic gets executed, you can use
:data:`~django.db.models.signals.pre_delete` and/or :data:`~django.db.models.signals.pre_delete` and/or
:data:`~django.db.models.signals.post_delete` signals. :data:`~django.db.models.signals.post_delete` signals.

View file

@ -133,8 +133,8 @@ For instance:
* At the most basic level, use :ref:`filter and exclude <queryset-api>` to do * At the most basic level, use :ref:`filter and exclude <queryset-api>` to do
filtering in the database. filtering in the database.
* Use :class:`F expressions <django.db.models.F>` to filter * Use :ref:`f-expressions` to filter based on other fields within the same
based on other fields within the same model. model.
* Use :doc:`annotate to do aggregation in the database * Use :doc:`annotate to do aggregation in the database
</topics/db/aggregation>`. </topics/db/aggregation>`.
@ -396,9 +396,8 @@ number of SQL queries. For example::
Entry.objects.create(headline="This is a test") Entry.objects.create(headline="This is a test")
Entry.objects.create(headline="This is only a test") Entry.objects.create(headline="This is only a test")
Note that there are a number of :meth:`caveats to this method Note that :meth:`~django.db.models.query.QuerySet.bulk_create` has several
<django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate caveats, so ensure it's appropriate for your use case.
for your use case.
Update in bulk Update in bulk
-------------- --------------
@ -427,9 +426,8 @@ The following example::
entries[1].headline = "This is no longer a test" entries[1].headline = "This is no longer a test"
entries[1].save() entries[1].save()
Note that there are a number of :meth:`caveats to this method Note that :meth:`~django.db.models.query.QuerySet.bulk_update` has several
<django.db.models.query.QuerySet.bulk_update>`, so make sure it's appropriate caveats, so ensure it's appropriate for your use case.
for your use case.
Insert in bulk Insert in bulk
-------------- --------------
@ -491,12 +489,12 @@ objects to reduce the number of SQL queries. For example::
...where ``Band`` and ``Artist`` are models with a many-to-many relationship. ...where ``Band`` and ``Artist`` are models with a many-to-many relationship.
When removing different pairs of objects from :class:`ManyToManyFields When removing multiple many-to-many relationships involving several instances
<django.db.models.ManyToManyField>`, use of the related models, use the :meth:`~django.db.models.query.QuerySet.delete`
:meth:`~django.db.models.query.QuerySet.delete` on a method on a filtered queryset of the field's
:class:`~django.db.models.Q` expression with multiple :attr:`~django.db.models.ManyToManyField.through` model. By combining multiple
:attr:`~django.db.models.ManyToManyField.through` model instances to reduce conditions with :ref:`q-objects`, you can delete several relationships in a
the number of SQL queries. For example:: single query. For example::
from django.db.models import Q from django.db.models import Q

View file

@ -541,9 +541,10 @@ is ``'Beatles Blog'``:
This spanning can be as deep as you'd like. This spanning can be as deep as you'd like.
It works backwards, too. While it :attr:`can be customized It works backwards, too. While it can be customized by setting
<.ForeignKey.related_query_name>`, by default you refer to a "reverse" :class:`~django.db.models.ForeignKey.related_query_name`, by default you
relationship in a lookup using the lowercase name of the model. refer to a "reverse" relationship in a lookup using the lowercase name of the
model.
This example retrieves all ``Blog`` objects which have at least one ``Entry`` This example retrieves all ``Blog`` objects which have at least one ``Entry``
whose ``headline`` contains ``'Lennon'``: whose ``headline`` contains ``'Lennon'``:
@ -692,10 +693,10 @@ In the examples given so far, we have constructed filters that compare
the value of a model field with a constant. But what if you want to compare the value of a model field with a constant. But what if you want to compare
the value of a model field with another field on the same model? the value of a model field with another field on the same model?
Django provides :class:`F expressions <django.db.models.F>` to allow such Django provides :ref:`f-expressions` to allow such comparisons. Instances of
comparisons. Instances of ``F()`` act as a reference to a model field within a ``F()`` act as a reference to a model field within a query. These references
query. These references can then be used in query filters to compare the values can then be used in query filters to compare the values of two different fields
of two different fields on the same model instance. on the same model instance.
For example, to find a list of all blog entries that have had more comments For example, to find a list of all blog entries that have had more comments
than pingbacks, we construct an ``F()`` object to reference the pingback count, than pingbacks, we construct an ``F()`` object to reference the pingback count,
@ -1370,12 +1371,11 @@ Complex lookups with ``Q`` objects
Keyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`, 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 etc. -- are "AND"ed together. If you need to execute more complex queries (for
example, queries with ``OR`` statements), you can use example, queries with ``OR`` statements), you can use :ref:`q-objects`.
:class:`Q objects <django.db.models.Q>`.
A :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object A :ref:`Q object <q-objects>` (``django.db.models.Q``) is an object used to
used to encapsulate a collection of keyword arguments. These keyword arguments encapsulate a collection of keyword arguments. These keyword arguments are
are specified as in "Field lookups" above. specified as in "Field lookups" above.
For example, this ``Q`` object encapsulates a single ``LIKE`` query:: For example, this ``Q`` object encapsulates a single ``LIKE`` query::
@ -1659,10 +1659,10 @@ them and call :meth:`~django.db.models.Model.save`::
for item in my_queryset: for item in my_queryset:
item.save() item.save()
Calls to update can also use :class:`F expressions <django.db.models.F>` to Calls to update can also use :ref:`f-expressions` to update one field based on
update one field based on the value of another field in the model. This is the value of another field in the model. This is especially useful for
especially useful for incrementing counters based upon their current value. For incrementing counters based upon their current value. For example, to increment
example, to increment the pingback count for every entry in the blog: the pingback count for every entry in the blog:
.. code-block:: pycon .. code-block:: pycon

View file

@ -50,8 +50,9 @@ following example will create a formset class to display two blank forms:
Formsets can be iterated and indexed, accessing forms in the order they were Formsets can be iterated and indexed, accessing forms in the order they were
created. You can reorder the forms by overriding the default created. You can reorder the forms by overriding the default
:meth:`iteration <object.__iter__>` and :meth:`~object.__iter__` and :meth:`~object.__getitem__` methods if needed.
:meth:`indexing <object.__getitem__>` behavior if needed. (For more information on implementing these methods, see the
:term:`Python documentation on sequences <sequence>`.)
.. _formsets-initial-data: .. _formsets-initial-data:

View file

@ -299,14 +299,14 @@ for more information on the model's ``clean()`` hook.
Considerations regarding model's ``error_messages`` Considerations regarding model's ``error_messages``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error messages defined at the Error messages defined at the form field level (
:attr:`form field <django.forms.Field.error_messages>` level or at the :attr:`django.forms.Field.error_messages`) or at the
:ref:`form Meta <modelforms-overriding-default-fields>` level always take :ref:`form Meta <modelforms-overriding-default-fields>` level always take
precedence over the error messages defined at the precedence over the error messages defined at the model field level
:attr:`model field <django.db.models.Field.error_messages>` level. (:attr:`django.db.models.Field.error_messages`).
Error messages defined on :attr:`model fields Error messages defined on model fields
<django.db.models.Field.error_messages>` are only used when the (:attr:`django.db.models.Field.error_messages`) are only used when the
``ValidationError`` is raised during the :ref:`model validation ``ValidationError`` is raised during the :ref:`model validation
<validating-objects>` step and no corresponding error messages are defined at <validating-objects>` step and no corresponding error messages are defined at
the form level. the form level.

View file

@ -206,7 +206,7 @@ Arguments
the object. the object.
``*args`` ``*args``
:class:`Q objects <django.db.models.Q>`. :ref:`q-objects`.
``**kwargs`` ``**kwargs``
Lookup parameters, which should be in the format accepted by ``get()`` and Lookup parameters, which should be in the format accepted by ``get()`` and
@ -286,7 +286,7 @@ Arguments
list. list.
``*args`` ``*args``
:class:`Q objects <django.db.models.Q>`. :ref:`q-objects`.
``**kwargs`` ``**kwargs``
Lookup parameters, which should be in the format accepted by ``get()`` and Lookup parameters, which should be in the format accepted by ``get()`` and

View file

@ -1043,7 +1043,7 @@ The ``JavaScriptCatalog`` view
.. attribute:: packages .. attribute:: packages
A list of :attr:`application names <django.apps.AppConfig.name>` among A list of application names (:attr:`.AppConfig.name`) among the
installed applications. Those apps should contain a ``locale`` installed applications. Those apps should contain a ``locale``
directory. All those catalogs plus all catalogs found in directory. All those catalogs plus all catalogs found in
:setting:`LOCALE_PATHS` (which are always included) are merged into one :setting:`LOCALE_PATHS` (which are always included) are merged into one

View file

@ -801,26 +801,21 @@ A subclass of :class:`unittest.TestCase` that adds this functionality:
* Some useful assertions like: * Some useful assertions like:
* Checking that a callable :meth:`raises a certain exception =========================================== ======================================
<SimpleTestCase.assertRaisesMessage>`. Assertion What it checks
* Checking that a callable :meth:`triggers a certain warning =========================================== ======================================
<SimpleTestCase.assertWarnsMessage>`. :meth:`~SimpleTestCase.assertRaisesMessage` That a callable raises a certain exception
* Testing form field :meth:`rendering and error treatment :meth:`~SimpleTestCase.assertWarnsMessage` That a callable triggers a certain warning
<SimpleTestCase.assertFieldOutput>`. :meth:`~SimpleTestCase.assertFieldOutput` Form field rendering and error output
* Testing :meth:`HTML responses for the presence/lack of a given fragment :meth:`~SimpleTestCase.assertContains` Presence or absence of HTML fragments
<SimpleTestCase.assertContains>`. :meth:`~SimpleTestCase.assertTemplateUsed` Template usage in a response
* Verifying that a template :meth:`has/hasn't been used to generate a given :meth:`~SimpleTestCase.assertURLEqual` That two URLs are equal
response content <SimpleTestCase.assertTemplateUsed>`. :meth:`~SimpleTestCase.assertRedirects` That an HTTP redirect occurred
* Verifying that two :meth:`URLs <SimpleTestCase.assertURLEqual>` are equal. :meth:`~SimpleTestCase.assertHTMLEqual` HTML fragment equality
* Verifying an HTTP :meth:`redirect <SimpleTestCase.assertRedirects>` is :meth:`~SimpleTestCase.assertInHTML` HTML fragment containment
performed by the app. :meth:`~SimpleTestCase.assertXMLEqual` XML fragment equality or inequality
* Robustly testing two :meth:`HTML fragments :meth:`~SimpleTestCase.assertJSONEqual` JSON fragment equality
<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.
* The ability to run tests with :ref:`modified settings <overriding-settings>`. * The ability to run tests with :ref:`modified settings <overriding-settings>`.
* Using the :attr:`~SimpleTestCase.client` :class:`~django.test.Client`. * Using the :attr:`~SimpleTestCase.client` :class:`~django.test.Client`.
@ -1688,7 +1683,7 @@ your test suite.
.. method:: SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False) .. method:: SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
Asserts that a :class:`response <django.http.HttpResponse>` produced the Asserts that an :class:`~django.http.HttpResponse` produced the
given :attr:`~django.http.HttpResponse.status_code` and that ``text`` given :attr:`~django.http.HttpResponse.status_code` and that ``text``
appears in its :attr:`~django.http.HttpResponse.content`. If ``count`` appears in its :attr:`~django.http.HttpResponse.content`. If ``count``
is provided, ``text`` must occur exactly ``count`` times in the response. is provided, ``text`` must occur exactly ``count`` times in the response.
@ -1701,7 +1696,7 @@ your test suite.
.. method:: SimpleTestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False) .. method:: SimpleTestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
Asserts that a :class:`response <django.http.HttpResponse>` produced the Asserts that an :class:`~django.http.HttpResponse` produced the
given :attr:`~django.http.HttpResponse.status_code` and that ``text`` does given :attr:`~django.http.HttpResponse.status_code` and that ``text`` does
*not* appear in its :attr:`~django.http.HttpResponse.content`. *not* appear in its :attr:`~django.http.HttpResponse.content`.
@ -1716,8 +1711,8 @@ your test suite.
Asserts that the template with the given name was used in rendering the Asserts that the template with the given name was used in rendering the
response. response.
``response`` must be a response instance returned by the ``response`` must be a :class:`~django.test.Response` instance returned by
:class:`test client <django.test.Response>`. the test client.
``template_name`` should be a string such as ``'admin/index.html'``. ``template_name`` should be a string such as ``'admin/index.html'``.
@ -1749,9 +1744,10 @@ your test suite.
.. method:: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True) .. method:: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)
Asserts that the :class:`response <django.http.HttpResponse>` returned a Asserts that the :class:`~django.http.HttpResponse` returned a response
:attr:`~django.http.HttpResponse.status_code` redirect status, redirected with a redirect status (based on its
to ``expected_url`` (including any ``GET`` data), and that the final page :attr:`~django.http.HttpResponse.status_code`), redirected to
``expected_url`` (including any ``GET`` data), and that the final response
was received with ``target_status_code``. was received with ``target_status_code``.
If your request used the ``follow`` argument, the ``expected_url`` and If your request used the ``follow`` argument, the ``expected_url`` and