1
0
mirror of https://github.com/django/django.git synced 2025-10-24 14:16:09 +00:00

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.
This commit is contained in:
David Smith
2025-07-25 10:24:17 +01:00
committed by nessita
parent 4286a23df6
commit f81e6e3a53
230 changed files with 3250 additions and 2914 deletions

View File

@@ -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:

View File

@@ -189,11 +189,13 @@ Model fields
* **fields.E121**: ``max_length`` must be a positive integer.
* **fields.W122**: ``max_length`` is ignored when used with
``<integer field type>``.
* **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
``<model>``.
* **fields.E338**: The intermediary model ``<through model>`` has no field
``<field name>``.
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to ``<model>``.
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to
``<model>``.
* **fields.E340**: The field's intermediary table ``<table name>`` clashes with
the table name of ``<model>``/``<model>.<field name>``.
* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.
@@ -382,7 +385,8 @@ Models
* **models.E019**: Autogenerated column name too long for M2M field
``<M2M field>``. Maximum length is ``<maximum length>`` for database
``<alias>``.
* **models.E020**: The ``<model>.check()`` class method is currently overridden.
* **models.E020**: The ``<model>.check()`` class method is currently
overridden.
* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used
together.
* **models.E022**: ``<function>`` 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**: ``<handler>`` was connected to the ``<signal>`` signal with
a lazy reference to the sender ``<app label>.<model>``, but app ``<app label>``
isn't installed or doesn't provide model ``<model>``.
a lazy reference to the sender ``<app label>.<model>``, but app
``<app label>`` isn't installed or doesn't provide model ``<model>``.
Templates
---------
@@ -871,8 +879,8 @@ The following checks are performed on the default
unique.
* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin
permission for model ``<model>``.
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for model
``<model>``.
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for
model ``<model>``.
* **auth.E007**: The :attr:`verbose_name
<django.db.models.Options.verbose_name>` of model ``<model>`` must be at most
244 characters for its builtin permission names

View File

@@ -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)

View File

@@ -222,9 +222,9 @@ views for displaying drilldown pages for date-based data.
context will be:
* ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`
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.

View File

@@ -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)

View File

@@ -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:

View File

@@ -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

View File

@@ -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

View File

@@ -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
<disabling-admin-actions>` -- by passing a second argument to
a name -- good if you later want to programmatically :ref:`remove the
action <disabling-admin-actions>` -- 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 <adminsite-actions>` you can
call :meth:`AdminSite.disable_action`.
If you need to disable a :ref:`site-wide action <adminsite-actions>` 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::

View File

@@ -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 ``<fieldset>`` 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
</ref/applications/>` 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 </ref/applications/>` 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
--------------------

View File

@@ -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 ``"<app label>.<permission codename>"``. (see
documentation on :ref:`permissions <topic-authorization>`). If the user is
inactive, this method will always return ``False``. For an active
documentation on :ref:`permissions <topic-authorization>`). 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
<auth-custom-user>`.
See :ref:`Creating users <topics-auth-creating-users>` for example usage.
See :ref:`Creating users <topics-auth-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

View File

@@ -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<topics-serialization-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<topics-serialization-natural-keys>` and
:option:`dumpdata --natural-foreign` for more information.
This will enable an API similar to the one used for a normal

View File

@@ -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

View File

@@ -68,7 +68,8 @@ of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.
.. 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

View File

@@ -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 <gis-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 <gis-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 <spatial-lookup-compatibility>`. 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 <geography-type>` 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 <tests/gis_tests/distapp/models.py>` ) on a

View File

@@ -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
</ref/contrib/syndication>` for details on general usage.
.. _W3C Geo: https://www.w3.org/2003/01/geo/

View File

@@ -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/

View File

@@ -29,7 +29,7 @@ Measurements
.. class:: Area(expression, **extra)
*Availability*: MariaDB, `MySQL
<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-area>`_,
<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-area>`__,
Oracle, `PostGIS <https://postgis.net/docs/ST_Area.html>`__, SpatiaLite
Accepts a single geographic field or expression and returns the area of the
@@ -48,8 +48,8 @@ geographic SRSes.
`PostGIS <https://postgis.net/docs/ST_Distance.html>`__, 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 <https://postgis.net/docs/geometry_distance_knn.html>`__
*Availability*: `PostGIS
<https://postgis.net/docs/geometry_distance_knn.html>`__
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 <https://postgis.net/docs/ST_Perimeter.html>`__,
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 <https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__,
`Oracle <https://docs.oracle.com/en/database/oracle/oracle-database/21/spatl/
*Availability*: `PostGIS
<https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__, `Oracle
<https://docs.oracle.com/en/database/oracle/oracle-database/21/spatl/
SDO_GEOM-reference.html#GUID-82A61626-BB64-4793-B53D-A0DBEC91831A>`_,
SpatiaLite 5.1+
@@ -205,8 +207,8 @@ representing the bounding box of the geometry.
*Availability*: `PostGIS <https://postgis.net/docs/ST_LineLocatePoint.html>`__,
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 <https://postgis.net/docs/ST_PointOnSurface.html>`__,
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 <https://postgis.net/docs/ST_Scale.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_Scale.html>`__,
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 <https://postgis.net/docs/ST_AsGML.html>`__,
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 <https://postgis.net/docs/ST_AsKML.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsKML.html>`__,
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 <https://postgis.net/docs/ST_AsSVG.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsSVG.html>`__,
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.
<https://dev.mysql.com/doc/refman/en/gis-linestring-property-functions.html#function_st-numpoints>`__,
`PostGIS <https://postgis.net/docs/ST_NPoints.html>`__, 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.

View File

@@ -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

View File

@@ -27,7 +27,8 @@ converted to a geometry where necessary using the `ST_Polygon
<https://postgis.net/docs/RT_ST_Polygon.html>`_ function. See also the
:ref:`introduction to raster lookups <spatial-lookup-raster>`.
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 <https://postgis.net/docs/ST_Geometry_Contain.html>`__,
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Contain.html>`__, 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 <https://postgis.net/docs/ST_Geometry_Contained.html>`__,
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Contained.html>`__, 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 <https://postgis.net/docs/ST_ContainsProperly.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_ContainsProperly.html>`__, 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 <https://postgis.net/docs/ST_Relate.html>`__,
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 <https://postgis.net/docs/ST_Geometry_Overleft.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overleft.html>`__, 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 <https://postgis.net/docs/ST_Geometry_Overright.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overright.html>`__, 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 <https://postgis.net/docs/ST_Geometry_Overabove.html>`__,
PGRaster (Conversion)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overabove.html>`__, 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 <https://postgis.net/docs/ST_Geometry_Overbelow.html>`__,
PGRaster (Conversion)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overbelow.html>`__, 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 <https://postgis.net/docs/ST_Collect.html>`__,
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 <https://postgis.net/docs/ST_3DExtent.html>`__
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:

View File

@@ -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) <GEOSGeometry.within>` returns
``True``.
Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>`
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) <GEOSGeometry>`.
@@ -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)

View File

@@ -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 <geos-exceptions-in-logfile>`.
See also :ref:`My logs are filled with GEOS-related errors
<geos-exceptions-in-logfile>`.
.. _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

View File

@@ -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/

View File

@@ -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

View File

@@ -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 <faq-see-raw-sql-queries>`
*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 <faq-see-raw-sql-queries>` *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

View File

@@ -206,6 +206,7 @@ Measurement API
Alias for :class:`Area` class.
.. rubric:: Footnotes
.. [#] `Robert Coup <https://koordinates.com/>`_ is the initial author of the measure objects,
and was inspired by Brian Beck's work in `geopy <https://github.com/geopy/geopy/>`_
and Geoff Biggs' PhD work on dimensioned units for robotics.
.. [#] `Robert Coup <https://koordinates.com/>`_ is the initial author of the
measure objects, and was inspired by Brian Beck's work in `geopy
<https://github.com/geopy/geopy/>`_ and Geoff Biggs' PhD work on
dimensioned units for robotics.

View File

@@ -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
<https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`_.
<https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`__.
.. rubric:: Footnotes
.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.

View File

@@ -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 <serialization-formats-json>`
instead.
outputted data, use the plain :ref:`json serializer
<serialization-formats-json>` 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.

View File

@@ -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

View File

@@ -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

View File

@@ -6,9 +6,9 @@ Django aims to follow Python's :ref:`"batteries included" philosophy
<tut-batteries-included>`. 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``

View File

@@ -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`_

View File

@@ -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 <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))

View File

@@ -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.

View File

@@ -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
<https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.
``SearchVectorField``

View File

@@ -16,7 +16,8 @@ To install the redirects app, follow these steps:
#. Ensure that the ``django.contrib.sites`` framework
:ref:`is installed <enabling-the-sites-framework>`.
#. 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 <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 </topics/db/models>`,
which lives in :source:`django/contrib/redirects/models.py`. You can access
redirect objects via the :doc:`Django database API </topics/db/queries>`.
For example:
Redirects are represented by a standard
:doc:`Django model </topics/db/models>`, which lives in
:source:`django/contrib/redirects/models.py`. You can access redirect
objects via the :doc:`Django database API </topics/db/queries>`. For
example:
.. code-block:: pycon

View File

@@ -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.

View File

@@ -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

View File

@@ -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 <staticfiles-storages>` 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 <staticfiles-storages>` 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

View File

@@ -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 ``<item>`` has a ``<title>``,
``<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):

View File

@@ -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

View File

@@ -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
=========

View File

@@ -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:

View File

@@ -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::

View File

@@ -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

View File

@@ -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)

View File

@@ -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

View File

@@ -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)")

View File

@@ -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``
========================

View File

@@ -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.

View File

@@ -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

View File

@@ -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``.

View File

@@ -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:

View File

@@ -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

View File

@@ -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>`.

View File

@@ -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

View File

@@ -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:

View File

@@ -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.

View File

@@ -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:

View File

@@ -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:

View File

@@ -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

View File

@@ -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

View File

@@ -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
=============================

View File

@@ -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::

View File

@@ -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

View File

@@ -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.

View File

@@ -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

View File

@@ -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:

View File

@@ -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

View File

@@ -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:

View File

@@ -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
-----------------------------------------

View File

@@ -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).

View File

@@ -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

View File

@@ -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``

View File

@@ -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``.

View File

@@ -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``
-----------------------------------