1
0
mirror of https://github.com/django/django.git synced 2025-08-26 03:39:11 +00:00

Refs #36485 -- Removed double spaces after periods in sentences.

This commit is contained in:
Natalia 2025-08-22 12:36:48 -03:00 committed by nessita
parent 01a460f23e
commit 4286a23df6
80 changed files with 310 additions and 306 deletions

View File

@ -4,7 +4,7 @@ How to authenticate using ``REMOTE_USER``
This document describes how to make use of external authentication sources This document describes how to make use of external authentication sources
(where the web server sets the ``REMOTE_USER`` environment variable) in your (where the web server sets the ``REMOTE_USER`` environment variable) in your
Django applications. This type of authentication solution is typically seen on Django applications. This type of authentication solution is typically seen on
intranet sites, with single sign-on solutions such as IIS and Integrated intranet sites, with single sign-on solutions such as IIS and Integrated
Windows Authentication or Apache and `mod_authnz_ldap`_, `CAS`_, `WebAuth`_, Windows Authentication or Apache and `mod_authnz_ldap`_, `CAS`_, `WebAuth`_,
`mod_auth_sspi`_, etc. `mod_auth_sspi`_, etc.
@ -15,9 +15,9 @@ Windows Authentication or Apache and `mod_authnz_ldap`_, `CAS`_, `WebAuth`_,
.. _mod_auth_sspi: https://sourceforge.net/projects/mod-auth-sspi .. _mod_auth_sspi: https://sourceforge.net/projects/mod-auth-sspi
When the web server takes care of authentication it typically sets the When the web server takes care of authentication it typically sets the
``REMOTE_USER`` environment variable for use in the underlying application. In ``REMOTE_USER`` environment variable for use in the underlying application. In
Django, ``REMOTE_USER`` is made available in the :attr:`request.META Django, ``REMOTE_USER`` is made available in the :attr:`request.META
<django.http.HttpRequest.META>` attribute. Django can be configured to make <django.http.HttpRequest.META>` attribute. Django can be configured to make
use of the ``REMOTE_USER`` value using the ``RemoteUserMiddleware`` use of the ``REMOTE_USER`` value using the ``RemoteUserMiddleware``
or ``PersistentRemoteUserMiddleware``, and or ``PersistentRemoteUserMiddleware``, and
:class:`~django.contrib.auth.backends.RemoteUserBackend` classes found in :class:`~django.contrib.auth.backends.RemoteUserBackend` classes found in
@ -76,7 +76,7 @@ regardless of ``AUTHENTICATION_BACKENDS``.
If your authentication mechanism uses a custom HTTP header and not If your authentication mechanism uses a custom HTTP header and not
``REMOTE_USER``, you can subclass ``RemoteUserMiddleware`` and set the ``REMOTE_USER``, you can subclass ``RemoteUserMiddleware`` and set the
``header`` attribute to the desired ``request.META`` key. For example: ``header`` attribute to the desired ``request.META`` key. For example:
.. code-block:: python .. code-block:: python
:caption: ``mysite/middleware.py`` :caption: ``mysite/middleware.py``

View File

@ -33,7 +33,7 @@ easier to follow, we'll use a consistent example throughout this document:
wrapping a Python object representing the deal of cards in a hand of Bridge_. wrapping a Python object representing the deal of cards in a hand of Bridge_.
Don't worry, you don't have to know how to play Bridge to follow this example. Don't worry, you don't have to know how to play Bridge to follow this example.
You only need to know that 52 cards are dealt out equally to four players, who You only need to know that 52 cards are dealt out equally to four players, who
are traditionally called *north*, *east*, *south* and *west*. Our class looks are traditionally called *north*, *east*, *south* and *west*. Our class looks
something like this:: something like this::
class Hand: class Hand:

View File

@ -264,7 +264,7 @@ Template filter code falls into one of two situations:
reviewing your code. reviewing your code.
Marking a filter ``is_safe`` will coerce the filter's return value to Marking a filter ``is_safe`` will coerce the filter's return value to
a string. If your filter should return a boolean or other non-string a string. If your filter should return a boolean or other non-string
value, marking it ``is_safe`` will probably have unintended value, marking it ``is_safe`` will probably have unintended
consequences (such as converting a boolean False to the string consequences (such as converting a boolean False to the string
'False'). 'False').
@ -841,7 +841,7 @@ When Django compiles a template, it splits the raw template text into *nodes*.
Each node is an instance of ``django.template.Node`` and has a ``render()`` Each node is an instance of ``django.template.Node`` and has a ``render()``
method. A compiled template is a list of ``Node`` objects. When you call method. A compiled template is a list of ``Node`` objects. When you call
``render()`` on a compiled template object, the template calls ``render()`` on ``render()`` on a compiled template object, the template calls ``render()`` on
each ``Node`` in its node list, with the given context. The results are all each ``Node`` in its node list, with the given context. The results are all
concatenated together to form the output of the template. concatenated together to form the output of the template.
Thus, to define a custom template tag, you specify how the raw template tag is Thus, to define a custom template tag, you specify how the raw template tag is
@ -1159,7 +1159,7 @@ Now your tag should begin to look like this::
return FormatTimeNode(date_to_be_formatted, format_string[1:-1]) return FormatTimeNode(date_to_be_formatted, format_string[1:-1])
You also have to change the renderer to retrieve the actual contents of the You also have to change the renderer to retrieve the actual contents of the
``date_updated`` property of the ``blog_entry`` object. This can be ``date_updated`` property of the ``blog_entry`` object. This can be
accomplished by using the ``Variable()`` class in ``django.template``. accomplished by using the ``Variable()`` class in ``django.template``.
To use the ``Variable`` class, instantiate it with the name of the variable to To use the ``Variable`` class, instantiate it with the name of the variable to

View File

@ -3,7 +3,7 @@ How to manage static files (e.g. images, JavaScript, CSS)
========================================================= =========================================================
Websites generally need to serve additional files such as images, JavaScript, Websites generally need to serve additional files such as images, JavaScript,
or CSS. In Django, we refer to these files as "static files". Django provides or CSS. In Django, we refer to these files as "static files". Django provides
:mod:`django.contrib.staticfiles` to help you manage them. :mod:`django.contrib.staticfiles` to help you manage them.
This page describes how you can serve these static files. This page describes how you can serve these static files.

View File

@ -5,7 +5,7 @@ Reporting bugs and requesting features
.. Important:: .. Important::
Please report security issues **only** to Please report security issues **only** to
security@djangoproject.com. This is a private list only open to security@djangoproject.com. This is a private list only open to
long-time, highly trusted Django developers, and its archives are long-time, highly trusted Django developers, and its archives are
not public. For further details, please see :doc:`our security not public. For further details, please see :doc:`our security
policies </internals/security>`. policies </internals/security>`.

View File

@ -1295,7 +1295,7 @@ details on these changes.
</topics/class-based-views/index>`. </topics/class-based-views/index>`.
* The ``django.core.servers.basehttp.AdminMediaHandler`` will be * The ``django.core.servers.basehttp.AdminMediaHandler`` will be
removed. In its place use removed. In its place use
``django.contrib.staticfiles.handlers.StaticFilesHandler``. ``django.contrib.staticfiles.handlers.StaticFilesHandler``.
* The template tags library ``adminmedia`` and the template tag ``{% * The template tags library ``adminmedia`` and the template tag ``{%
@ -1358,7 +1358,7 @@ details on these changes.
See the :ref:`Django 1.2 release notes<deprecated-features-1.2>` for more See the :ref:`Django 1.2 release notes<deprecated-features-1.2>` for more
details on these changes. details on these changes.
* ``CsrfResponseMiddleware`` and ``CsrfMiddleware`` will be removed. Use * ``CsrfResponseMiddleware`` and ``CsrfMiddleware`` will be removed. Use
the ``{% csrf_token %}`` template tag inside forms to enable CSRF the ``{% csrf_token %}`` template tag inside forms to enable CSRF
protection. ``CsrfViewMiddleware`` remains and is enabled by default. protection. ``CsrfViewMiddleware`` remains and is enabled by default.
@ -1386,7 +1386,7 @@ details on these changes.
* The ``Message`` model (in ``django.contrib.auth``), its related * The ``Message`` model (in ``django.contrib.auth``), its related
manager in the ``User`` model (``user.message_set``), and the manager in the ``User`` model (``user.message_set``), and the
associated methods (``user.message_set.create()`` and associated methods (``user.message_set.create()`` and
``user.get_and_delete_messages()``), will be removed. The ``user.get_and_delete_messages()``), will be removed. The
:doc:`messages framework </ref/contrib/messages>` should be used :doc:`messages framework </ref/contrib/messages>` should be used
instead. The related ``messages`` variable returned by the instead. The related ``messages`` variable returned by the
auth context processor will also be removed. Note that this auth context processor will also be removed. Note that this
@ -1398,7 +1398,7 @@ details on these changes.
will no longer be checked and can be removed from custom backends. will no longer be checked and can be removed from custom backends.
* Authentication backends will need to support the ``AnonymousUser`` class * Authentication backends will need to support the ``AnonymousUser`` class
being passed to all methods dealing with permissions. The being passed to all methods dealing with permissions. The
``supports_anonymous_user`` variable will no longer be checked and can be ``supports_anonymous_user`` variable will no longer be checked and can be
removed from custom backends. removed from custom backends.
@ -1425,7 +1425,7 @@ details on these changes.
``django.contrib.syndication`` will be removed. The class-based view ``django.contrib.syndication`` will be removed. The class-based view
``views.Feed`` should be used instead. ``views.Feed`` should be used instead.
* ``django.core.context_processors.auth``. This release will * ``django.core.context_processors.auth``. This release will
remove the old method in favor of the new method in remove the old method in favor of the new method in
``django.contrib.auth.context_processors.auth``. ``django.contrib.auth.context_processors.auth``.
@ -1456,7 +1456,7 @@ details on these changes.
See the :ref:`Django 1.1 release notes<deprecated-features-1.1>` for more See the :ref:`Django 1.1 release notes<deprecated-features-1.1>` for more
details on these changes. details on these changes.
* ``AdminSite.root()``. This method of hooking up the admin URLs will be * ``AdminSite.root()``. This method of hooking up the admin URLs will be
removed in favor of including ``admin.site.urls``. removed in favor of including ``admin.site.urls``.
* Authentication backends need to define the boolean attributes * Authentication backends need to define the boolean attributes

View File

@ -5,7 +5,7 @@ Mailing lists and Forum
.. Important:: .. Important::
Please report security issues **only** to Please report security issues **only** to
security@djangoproject.com. This is a private list only open to security@djangoproject.com. This is a private list only open to
long-time, highly trusted Django developers, and its archives are long-time, highly trusted Django developers, and its archives are
not public. For further details, please see :doc:`our security not public. For further details, please see :doc:`our security
policies </internals/security>`. policies </internals/security>`.

View File

@ -91,7 +91,7 @@ These files are:
read :ref:`more about packages <tut-packages>` in the official Python docs. read :ref:`more about packages <tut-packages>` in the official Python docs.
* :file:`mysite/settings.py`: Settings/configuration for this Django * :file:`mysite/settings.py`: Settings/configuration for this Django
project. :doc:`/topics/settings` will tell you all about how settings project. :doc:`/topics/settings` will tell you all about how settings
work. work.
* :file:`mysite/urls.py`: The URL declarations for this Django project; a * :file:`mysite/urls.py`: The URL declarations for this Django project; a

View File

@ -352,7 +352,7 @@ The Django test client
---------------------- ----------------------
Django provides a test :class:`~django.test.Client` to simulate a user Django provides a test :class:`~django.test.Client` to simulate a user
interacting with the code at the view level. We can use it in ``tests.py`` interacting with the code at the view level. We can use it in ``tests.py``
or even in the :djadmin:`shell`. or even in the :djadmin:`shell`.
We will start again with the :djadmin:`shell`, where we need to do a couple of We will start again with the :djadmin:`shell`, where we need to do a couple of

View File

@ -159,7 +159,7 @@ by ``extra`` -- and each time you come back to the "Change" page for an
already-created object, you get another three extra slots. already-created object, you get another three extra slots.
At the end of the three current slots you will find an "Add another Choice" At the end of the three current slots you will find an "Add another Choice"
link. If you click on it, a new slot will be added. If you want to remove the link. If you click on it, a new slot will be added. If you want to remove the
added slot, you can click on the X to the top right of the added slot. This added slot, you can click on the X to the top right of the added slot. This
image shows an added slot: image shows an added slot:

View File

@ -310,7 +310,7 @@ The core goals of Django's :doc:`cache framework </topics/cache>` are:
Less code Less code
--------- ---------
A cache should be as fast as possible. Hence, all framework code surrounding A cache should be as fast as possible. Hence, all framework code surrounding
the cache backend should be kept to the absolute minimum, especially for the cache backend should be kept to the absolute minimum, especially for
``get()`` operations. ``get()`` operations.

View File

@ -16,7 +16,7 @@ instructions for :ref:`installing the development version
If you're using Linux or a Unix installation, such as OpenSolaris, If you're using Linux or a Unix installation, such as OpenSolaris,
check with your distributor to see if they already package Django. If check with your distributor to see if they already package Django. If
you're using a Linux distro and don't know how to find out if a package you're using a Linux distro and don't know how to find out if a package
is available, then now is a good time to learn. The Django Wiki contains is available, then now is a good time to learn. The Django Wiki contains
a list of `Third Party Distributions`_ to help you out. a list of `Third Party Distributions`_ to help you out.
.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions .. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions

View File

@ -37,9 +37,9 @@ Simple mixins
.. admonition:: Use ``alters_data`` where appropriate .. admonition:: Use ``alters_data`` where appropriate
Note that having the view instance in the template context may Note that having the view instance in the template context may
expose potentially hazardous methods to template authors. To expose potentially hazardous methods to template authors. To
prevent methods like this from being called in the template, set prevent methods like this from being called in the template, set
``alters_data=True`` on those methods. For more information, read ``alters_data=True`` on those methods. For more information, read
the documentation on :ref:`rendering a template context the documentation on :ref:`rendering a template context
<alters-data-description>`. <alters-data-description>`.

View File

@ -6,7 +6,7 @@ Clickjacking Protection
:synopsis: Protects against Clickjacking :synopsis: Protects against Clickjacking
The clickjacking middleware and decorators provide easy-to-use protection The clickjacking middleware and decorators provide easy-to-use protection
against `clickjacking`_. This type of attack occurs when a malicious site against `clickjacking`_. This type of attack occurs when a malicious site
tricks a user into clicking on a concealed element of another site which they tricks a user into clicking on a concealed element of another site which they
have loaded in a hidden frame or iframe. have loaded in a hidden frame or iframe.

View File

@ -1153,7 +1153,7 @@ subclass::
The ``raw_id_fields`` ``Input`` widget should contain a primary key if the The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
field is a ``ForeignKey`` or a comma separated list of values if the field field is a ``ForeignKey`` or a comma separated list of values if the field
is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying
glass button next to the field which allows users to search for and select glass button next to the field which allows users to search for and select
a value: a value:
@ -1355,9 +1355,9 @@ subclass::
Custom template options Custom template options
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
The :ref:`admin-overriding-templates` section describes how to override or extend The :ref:`admin-overriding-templates` section describes how to override or
the default admin templates. Use the following options to override the default extend the default admin templates. Use the following options to override the
templates used by the :class:`ModelAdmin` views: default templates used by the :class:`ModelAdmin` views:
.. attribute:: ModelAdmin.add_form_template .. attribute:: ModelAdmin.add_form_template
@ -1660,7 +1660,7 @@ templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.get_urls() .. method:: ModelAdmin.get_urls()
The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
that ModelAdmin in the same way as a URLconf. Therefore you can extend that ModelAdmin in the same way as a URLconf. Therefore you can extend
them as documented in :doc:`/topics/http/urls`, using the them as documented in :doc:`/topics/http/urls`, using the
``AdminSite.admin_view()`` wrapper on your views:: ``AdminSite.admin_view()`` wrapper on your views::
@ -1970,7 +1970,7 @@ templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False) .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
Sends a message to the user using the :mod:`django.contrib.messages` Sends a message to the user using the :mod:`django.contrib.messages`
backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`. backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`.
Keyword arguments allow you to change the message level, add extra CSS Keyword arguments allow you to change the message level, add extra CSS
tags, or fail silently if the ``contrib.messages`` framework is not tags, or fail silently if the ``contrib.messages`` framework is not

View File

@ -604,9 +604,9 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
.. class:: ModelBackend .. class:: ModelBackend
This is the default authentication backend used by Django. It This is the default authentication backend used by Django. It
authenticates using credentials consisting of a user identifier and authenticates using credentials consisting of a user identifier and
password. For Django's default user model, the user identifier is the password. For Django's default user model, the user identifier is the
username, for custom user models it is the field specified by username, for custom user models it is the field specified by
USERNAME_FIELD (see :doc:`Customizing Users and authentication USERNAME_FIELD (see :doc:`Customizing Users and authentication
</topics/auth/customizing>`). </topics/auth/customizing>`).
@ -751,8 +751,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
.. class:: RemoteUserBackend .. class:: RemoteUserBackend
Use this backend to take advantage of external-to-Django-handled Use this backend to take advantage of external-to-Django-handled
authentication. It authenticates using usernames passed in authentication. It authenticates using usernames passed in
:attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>` the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
documentation. documentation.

View File

@ -19,13 +19,13 @@ auto-generated model definition, where appropriate.
The ``ogrinspect`` management command will inspect the given OGR-compatible The ``ogrinspect`` management command will inspect the given OGR-compatible
:class:`~django.contrib.gis.gdal.DataSource` (e.g., a shapefile) and will :class:`~django.contrib.gis.gdal.DataSource` (e.g., a shapefile) and will
output a GeoDjango model with the given model name. There's a detailed example output a GeoDjango model with the given model name. There's a detailed example
of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`. of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.
.. django-admin-option:: --blank BLANK .. django-admin-option:: --blank BLANK
Use a comma separated list of OGR field names to add the ``blank=True`` Use a comma separated list of OGR field names to add the ``blank=True``
keyword option to the field definition. Set with ``true`` to apply keyword option to the field definition. Set with ``true`` to apply
to all applicable fields. to all applicable fields.
.. django-admin-option:: --decimal DECIMAL .. django-admin-option:: --decimal DECIMAL
@ -73,10 +73,10 @@ of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.
.. django-admin-option:: --null NULL .. django-admin-option:: --null NULL
Use a comma separated list of OGR field names to add the ``null=True`` Use a comma separated list of OGR field names to add the ``null=True``
keyword option to the field definition. Set with ``true`` to apply to keyword option to the field definition. Set with ``true`` to apply to
all applicable fields. all applicable fields.
.. django-admin-option:: --srid SRID .. django-admin-option:: --srid SRID
The SRID to use for the geometry field. If not set, ``ogrinspect`` attempts The SRID to use for the geometry field. If not set, ``ogrinspect`` attempts
to automatically determine of the SRID of the data source. to automatically determine of the SRID of the data source.

View File

@ -141,7 +141,7 @@ Spatial Lookups
=============== ===============
GeoDjango's lookup types may be used with any manager method like GeoDjango's lookup types may be used with any manager method like
``filter()``, ``exclude()``, etc. However, the lookup types unique to ``filter()``, ``exclude()``, etc. However, the lookup types unique to
GeoDjango are only available on spatial fields. GeoDjango are only available on spatial fields.
Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`) Filters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)
@ -233,9 +233,9 @@ Introduction
------------ ------------
Distance calculations with spatial data is tricky because, unfortunately, Distance calculations with spatial data is tricky because, unfortunately,
the Earth is not flat. Some distance queries with fields in a geographic the Earth is not flat. Some distance queries with fields in a geographic
coordinate system may have to be expressed differently because of coordinate system may have to be expressed differently because of
limitations in PostGIS. Please see the :ref:`selecting-an-srid` section limitations in PostGIS. Please see the :ref:`selecting-an-srid` section
in the :doc:`model-api` documentation for more details. in the :doc:`model-api` documentation for more details.
.. _distance-lookups-intro: .. _distance-lookups-intro:
@ -273,7 +273,7 @@ to be in the units of the field.
In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
geographic distance queries are performed with. [#fndistsphere15]_ However, geographic distance queries are performed with. [#fndistsphere15]_ However,
these queries may take a long time, as great-circle distances must be 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 calculated on the fly for *every* row in the query. This is because the
spatial index on traditional geometry fields cannot be used. spatial index on traditional geometry fields cannot be used.
For much better performance on WGS84 distance queries, consider using For much better performance on WGS84 distance queries, consider using

View File

@ -9,11 +9,11 @@ the deployment of a normal Django application. Please consult Django's
.. warning:: .. warning::
GeoDjango uses the GDAL geospatial library which is GeoDjango uses the GDAL geospatial library which is
not thread safe at this time. Thus, it is *highly* recommended not thread safe at this time. Thus, it is *highly* recommended
to not use threading when deploying -- in other words, use an to not use threading when deploying -- in other words, use an
appropriate configuration of Apache. appropriate configuration of Apache.
For example, when configuring your application with ``mod_wsgi``, For example, when configuring your application with ``mod_wsgi``,
set the ``WSGIDaemonProcess`` attribute ``threads`` to ``1``, unless set the ``WSGIDaemonProcess`` attribute ``threads`` to ``1``, unless
Apache may crash when running your GeoDjango application. Increase the Apache may crash when running your GeoDjango application. Increase the
number of ``processes`` instead. number of ``processes`` instead.

View File

@ -7,7 +7,7 @@ Geographic Feeds
GeoDjango has its own :class:`Feed` subclass that may embed location information GeoDjango has its own :class:`Feed` subclass that may embed location information
in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or
`W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of `W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of
Django's, please consult :doc:`Django's syndication documentation Django's, please consult :doc:`Django's syndication documentation
</ref/contrib/syndication>` for details on general usage. </ref/contrib/syndication>` for details on general usage.

View File

@ -349,7 +349,7 @@ scaled coordinates by multiplying them with the ``x``, ``y``, and optionally
SpatiaLite SpatiaLite
Accepts a single geographic field or expression and returns a geometry with all Accepts a single geographic field or expression and returns a geometry with all
points snapped to the given grid. How the geometry is snapped to the grid points snapped to the given grid. How the geometry is snapped to the grid
depends on how many numeric (either float, integer, or long) arguments are depends on how many numeric (either float, integer, or long) arguments are
given. given.
@ -376,7 +376,7 @@ the transformed geometry to the spatial reference system specified by the
.. note:: .. note::
What spatial reference system an integer SRID corresponds to may depend on What spatial reference system an integer SRID corresponds to may depend on
the spatial database used. In other words, the SRID numbers used for Oracle the spatial database used. In other words, the SRID numbers used for Oracle
are not necessarily the same as those used by PostGIS. are not necessarily the same as those used by PostGIS.
``Translate`` ``Translate``

View File

@ -6,7 +6,7 @@ GDAL API
:synopsis: GeoDjango's high-level interface to the GDAL library. :synopsis: GeoDjango's high-level interface to the GDAL library.
`GDAL`__ stands for **Geospatial Data Abstraction Library**, `GDAL`__ stands for **Geospatial Data Abstraction Library**,
and is a veritable "Swiss army knife" of GIS data functionality. A subset and is a veritable "Swiss army knife" of GIS data functionality. A subset
of GDAL is the `OGR`__ Simple Features Library, which specializes of GDAL is the `OGR`__ Simple Features Library, which specializes
in reading and writing vector geographic data in a variety of standard in reading and writing vector geographic data in a variety of standard
formats. formats.
@ -34,7 +34,7 @@ Sample Data
The GDAL/OGR tools described here are designed to help you read in The GDAL/OGR tools described here are designed to help you read in
your geospatial data, in order for most of them to be useful you have your geospatial data, in order for most of them to be useful you have
to have some data to work with. If you're starting out and don't yet to have some data to work with. If you're starting out and don't yet
have any data of your own to use, GeoDjango tests contain a number of have any data of your own to use, GeoDjango tests contain a number of
data sets that you can use for testing. You can download them here: data sets that you can use for testing. You can download them here:
@ -51,9 +51,9 @@ Vector Data Source Objects
:class:`DataSource` is a wrapper for the OGR data source object that :class:`DataSource` is a wrapper for the OGR data source object that
supports reading data from a variety of OGR-supported geospatial file supports reading data from a variety of OGR-supported geospatial file
formats and data sources using a consistent interface. Each formats and data sources using a consistent interface. Each
data source is represented by a :class:`DataSource` object which contains data source is represented by a :class:`DataSource` object which contains
one or more layers of data. Each layer, represented by a :class:`Layer` one or more layers of data. Each layer, represented by a :class:`Layer`
object, contains some number of geographic features (:class:`Feature`), object, contains some number of geographic features (:class:`Feature`),
information about the type of features contained in that layer (e.g. information about the type of features contained in that layer (e.g.
points, polygons, etc.), as well as the names and types of any points, polygons, etc.), as well as the names and types of any
@ -285,7 +285,7 @@ __ https://gdal.org/drivers/vector/
.. method:: test_capability(capability) .. method:: test_capability(capability)
Returns a boolean indicating whether this layer supports the given Returns a boolean indicating whether this layer supports the given
capability (a string). Examples of valid capability strings include: capability (a string). Examples of valid capability strings include:
``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``, ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,
``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``, ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,
``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and
@ -673,7 +673,7 @@ coordinate transformation:
This property controls the spatial reference for this geometry, or This property controls the spatial reference for this geometry, or
``None`` if no spatial reference system has been assigned to it. ``None`` if no spatial reference system has been assigned to it.
If assigned, accessing this property returns a :class:`SpatialReference` If assigned, accessing this property returns a :class:`SpatialReference`
object. It may be set with another :class:`SpatialReference` object, object. It may be set with another :class:`SpatialReference` object,
or any input that :class:`SpatialReference` accepts. Example: or any input that :class:`SpatialReference` accepts. Example:
.. code-block:: pycon .. code-block:: pycon
@ -684,7 +684,7 @@ coordinate transformation:
.. attribute:: srid .. attribute:: srid
Returns or sets the spatial reference identifier corresponding to Returns or sets the spatial reference identifier corresponding to
:class:`SpatialReference` of this geometry. Returns ``None`` if :class:`SpatialReference` of this geometry. Returns ``None`` if
there is no spatial reference information associated with this there is no spatial reference information associated with this
geometry, or if an SRID cannot be determined. geometry, or if an SRID cannot be determined.
@ -1274,9 +1274,9 @@ Raster Data Objects
:class:`GDALRaster` is a wrapper for the GDAL raster source object that :class:`GDALRaster` is a wrapper for the GDAL raster source object that
supports reading data from a variety of GDAL-supported geospatial file supports reading data from a variety of GDAL-supported geospatial file
formats and data sources using a consistent interface. Each formats and data sources using a consistent interface. Each
data source is represented by a :class:`GDALRaster` object which contains data source is represented by a :class:`GDALRaster` object which contains
one or more layers of data named bands. Each band, represented by a one or more layers of data named bands. Each band, represented by a
:class:`GDALBand` object, contains georeferenced image data. For example, an RGB :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 image is represented as three bands: one for red, one for green, and one for
blue. blue.
@ -2140,7 +2140,7 @@ Settings
``GDAL_LIBRARY_PATH`` ``GDAL_LIBRARY_PATH``
--------------------- ---------------------
A string specifying the location of the GDAL library. Typically, A string specifying the location of the GDAL library. Typically,
this setting is only used if the GDAL library is in a non-standard this setting is only used if the GDAL library is in a non-standard
location (e.g., ``/home/john/lib/libgdal.so``). location (e.g., ``/home/john/lib/libgdal.so``).

View File

@ -13,7 +13,7 @@ The spatial lookups in this section are available for :class:`GeometryField`
and :class:`RasterField`. and :class:`RasterField`.
For an introduction, see the :ref:`spatial lookups introduction For an introduction, see the :ref:`spatial lookups introduction
<spatial-lookups-intro>`. For an overview of what lookups are <spatial-lookups-intro>`. For an overview of what lookups are
compatible with a particular spatial backend, refer to the compatible with a particular spatial backend, refer to the
:ref:`spatial lookup compatibility table <spatial-lookup-compatibility>`. :ref:`spatial lookup compatibility table <spatial-lookup-compatibility>`.
@ -454,18 +454,18 @@ SpatiaLite ``Overlaps(poly, geom)``
MariaDB, Oracle, SpatiaLite, PGRaster (Conversion) MariaDB, Oracle, SpatiaLite, PGRaster (Conversion)
Tests if the geometry field is spatially related to the lookup geometry by 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, 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: ``(geom, pattern)``; the form of ``pattern`` will depend on the spatial backend:
MariaDB, PostGIS, and SpatiaLite MariaDB, PostGIS, and SpatiaLite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
On these spatial backends the intersection pattern is a string comprising On these spatial backends the intersection pattern is a string comprising nine
nine characters, which define intersections between the interior, boundary, characters, which define intersections between the interior, boundary, and
and exterior of the geometry field and the lookup geometry. exterior of the geometry field and the lookup geometry. The intersection
The intersection pattern matrix may only use the following characters: pattern matrix may only use the following characters: ``1``, ``2``, ``T``,
``1``, ``2``, ``T``, ``F``, or ``*``. This lookup type allows users to "fine tune" ``F``, or ``*``. This lookup type allows users to "fine tune" a specific
a specific geometric relationship consistent with the DE-9IM model. [#fnde9im]_ geometric relationship consistent with the DE-9IM model. [#fnde9im]_
Geometry example:: Geometry example::
@ -503,7 +503,7 @@ Oracle
Here the relation pattern is comprised of at least one of the nine relation Here the relation pattern is comprised of at least one of the nine relation
strings: ``TOUCH``, ``OVERLAPBDYDISJOINT``, ``OVERLAPBDYINTERSECT``, strings: ``TOUCH``, ``OVERLAPBDYDISJOINT``, ``OVERLAPBDYINTERSECT``,
``EQUAL``, ``INSIDE``, ``COVEREDBY``, ``CONTAINS``, ``COVERS``, ``ON``, and ``EQUAL``, ``INSIDE``, ``COVEREDBY``, ``CONTAINS``, ``COVERS``, ``ON``, and
``ANYINTERACT``. Multiple strings may be combined with the logical Boolean ``ANYINTERACT``. Multiple strings may be combined with the logical Boolean
operator OR, for example, ``'inside+touch'``. [#fnsdorelate]_ The relation operator OR, for example, ``'inside+touch'``. [#fnsdorelate]_ The relation
strings are case-insensitive. strings are case-insensitive.
@ -894,7 +894,7 @@ use these aggregate functions, see :doc:`the topic guide on aggregation
===================== ===================================================== ===================== =====================================================
Keyword Argument Description Keyword Argument Description
===================== ===================================================== ===================== =====================================================
``tolerance`` This keyword is for Oracle only. It is for the ``tolerance`` This keyword is for Oracle only. It is for the
tolerance value used by the ``SDOAGGRTYPE`` tolerance value used by the ``SDOAGGRTYPE``
procedure; the `Oracle documentation`__ has more procedure; the `Oracle documentation`__ has more
details. details.

View File

@ -12,7 +12,7 @@ What is GEOS?
------------- -------------
`GEOS`__ stands for **Geometry Engine - Open Source**, `GEOS`__ stands for **Geometry Engine - Open Source**,
and is a C++ library, ported from the `Java Topology Suite`__. GEOS and is a C++ library, ported from the `Java Topology Suite`__. GEOS
implements the OpenGIS `Simple Features for SQL`__ spatial predicate functions implements the OpenGIS `Simple Features for SQL`__ spatial predicate functions
and spatial operators. GEOS, now an OSGeo project, was initially developed and and spatial operators. GEOS, now an OSGeo project, was initially developed and
maintained by `Refractions Research`__ of Victoria, Canada. maintained by `Refractions Research`__ of Victoria, Canada.
@ -30,8 +30,8 @@ features include:
* A BSD-licensed interface to the GEOS geometry routines, implemented purely * A BSD-licensed interface to the GEOS geometry routines, implemented purely
in Python using ``ctypes``. in Python using ``ctypes``.
* Loosely-coupled to GeoDjango. For example, :class:`GEOSGeometry` objects * Loosely-coupled to GeoDjango. For example, :class:`GEOSGeometry` objects
may be used outside of a Django project/application. In other words, may be used outside of a Django project/application. In other words,
no need to have :envvar:`DJANGO_SETTINGS_MODULE` set or use a database, etc. no need to have :envvar:`DJANGO_SETTINGS_MODULE` set or use a database, etc.
* Mutability: :class:`GEOSGeometry` objects may be modified. * Mutability: :class:`GEOSGeometry` objects may be modified.
* Cross-platform tested. * Cross-platform tested.
@ -47,7 +47,7 @@ This section contains a brief introduction and tutorial to using
Creating a Geometry Creating a Geometry
------------------- -------------------
:class:`GEOSGeometry` objects may be created in a few ways. The first is :class:`GEOSGeometry` objects may be created in a few ways. The first is
to simply instantiate the object on some spatial input -- the following to simply instantiate the object on some spatial input -- the following
are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON: are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON:
@ -66,7 +66,7 @@ are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON:
... ) # GeoJSON ... ) # GeoJSON
Another option is to use the constructor for the specific geometry type Another option is to use the constructor for the specific geometry type
that you wish to create. For example, a :class:`Point` object may be that you wish to create. For example, a :class:`Point` object may be
created by passing in the X and Y coordinates into its constructor: created by passing in the X and Y coordinates into its constructor:
.. code-block:: pycon .. code-block:: pycon
@ -127,8 +127,8 @@ may be used to get the geometry coordinates as a Python tuple:
(5.0, 23.0) (5.0, 23.0)
You can get/set geometry components using standard Python indexing You can get/set geometry components using standard Python indexing
techniques. However, what is returned depends on the geometry type techniques. However, what is returned depends on the geometry type
of the object. For example, indexing on a :class:`LineString` of the object. For example, indexing on a :class:`LineString`
returns a coordinate tuple: returns a coordinate tuple:
.. code-block:: pycon .. code-block:: pycon
@ -212,7 +212,7 @@ Geometry Objects
:param srid: spatial reference identifier :param srid: spatial reference identifier
:type srid: int :type srid: int
This is the base class for all GEOS geometry objects. It initializes on the This is the base class for all GEOS geometry objects. It initializes on the
given ``geo_input`` argument, and then assumes the proper geometry subclass given ``geo_input`` argument, and then assumes the proper geometry subclass
(e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object). (e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).
@ -275,7 +275,7 @@ Properties
.. attribute:: GEOSGeometry.geom_type .. attribute:: GEOSGeometry.geom_type
Returns a string corresponding to the type of geometry. For example: Returns a string corresponding to the type of geometry. For example:
.. code-block:: pycon .. code-block:: pycon
@ -285,7 +285,7 @@ Properties
.. attribute:: GEOSGeometry.geom_typeid .. attribute:: GEOSGeometry.geom_typeid
Returns the GEOS geometry type identification number. The following table Returns the GEOS geometry type identification number. The following table
shows the value for each geometry type: shows the value for each geometry type:
=========================== ======== =========================== ========
@ -307,7 +307,7 @@ Properties
.. attribute:: GEOSGeometry.num_geom .. attribute:: GEOSGeometry.num_geom
Returns the number of geometries in this geometry. In other words, will Returns the number of geometries in this geometry. In other words, will
return 1 on anything but geometry collections. return 1 on anything but geometry collections.
.. attribute:: GEOSGeometry.hasz .. attribute:: GEOSGeometry.hasz
@ -329,7 +329,7 @@ Properties
Returns a boolean indicating whether the geometry is 'simple'. A geometry Returns a boolean indicating whether the geometry is 'simple'. A geometry
is simple if and only if it does not intersect itself (except at boundary is simple if and only if it does not intersect itself (except at boundary
points). For example, a :class:`LineString` object is not simple if it points). For example, a :class:`LineString` object is not simple if it
intersects itself. Thus, :class:`LinearRing` and :class:`Polygon` objects intersects itself. Thus, :class:`LinearRing` and :class:`Polygon` objects
are always simple because they cannot intersect themselves, by definition. are always simple because they cannot intersect themselves, by definition.
@ -344,7 +344,7 @@ Properties
.. attribute:: GEOSGeometry.srid .. attribute:: GEOSGeometry.srid
Property that may be used to retrieve or set the SRID associated with the Property that may be used to retrieve or set the SRID associated with the
geometry. For example: geometry. For example:
.. code-block:: pycon .. code-block:: pycon
@ -359,12 +359,12 @@ Output Properties
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
The properties in this section export the :class:`GEOSGeometry` object into The properties in this section export the :class:`GEOSGeometry` object into
a different. This output may be in the form of a string, buffer, or even a different. This output may be in the form of a string, buffer, or even
another object. another object.
.. attribute:: GEOSGeometry.ewkt .. attribute:: GEOSGeometry.ewkt
Returns the "extended" Well-Known Text of the geometry. This representation Returns the "extended" Well-Known Text of the geometry. This representation
is specific to PostGIS and is a superset of the OGC WKT standard. [#fnogc]_ is specific to PostGIS and is a superset of the OGC WKT standard. [#fnogc]_
Essentially the SRID is prepended to the WKT representation, for example Essentially the SRID is prepended to the WKT representation, for example
``SRID=4326;POINT(5 23)``. ``SRID=4326;POINT(5 23)``.
@ -376,14 +376,14 @@ another object.
.. attribute:: GEOSGeometry.hex .. attribute:: GEOSGeometry.hex
Returns the WKB of this Geometry in hexadecimal form. Please note Returns the WKB of this Geometry in hexadecimal form. Please note
that the SRID value is not included in this representation that the SRID value is not included in this representation
because it is not a part of the OGC specification (use the because it is not a part of the OGC specification (use the
:attr:`GEOSGeometry.hexewkb` property instead). :attr:`GEOSGeometry.hexewkb` property instead).
.. attribute:: GEOSGeometry.hexewkb .. attribute:: GEOSGeometry.hexewkb
Returns the EWKB of this Geometry in hexadecimal form. This is an Returns the EWKB of this Geometry in hexadecimal form. This is an
extension of the WKB specification that includes the SRID value extension of the WKB specification that includes the SRID value
that are a part of this geometry. that are a part of this geometry.
@ -400,7 +400,7 @@ another object.
.. attribute:: GEOSGeometry.kml .. attribute:: GEOSGeometry.kml
Returns a `KML`__ (Keyhole Markup Language) representation of the Returns a `KML`__ (Keyhole Markup Language) representation of the
geometry. This should only be used for geometries with an SRID of geometry. This should only be used for geometries with an SRID of
4326 (WGS84), but this restriction is not enforced. 4326 (WGS84), but this restriction is not enforced.
.. attribute:: GEOSGeometry.ogr .. attribute:: GEOSGeometry.ogr
@ -413,7 +413,7 @@ another object.
.. attribute:: GEOSGeometry.wkb .. attribute:: GEOSGeometry.wkb
Returns the WKB (Well-Known Binary) representation of this Geometry Returns the WKB (Well-Known Binary) representation of this Geometry
as a Python buffer. SRID value is not included, use the as a Python buffer. SRID value is not included, use the
:attr:`GEOSGeometry.ewkb` property instead. :attr:`GEOSGeometry.ewkb` property instead.
.. _ewkb: .. _ewkb:
@ -483,7 +483,7 @@ return a boolean.
.. method:: GEOSGeometry.equals_exact(other, tolerance=0) .. method:: GEOSGeometry.equals_exact(other, tolerance=0)
Returns true if the two geometries are exactly equal, up to a Returns true if the two geometries are exactly equal, up to a
specified tolerance. The ``tolerance`` value should be a floating specified tolerance. The ``tolerance`` value should be a floating
point number representing the error tolerance in the comparison, e.g., point number representing the error tolerance in the comparison, e.g.,
``poly1.equals_exact(poly2, 0.001)`` will compare equality to within ``poly1.equals_exact(poly2, 0.001)`` will compare equality to within
one thousandth of a unit. one thousandth of a unit.
@ -608,7 +608,7 @@ Topological Properties
.. attribute:: GEOSGeometry.centroid .. attribute:: GEOSGeometry.centroid
Returns a :class:`Point` object representing the geometric center of Returns a :class:`Point` object representing the geometric center of
the geometry. The point is not guaranteed to be on the interior the geometry. The point is not guaranteed to be on the interior
of the geometry. of the geometry.
.. attribute:: GEOSGeometry.convex_hull .. attribute:: GEOSGeometry.convex_hull
@ -809,7 +809,7 @@ Other Properties & Methods
.. class:: Polygon(*args, **kwargs) .. class:: Polygon(*args, **kwargs)
``Polygon`` objects may be instantiated by passing in parameters that ``Polygon`` objects may be instantiated by passing in parameters that
represent the rings of the polygon. The parameters must either be 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` instances, or a sequence that may be used to construct a
:class:`LinearRing`: :class:`LinearRing`:
@ -922,12 +922,13 @@ Prepared Geometries
=================== ===================
In order to obtain a prepared geometry, access the In order to obtain a prepared geometry, access the
:attr:`GEOSGeometry.prepared` property. Once you have a :attr:`GEOSGeometry.prepared` property. Once you have a ``PreparedGeometry``
``PreparedGeometry`` instance its spatial predicate methods, listed below, instance its spatial predicate methods, listed below, may be used with other
may be used with other ``GEOSGeometry`` objects. An operation with a prepared ``GEOSGeometry`` objects. An operation with a prepared geometry can be orders
geometry can be orders of magnitude faster -- the more complex the geometry of magnitude faster -- the more complex the geometry that is prepared, the
that is prepared, the larger the speedup in the operation. For more information, larger the speedup in the operation. For more information, please consult the
please consult the `GEOS wiki page on prepared geometries <https://trac.osgeo.org/geos/wiki/PreparedGeometry>`_. `GEOS wiki page on prepared geometries
<https://trac.osgeo.org/geos/wiki/PreparedGeometry>`_.
For example: For example:
@ -1034,14 +1035,14 @@ Writer Objects
-------------- --------------
All writer objects have a ``write(geom)`` method that returns either the All writer objects have a ``write(geom)`` method that returns either the
WKB or WKT of the given geometry. In addition, :class:`WKBWriter` objects WKB or WKT of the given geometry. In addition, :class:`WKBWriter` objects
also have properties that may be used to change the byte order, and or also have properties that may be used to change the byte order, and or
include the SRID value (in other words, EWKB). include the SRID value (in other words, EWKB).
.. class:: WKBWriter(dim=2) .. class:: WKBWriter(dim=2)
``WKBWriter`` provides the most control over its output. By default it ``WKBWriter`` provides the most control over its output. By default it
returns OGC-compliant WKB when its ``write`` method is called. However, returns OGC-compliant WKB when its ``write`` method is called. However,
it has properties that allow for the creation of EWKB, a superset of the it has properties that allow for the creation of EWKB, a superset of the
WKB standard that includes additional information. See the WKB standard that includes additional information. See the
:attr:`WKBWriter.outdim` documentation for more details about the ``dim`` :attr:`WKBWriter.outdim` documentation for more details about the ``dim``
@ -1062,7 +1063,7 @@ include the SRID value (in other words, EWKB).
.. method:: WKBWriter.write_hex(geom) .. method:: WKBWriter.write_hex(geom)
Returns WKB of the geometry in hexadecimal. Example: Returns WKB of the geometry in hexadecimal. Example:
.. code-block:: pycon .. code-block:: pycon
@ -1099,7 +1100,7 @@ include the SRID value (in other words, EWKB).
.. attribute:: WKBWriter.outdim .. attribute:: WKBWriter.outdim
This property may be set to change the output dimension of the geometry This property may be set to change the output dimension of the geometry
representation. In other words, if you have a 3D geometry then set to 3 representation. In other words, if you have a 3D geometry then set to 3
so that the Z value is included in the WKB. so that the Z value is included in the WKB.
============ =========================== ============ ===========================
@ -1127,7 +1128,7 @@ include the SRID value (in other words, EWKB).
.. attribute:: WKBWriter.srid .. attribute:: WKBWriter.srid
Set this property with a boolean to indicate whether the SRID of the Set this property with a boolean to indicate whether the SRID of the
geometry should be included with the WKB representation. Example: geometry should be included with the WKB representation. Example:
.. code-block:: pycon .. code-block:: pycon
@ -1210,7 +1211,7 @@ Settings
``GEOS_LIBRARY_PATH`` ``GEOS_LIBRARY_PATH``
--------------------- ---------------------
A string specifying the location of the GEOS C library. Typically, A string specifying the location of the GEOS C library. Typically,
this setting is only used if the GEOS C library is in a non-standard this setting is only used if the GEOS C library is in a non-standard
location (e.g., ``/home/bob/lib/libgeos_c.so``). location (e.g., ``/home/bob/lib/libgeos_c.so``).

View File

@ -80,7 +80,7 @@ Building from source
When installing from source on UNIX and GNU/Linux systems, please follow When installing from source on UNIX and GNU/Linux systems, please follow
the installation instructions carefully, and install the libraries in the the installation instructions carefully, and install the libraries in the
given order. If using MySQL or Oracle as the spatial database, only GEOS given order. If using MySQL or Oracle as the spatial database, only GEOS
is required. is required.
.. note:: .. note::
@ -106,7 +106,7 @@ GEOS
GEOS is a C++ library for performing geometric operations, and is the default GEOS is a C++ library for performing geometric operations, and is the default
internal geometry representation used by GeoDjango (it's behind the "lazy" internal geometry representation used by GeoDjango (it's behind the "lazy"
geometries). Specifically, the C API library is called (e.g., ``libgeos_c.so``) geometries). Specifically, the C API library is called (e.g., ``libgeos_c.so``)
directly from Python using ctypes. directly from Python using ctypes.
First, download GEOS from the GEOS website and untar the source archive: First, download GEOS from the GEOS website and untar the source archive:
@ -158,7 +158,7 @@ If using a binary package of GEOS (e.g., on Ubuntu), you may need to :ref:`binut
If your GEOS library is in a non-standard location, or you don't want to If your GEOS library is in a non-standard location, or you don't want to
modify the system's library path then the :setting:`GEOS_LIBRARY_PATH` modify the system's library path then the :setting:`GEOS_LIBRARY_PATH`
setting may be added to your Django settings file with the full path to the setting may be added to your Django settings file with the full path to the
GEOS C library. For example: GEOS C library. For example:
.. code-block:: shell .. code-block:: shell
@ -231,7 +231,7 @@ GDAL
---- ----
`GDAL`__ is an excellent open source geospatial library that has support for `GDAL`__ is an excellent open source geospatial library that has support for
reading most vector and raster spatial data formats. Currently, GeoDjango only reading most vector and raster spatial data formats. Currently, GeoDjango only
supports :doc:`GDAL's vector data <../gdal>` capabilities [#]_. supports :doc:`GDAL's vector data <../gdal>` capabilities [#]_.
:ref:`geosbuild` and :ref:`proj4` should be installed prior to building GDAL. :ref:`geosbuild` and :ref:`proj4` should be installed prior to building GDAL.
@ -284,7 +284,7 @@ When GeoDjango can't find the GDAL library, configure your :ref:`libsettings`
If your GDAL library is in a non-standard location, or you don't want to If your GDAL library is in a non-standard location, or you don't want to
modify the system's library path then the :setting:`GDAL_LIBRARY_PATH` modify the system's library path then the :setting:`GDAL_LIBRARY_PATH`
setting may be added to your Django settings file with the full path to setting may be added to your Django settings file with the full path to
the GDAL library. For example: the GDAL library. For example:
.. code-block:: shell .. code-block:: shell

View File

@ -21,9 +21,9 @@ then inserting into a GeoDjango model.
.. warning :: .. warning ::
GIS data sources, like shapefiles, may be very large. If you find GIS data sources, like shapefiles, may be very large. If you find
that :class:`LayerMapping` is using too much memory, set that :class:`LayerMapping` is using too much memory, set
:setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG` :setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG`
is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>` is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>`
*every* SQL query -- and when SQL statements contain geometries, this may *every* SQL query -- and when SQL statements contain geometries, this may
consume more memory than is typical. consume more memory than is typical.
@ -83,7 +83,7 @@ Example
Here, :class:`LayerMapping` transformed the three geometries from the shapefile Here, :class:`LayerMapping` transformed the three geometries from the shapefile
in their original spatial reference system (WGS84) to the spatial reference in their original spatial reference system (WGS84) to the spatial reference
system of the GeoDjango model (NAD83). If no spatial reference system is system of the GeoDjango model (NAD83). If no spatial reference system is
defined for the layer, use the ``source_srs`` keyword with a defined for the layer, use the ``source_srs`` keyword with a
:class:`~django.contrib.gis.gdal.SpatialReference` object to specify one. :class:`~django.contrib.gis.gdal.SpatialReference` object to specify one.
@ -101,7 +101,7 @@ Argument Description
``model`` The geographic model, *not* an instance. ``model`` The geographic model, *not* an instance.
``data_source`` The path to the OGR-supported data source file ``data_source`` The path to the OGR-supported data source file
(e.g., a shapefile). Also accepts (e.g., a shapefile). Also accepts
:class:`django.contrib.gis.gdal.DataSource` instances. :class:`django.contrib.gis.gdal.DataSource` instances.
``mapping`` A dictionary: keys are strings corresponding to ``mapping`` A dictionary: keys are strings corresponding to
@ -120,12 +120,12 @@ Keyword Arguments
``source_srs`` Use this to specify the source SRS manually (for ``source_srs`` Use this to specify the source SRS manually (for
example, some shapefiles don't come with a ``'.prj'`` example, some shapefiles don't come with a ``'.prj'``
file). An integer SRID, WKT or PROJ strings, and file). An integer SRID, WKT or PROJ strings, and
:class:`django.contrib.gis.gdal.SpatialReference` :class:`django.contrib.gis.gdal.SpatialReference`
objects are accepted. objects are accepted.
``encoding`` Specifies the character set encoding of the strings ``encoding`` Specifies the character set encoding of the strings
in the OGR data source. For example, ``'latin-1'``, in the OGR data source. For example, ``'latin-1'``,
``'utf-8'``, and ``'cp437'`` are all valid encoding ``'utf-8'``, and ``'cp437'`` are all valid encoding
parameters. parameters.
@ -133,7 +133,7 @@ Keyword Arguments
``'autocommit'``. ``'autocommit'``.
``transform`` Setting this to False will disable coordinate ``transform`` Setting this to False will disable coordinate
transformations. In other words, geometries will transformations. In other words, geometries will
be inserted into the database unmodified from their be inserted into the database unmodified from their
original state in the data source. original state in the data source.
@ -141,7 +141,7 @@ Keyword Arguments
from the given model will create models unique from the given model will create models unique
only to the given name(s). Geometries from only to the given name(s). Geometries from
each feature will be added into the collection each feature will be added into the collection
associated with the unique model. Forces associated with the unique model. Forces
the transaction mode to be ``'autocommit'``. the transaction mode to be ``'autocommit'``.
``using`` Sets the database to use when importing spatial data. ``using`` Sets the database to use when importing spatial data.
@ -153,7 +153,7 @@ Keyword Arguments
.. method:: LayerMapping.save(verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False) .. method:: LayerMapping.save(verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)
The ``save()`` method also accepts keywords. These keywords are The ``save()`` method also accepts keywords. These keywords are
used for controlling output logging, error handling, and for importing used for controlling output logging, error handling, and for importing
specific feature ranges. specific feature ranges.
@ -162,14 +162,14 @@ Save Keyword Arguments Description
=========================== ================================================= =========================== =================================================
``fid_range`` May be set with a slice or tuple of ``fid_range`` May be set with a slice or tuple of
(begin, end) feature ID's to map from (begin, end) feature ID's to map from
the data source. In other words, this the data source. In other words, this
keyword enables the user to selectively keyword enables the user to selectively
import a subset range of features in the import a subset range of features in the
geographic data source. geographic data source.
``progress`` When this keyword is set, status information ``progress`` When this keyword is set, status information
will be printed giving the number of features will be printed giving the number of features
processed and successfully saved. By default, processed and successfully saved. By default,
progress information will be printed every 1000 progress information will be printed every 1000
features processed, however, this default may features processed, however, this default may
be overridden by setting this keyword with an be overridden by setting this keyword with an
@ -186,11 +186,11 @@ Save Keyword Arguments Description
``stream`` Status information will be written to this file ``stream`` Status information will be written to this file
handle. Defaults to using ``sys.stdout``, but handle. Defaults to using ``sys.stdout``, but
any object with a ``write`` method is supported. any object with a ``write`` method is supported.
``strict`` Execution of the model mapping will cease upon ``strict`` Execution of the model mapping will cease upon
the first error encountered. The default value the first error encountered. The default value
(``False``) (``False``)
behavior is to attempt to continue. behavior is to attempt to continue.
@ -206,7 +206,7 @@ Running out of memory
--------------------- ---------------------
As noted in the warning at the top of this section, Django stores all SQL As noted in the warning at the top of this section, Django stores all SQL
queries when ``DEBUG=True``. Set ``DEBUG=False`` in your settings, and this queries when ``DEBUG=True``. Set ``DEBUG=False`` in your settings, and this
should stop excessive memory use when running ``LayerMapping`` scripts. should stop excessive memory use when running ``LayerMapping`` scripts.
MySQL: ``max_allowed_packet`` error MySQL: ``max_allowed_packet`` error
@ -219,7 +219,7 @@ If you encounter the following error when using ``LayerMapping`` and MySQL:
OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes") OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes")
Then the solution is to increase the value of the ``max_allowed_packet`` Then the solution is to increase the value of the ``max_allowed_packet``
setting in your MySQL configuration. For example, the default value may setting in your MySQL configuration. For example, the default value may
be something low like one megabyte -- the setting may be modified in MySQL's be something low like one megabyte -- the setting may be modified in MySQL's
configuration file (``my.cnf``) in the ``[mysqld]`` section: configuration file (``my.cnf``) in the ``[mysqld]`` section:

View File

@ -14,9 +14,10 @@ Specifically, it implements two objects, :class:`Distance` and
Example Example
======= =======
:class:`Distance` objects may be instantiated using a keyword argument indicating the :class:`Distance` objects may be instantiated using a keyword argument
context of the units. In the example below, two different distance objects are indicating the context of the units. In the example below, two different
instantiated in units of kilometers (``km``) and miles (``mi``): distance objects are instantiated in units of kilometers (``km``) and miles
(``mi``):
.. code-block:: pycon .. code-block:: pycon

View File

@ -5,7 +5,7 @@ GeoDjango Model API
.. module:: django.contrib.gis.db.models .. module:: django.contrib.gis.db.models
:synopsis: GeoDjango model and field API. :synopsis: GeoDjango model and field API.
This document explores the details of the GeoDjango Model API. Throughout this This document explores the details of the GeoDjango Model API. Throughout this
section, we'll be using the following geographic model of a `ZIP code`__ and section, we'll be using the following geographic model of a `ZIP code`__ and
of a `Digital Elevation Model`__ as our examples:: of a `Digital Elevation Model`__ as our examples::
@ -120,32 +120,33 @@ Selecting an SRID
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
Choosing an appropriate SRID for your model is an important decision that the Choosing an appropriate SRID for your model is an important decision that the
developer should consider carefully. The SRID is an integer specifier that developer should consider carefully. The SRID is an integer specifier that
corresponds to the projection system that will be used to interpret the data 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 in the spatial database. [#fnsrid]_ Projection systems give the context to the
coordinates that specify a location. Although the details of `geodesy`__ are coordinates that specify a location. Although the details of `geodesy`__ are
beyond the scope of this documentation, the general problem is that the earth 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) is spherical and representations of the earth (e.g., paper maps, web maps)
are not. are not.
Most people are familiar with using latitude and longitude to reference a Most people are familiar with using latitude and longitude to reference a
location on the earth's surface. However, latitude and longitude are angles, location on the earth's surface. However, latitude and longitude are angles,
not distances. In other words, while the shortest path between two points on not distances. In other words, while the shortest path between two points on a
a flat surface is a straight line, the shortest path between two points on a curved flat surface is a straight line, the shortest path between two points on a
surface (such as the earth) is an *arc* of a `great circle`__. [#fnthematic]_ Thus, curved surface (such as the earth) is an *arc* of a `great circle`__.
additional computation is required to obtain distances in planar units (e.g., [#fnthematic]_
kilometers and miles). Using a geographic coordinate system may introduce
complications for the developer later on. For example, SpatiaLite does not have Thus, additional computation is required to obtain distances in planar units
the capability to perform distance calculations between geometries using (e.g., kilometers and miles). Using a geographic coordinate system may
geographic coordinate systems, e.g. constructing a query to find all points introduce complications for the developer later on. For example, SpatiaLite
within 5 miles of a county boundary stored as WGS84. does not have the capability to perform distance calculations between
[#fndist]_ 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 Portions of the earth's surface may projected onto a two-dimensional, or
Cartesian, plane. Projected coordinate systems are especially convenient Cartesian, plane. Projected coordinate systems are especially convenient for
for region-specific applications, e.g., if you know that your database will region-specific applications, e.g., if you know that your database will only
only cover geometries in `North Kansas`__, then you may consider using projection cover geometries in `North Kansas`__, then you may consider using projection
system specific to that region. Moreover, projected coordinate systems are system specific to that region. Moreover, projected coordinate systems are
defined in Cartesian units (such as meters or feet), easing distance defined in Cartesian units (such as meters or feet), easing distance
calculations. calculations.
@ -161,7 +162,7 @@ Additional Resources:
* `spatialreference.org`__: A Django-powered database of spatial reference * `spatialreference.org`__: A Django-powered database of spatial reference
systems. systems.
* `The State Plane Coordinate System`__: A website covering the various * `The State Plane Coordinate System`__: A website covering the various
projection systems used in the United States. Much of the U.S. spatial projection systems used in the United States. Much of the U.S. spatial
data encountered will be in one of these coordinate systems rather than data encountered will be in one of these coordinate systems rather than
in a geographic coordinate system such as WGS84. in a geographic coordinate system such as WGS84.
@ -176,14 +177,14 @@ __ https://web.archive.org/web/20080302095452/http://welcome.warnercnr.colostate
.. attribute:: BaseSpatialField.spatial_index .. attribute:: BaseSpatialField.spatial_index
Defaults to ``True``. Creates a spatial index for the given geometry Defaults to ``True``. Creates a spatial index for the given geometry
field. field.
.. note:: .. note::
This is different from the ``db_index`` field option because spatial This is different from the ``db_index`` field option because spatial
indexes are created in a different manner than regular database indexes are created in a different manner than regular database
indexes. Specifically, spatial indexes are typically created using indexes. Specifically, spatial indexes are typically created using
a variant of the R-Tree, while regular database indexes typically a variant of the R-Tree, while regular database indexes typically
use B-Trees. use B-Trees.
@ -201,8 +202,8 @@ options are optional.
.. attribute:: GeometryField.dim .. attribute:: GeometryField.dim
This option may be used for customizing the coordinate dimension of the This option may be used for customizing the coordinate dimension of the
geometry field. By default, it is set to 2, for representing two-dimensional geometry field. By default, it is set to 2, for representing two-dimensional
geometries. For spatial backends that support it, it may be set to 3 for geometries. For spatial backends that support it, it may be set to 3 for
three-dimensional support. three-dimensional support.
.. note:: .. note::
@ -215,7 +216,7 @@ three-dimensional support.
.. attribute:: GeometryField.geography .. attribute:: GeometryField.geography
If set to ``True``, this option will create a database column of If set to ``True``, this option will create a database column of
type geography, rather than geometry. Please refer to the type geography, rather than geometry. Please refer to the
:ref:`geography type <geography-type>` section below for more :ref:`geography type <geography-type>` section below for more
details. details.
@ -231,9 +232,9 @@ Geography Type
The geography type provides native support for spatial features represented The geography type provides native support for spatial features represented
with geographic coordinates (e.g., WGS84 longitude/latitude). [#fngeography]_ with geographic coordinates (e.g., WGS84 longitude/latitude). [#fngeography]_
Unlike the plane used by a geometry type, the geography type uses a spherical Unlike the plane used by a geometry type, the geography type uses a spherical
representation of its data. Distance and measurement operations representation of its data. Distance and measurement operations
performed on a geography column automatically employ great circle arc performed on a geography column automatically employ great circle arc
calculations and return linear units. In other words, when ``ST_Distance`` calculations and return linear units. In other words, when ``ST_Distance``
is called on two geographies, a value in meters is returned (as opposed is called on two geographies, a value in meters is returned (as opposed
to degrees if called on a geometry column in WGS84). to degrees if called on a geometry column in WGS84).
@ -267,7 +268,7 @@ determining `when to use geography data type over geometry data type
.. rubric:: Footnotes .. rubric:: Footnotes
.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_. .. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.
.. [#fnogcsrid] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems). .. [#fnogcsrid] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems).
.. [#fnsrid] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <https://epsg.org/>`_) identifier. However, it may also be associated with custom projections defined in spatial database's spatial reference systems table. .. [#fnsrid] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <https://epsg.org/>`_) identifier. However, it may also be associated with custom projections defined in spatial database's spatial reference systems table.
.. [#fnthematic] Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler, & Hugh H. Howard, *Thematic Cartography and Geographic Visualization* (Prentice Hall, 2nd edition), at Ch. 7.1.3. .. [#fnthematic] Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler, & Hugh H. Howard, *Thematic Cartography and Geographic Visualization* (Prentice Hall, 2nd edition), at Ch. 7.1.3.
.. [#fndist] This limitation does not apply to PostGIS. .. [#fndist] This limitation does not apply to PostGIS.
.. [#fngeography] Please refer to the `PostGIS Geography Type <https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography>`_ documentation for more details. .. [#fngeography] Please refer to the `PostGIS Geography Type <https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography>`_ documentation for more details.

View File

@ -107,7 +107,7 @@ Geographic Data
World Borders World Borders
------------- -------------
The world borders data is available in this `zip file`__. Create a ``data`` The world borders data is available in this `zip file`__. Create a ``data``
directory in the ``world`` application, download the world borders data, and directory in the ``world`` application, download the world borders data, and
unzip. On GNU/Linux platforms, use the following commands: unzip. On GNU/Linux platforms, use the following commands:
@ -120,7 +120,7 @@ unzip. On GNU/Linux platforms, use the following commands:
$ cd ../.. $ cd ../..
The world borders ZIP file contains a set of data files collectively known as The world borders ZIP file contains a set of data files collectively known as
an `ESRI Shapefile`__, one of the most popular geospatial data formats. When an `ESRI Shapefile`__, one of the most popular geospatial data formats. When
unzipped, the world borders dataset includes files with the following unzipped, the world borders dataset includes files with the following
extensions: extensions:
@ -148,7 +148,7 @@ other vector data sources:
1: TM_WORLD_BORDERS-0.3 (Polygon) 1: TM_WORLD_BORDERS-0.3 (Polygon)
``ogrinfo`` tells us that the shapefile has one layer, and that this ``ogrinfo`` tells us that the shapefile has one layer, and that this
layer contains polygon data. To find out more, we'll specify the layer name layer contains polygon data. To find out more, we'll specify the layer name
and use the ``-so`` option to get only the important summary information: and use the ``-so`` option to get only the important summary information:
.. console:: .. console::
@ -195,7 +195,7 @@ This detailed summary information tells us the number of features in the layer
(246), the geographic bounds of the data, the spatial reference system (246), the geographic bounds of the data, the spatial reference system
("SRS WKT"), as well as type information for each attribute field. For example, ("SRS WKT"), as well as type information for each attribute field. For example,
``FIPS: String (2.0)`` indicates that the ``FIPS`` character field has ``FIPS: String (2.0)`` indicates that the ``FIPS`` character field has
a maximum length of 2. Similarly, ``LON: Real (8.3)`` is a floating-point a maximum length of 2. Similarly, ``LON: Real (8.3)`` is a floating-point
field that holds a maximum of 8 digits up to three decimal places. field that holds a maximum of 8 digits up to three decimal places.
Geographic Models Geographic Models
@ -236,7 +236,7 @@ Note that the ``models`` module is imported from ``django.contrib.gis.db``.
The default spatial reference system for geometry fields is WGS84 (meaning The default spatial reference system for geometry fields is WGS84 (meaning
the `SRID`__ is 4326) -- in other words, the field coordinates are in the `SRID`__ is 4326) -- in other words, the field coordinates are in
longitude, latitude pairs in units of degrees. To use a different longitude, latitude pairs in units of degrees. To use a different
coordinate system, set the SRID of the geometry field with the ``srid`` coordinate system, set the SRID of the geometry field with the ``srid``
argument. Use an integer representing the coordinate system's EPSG code. argument. Use an integer representing the coordinate system's EPSG code.
@ -324,7 +324,7 @@ GDAL Interface
-------------- --------------
Earlier, you used ``ogrinfo`` to examine the contents of the world borders Earlier, you used ``ogrinfo`` to examine the contents of the world borders
shapefile. GeoDjango also includes a Pythonic interface to GDAL's powerful OGR shapefile. GeoDjango also includes a Pythonic interface to GDAL's powerful OGR
library that can work with all the vector data sources that OGR supports. library that can work with all the vector data sources that OGR supports.
First, invoke the Django shell: First, invoke the Django shell:
@ -375,15 +375,15 @@ You can see the layer's geometry type and how many features it contains:
.. note:: .. note::
Unfortunately, the shapefile data format does not allow for greater Unfortunately, the shapefile data format does not allow for greater
specificity with regards to geometry types. This shapefile, like specificity with regards to geometry types. This shapefile, like
many others, actually includes ``MultiPolygon`` geometries, not Polygons. many others, actually includes ``MultiPolygon`` geometries, not Polygons.
It's important to use a more general field type in models: a It's important to use a more general field type in models: a
GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This ``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This
is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``. is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference 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 system associated with it. If it does, the ``srs`` attribute will return a
:class:`~django.contrib.gis.gdal.SpatialReference` object: :class:`~django.contrib.gis.gdal.SpatialReference` object:
.. code-block:: pycon .. code-block:: pycon
@ -410,7 +410,7 @@ system -- in other words, the data uses longitude, latitude pairs in
units of degrees. units of degrees.
In addition, shapefiles also support attribute fields that may contain In addition, shapefiles also support attribute fields that may contain
additional data. Here are the fields on the World Borders layer: additional data. Here are the fields on the World Borders layer:
>>> print(lyr.fields) >>> print(lyr.fields)
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT'] ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
@ -497,10 +497,10 @@ with the following code::
A few notes about what's going on: A few notes about what's going on:
* Each key in the ``world_mapping`` dictionary corresponds to a field in the * Each key in the ``world_mapping`` dictionary corresponds to a field in the
``WorldBorder`` model. The value is the name of the shapefile field ``WorldBorder`` model. The value is the name of the shapefile field
that data will be loaded from. that data will be loaded from.
* The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the * The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the
geometry type GeoDjango will import the field as. Even simple polygons in geometry type GeoDjango will import the field as. Even simple polygons in
the shapefile will automatically be converted into collections prior to the shapefile will automatically be converted into collections prior to
insertion into the database. insertion into the database.
* The path to the shapefile is not absolute -- in other words, if you move the * The path to the shapefile is not absolute -- in other words, if you move the
@ -529,7 +529,7 @@ Try ``ogrinspect``
------------------ ------------------
Now that you've seen how to define geographic models and import data with the Now that you've seen how to define geographic models and import data with the
:doc:`layermapping`, it's possible to further automate this process with :doc:`layermapping`, it's possible to further automate this process with
use of the :djadmin:`ogrinspect` management command. The :djadmin:`ogrinspect` use of the :djadmin:`ogrinspect` management command. The :djadmin:`ogrinspect`
command introspects a GDAL-supported vector data source (e.g., a shapefile) command introspects a GDAL-supported vector data source (e.g., a shapefile)
and generates a model definition and ``LayerMapping`` dictionary automatically. and generates a model definition and ``LayerMapping`` dictionary automatically.
@ -540,7 +540,7 @@ The general usage of the command goes as follows:
$ python manage.py ogrinspect [options] <data_source> <model_name> [options] $ python manage.py ogrinspect [options] <data_source> <model_name> [options]
``data_source`` is the path to the GDAL-supported data source and ``data_source`` is the path to the GDAL-supported data source and
``model_name`` is the name to use for the model. Command-line options may ``model_name`` is the name to use for the model. Command-line options may
be used to further define how the model is generated. be used to further define how the model is generated.
For example, the following command nearly reproduces the ``WorldBorder`` model For example, the following command nearly reproduces the ``WorldBorder`` model
@ -604,9 +604,9 @@ Spatial Queries
Spatial Lookups Spatial Lookups
--------------- ---------------
GeoDjango adds spatial lookups to the Django ORM. For example, you GeoDjango adds spatial lookups to the Django ORM. For example, you
can find the country in the ``WorldBorder`` table that contains can find the country in the ``WorldBorder`` table that contains
a particular point. First, fire up the management shell: a particular point. First, fire up the management shell:
.. console:: .. console::
@ -619,7 +619,7 @@ Now, define a point of interest [#]_:
>>> pnt_wkt = "POINT(-95.3385 29.7245)" >>> pnt_wkt = "POINT(-95.3385 29.7245)"
The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude, The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude,
29.7245 degrees latitude. The geometry is in a format known as 29.7245 degrees latitude. The geometry is in a format known as
Well Known Text (WKT), a standard issued by the Open Geospatial Well Known Text (WKT), a standard issued by the Open Geospatial
Consortium (OGC). [#]_ Import the ``WorldBorder`` model, and perform Consortium (OGC). [#]_ Import the ``WorldBorder`` model, and perform
a ``contains`` lookup using the ``pnt_wkt`` as the parameter: a ``contains`` lookup using the ``pnt_wkt`` as the parameter:
@ -653,7 +653,7 @@ available queries -- the :doc:`db-api` documentation has more.
Automatic Spatial Transformations Automatic Spatial Transformations
--------------------------------- ---------------------------------
When doing spatial queries, GeoDjango automatically transforms When doing spatial queries, GeoDjango automatically transforms
geometries if they're in a different coordinate system. In the following geometries if they're in a different coordinate system. In the following
example, coordinates will be expressed in `EPSG SRID 32140`__, example, coordinates will be expressed in `EPSG SRID 32140`__,
a coordinate system specific to south Texas **only** and in units of a coordinate system specific to south Texas **only** and in units of
**meters**, not degrees: **meters**, not degrees:
@ -710,7 +710,7 @@ __ https://spatialreference.org/ref/epsg/32140/
Lazy Geometries Lazy Geometries
--------------- ---------------
GeoDjango loads geometries in a standardized textual representation. When the GeoDjango loads geometries in a standardized textual representation. When the
geometry field is first accessed, GeoDjango creates a geometry field is first accessed, GeoDjango creates a
:class:`~django.contrib.gis.geos.GEOSGeometry` object, exposing powerful :class:`~django.contrib.gis.geos.GEOSGeometry` object, exposing powerful
functionality, such as serialization properties for popular geospatial functionality, such as serialization properties for popular geospatial

View File

@ -299,11 +299,11 @@ Indexes for ``varchar`` and ``text`` columns
-------------------------------------------- --------------------------------------------
When specifying ``db_index=True`` on your model fields, Django typically When specifying ``db_index=True`` on your model fields, Django typically
outputs a single ``CREATE INDEX`` statement. However, if the database type outputs a single ``CREATE INDEX`` statement. However, if the database type
for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``, for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
``FileField``, and ``TextField``), then Django will create ``FileField``, and ``TextField``), then Django will create
an additional index that uses an appropriate `PostgreSQL operator class`_ an additional index that uses an appropriate `PostgreSQL operator class`_
for the column. The extra index is necessary to correctly perform for the column. The extra index is necessary to correctly perform
lookups that use the ``LIKE`` operator in their SQL, as is done with the lookups that use the ``LIKE`` operator in their SQL, as is done with the
``contains`` and ``startswith`` lookup types. ``contains`` and ``startswith`` lookup types.
@ -827,7 +827,7 @@ Substring matching and case sensitivity
--------------------------------------- ---------------------------------------
For all SQLite versions, there is some slightly counterintuitive behavior when For all SQLite versions, there is some slightly counterintuitive behavior when
attempting to match some types of strings. These are triggered when using the attempting to match some types of strings. These are triggered when using the
:lookup:`iexact` or :lookup:`contains` filters in querysets. The behavior :lookup:`iexact` or :lookup:`contains` filters in querysets. The behavior
splits into two cases: splits into two cases:
@ -1143,7 +1143,7 @@ INSERT ... RETURNING INTO
------------------------- -------------------------
By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
retrieve the value of an ``AutoField`` when inserting new rows. This behavior retrieve the value of an ``AutoField`` when inserting new rows. This behavior
may result in a ``DatabaseError`` in certain unusual setups, such as when may result in a ``DatabaseError`` in certain unusual setups, such as when
inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger. inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
The ``RETURNING INTO`` clause can be disabled by setting the The ``RETURNING INTO`` clause can be disabled by setting the
@ -1182,9 +1182,9 @@ backends; except for Oracle, however, the quotes have no effect.
When running ``migrate``, an ``ORA-06552`` error may be encountered if When running ``migrate``, an ``ORA-06552`` error may be encountered if
certain Oracle keywords are used as the name of a model field or the certain Oracle keywords are used as the name of a model field or the
value of a ``db_column`` option. Django quotes all identifiers used value of a ``db_column`` option. Django quotes all identifiers used
in queries to prevent most such problems, but this error can still in queries to prevent most such problems, but this error can still
occur when an Oracle datatype is used as a column name. In occur when an Oracle datatype is used as a column name. In
particular, take care to avoid using the names ``date``, particular, take care to avoid using the names ``date``,
``timestamp``, ``number`` or ``float`` as a field name. ``timestamp``, ``number`` or ``float`` as a field name.

View File

@ -1641,7 +1641,7 @@ This is useful in a number of ways:
copy of a database that you'd like to interact with. You can dump your copy of a database that you'd like to interact with. You can dump your
database to a :ref:`fixture <fixtures-explanation>` (using the database to a :ref:`fixture <fixtures-explanation>` (using the
:djadmin:`dumpdata` command, explained above), then use ``testserver`` to run :djadmin:`dumpdata` command, explained above), then use ``testserver`` to run
your web application with that data. With this arrangement, you have the your web application with that data. With this arrangement, you have the
flexibility of messing up your data in any way, knowing that whatever data flexibility of messing up your data in any way, knowing that whatever data
changes you're making are only being made to a test database. changes you're making are only being made to a test database.
@ -1907,7 +1907,7 @@ Example usage:
.. django-admin-option:: --no-color .. django-admin-option:: --no-color
Disables colorized command output. Some commands format their output to be Disables colorized command output. Some commands format their output to be
colorized. For example, errors will be printed to the console in red and SQL colorized. For example, errors will be printed to the console in red and SQL
statements will be syntax highlighted. statements will be syntax highlighted.

View File

@ -842,7 +842,7 @@ By default, the form rendering methods include:
It's always a good idea to use ``<label>`` tags. It's always a good idea to use ``<label>`` tags.
The ``id`` attribute values are generated by prepending ``id_`` to the form The ``id`` attribute values are generated by prepending ``id_`` to the form
field names. This behavior is configurable, though, if you want to change the field names. This behavior is configurable, though, if you want to change the
``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags ``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags
entirely. entirely.
@ -1389,7 +1389,7 @@ Methods of ``BoundField``
.. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False) .. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)
Renders the field by rendering the passed widget, adding any HTML Renders the field by rendering the passed widget, adding any HTML
attributes passed as ``attrs``. If no widget is specified, then the attributes passed as ``attrs``. If no widget is specified, then the
field's default widget will be used. field's default widget will be used.
``only_initial`` is used by Django internals and should not be set ``only_initial`` is used by Django internals and should not be set

View File

@ -713,15 +713,15 @@ For each field, we describe the default widget used if you don't specify
.. attribute:: allow_files .. attribute:: allow_files
Optional. Either ``True`` or ``False``. Default is ``True``. Specifies Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
whether files in the specified location should be included. Either this or whether files in the specified location should be included. Either this
:attr:`allow_folders` must be ``True``. or :attr:`allow_folders` must be ``True``.
.. attribute:: allow_folders .. attribute:: allow_folders
Optional. Either ``True`` or ``False``. Default is ``False``. Specifies Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
whether folders in the specified location should be included. Either this or whether folders in the specified location should be included. Either
:attr:`allow_files` must be ``True``. this or :attr:`allow_files` must be ``True``.
``FloatField`` ``FloatField``
@ -1217,7 +1217,7 @@ Slightly complex built-in ``Field`` classes
.. attribute:: fields .. attribute:: fields
A tuple of fields whose values are cleaned and subsequently combined A tuple of fields whose values are cleaned and subsequently combined
into a single value. Each value of the field is cleaned by the into a single value. Each value of the field is cleaned by the
corresponding field in ``fields`` -- the first value is cleaned by the corresponding field in ``fields`` -- the first value is cleaned by the
first field, the second value is cleaned by the second field, etc. first field, the second value is cleaned by the second field, etc.
Once all fields are cleaned, the list of clean values is combined into Once all fields are cleaned, the list of clean values is combined into
@ -1325,9 +1325,9 @@ Fields which handle relationships
Two fields are available for representing relationships between Two fields are available for representing relationships between
models: :class:`ModelChoiceField` and models: :class:`ModelChoiceField` and
:class:`ModelMultipleChoiceField`. Both of these fields require a :class:`ModelMultipleChoiceField`. Both of these fields require a
single ``queryset`` parameter that is used to create the choices for single ``queryset`` parameter that is used to create the choices for
the field. Upon form validation, these fields will place either one the field. Upon form validation, these fields will place either one
model object (in the case of ``ModelChoiceField``) or multiple model model object (in the case of ``ModelChoiceField``) or multiple model
objects (in the case of ``ModelMultipleChoiceField``) into the objects (in the case of ``ModelMultipleChoiceField``) into the
``cleaned_data`` dictionary of the form. ``cleaned_data`` dictionary of the form.

View File

@ -251,7 +251,7 @@ The security loggers will receive messages on any occurrence of
:exc:`~django.core.exceptions.SuspiciousOperation` and other security-related :exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
errors. There is a sub-logger for each subtype of security error, including all errors. There is a sub-logger for each subtype of security error, including all
``SuspiciousOperation``\s. The level of the log event depends on where the ``SuspiciousOperation``\s. The level of the log event depends on where the
exception is handled. Most occurrences are logged as a warning, while exception is handled. Most occurrences are logged as a warning, while
any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
error. For example, when an HTTP ``Host`` header is included in a request from error. For example, when an HTTP ``Host`` header is included in a request from
a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400 a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400

View File

@ -416,7 +416,7 @@ the browser when you expected it to be something harmless.
To prevent the browser from guessing the content type and force it to To prevent the browser from guessing the content type and force it to
always use the type provided in the ``Content-Type`` header, you can pass always use the type provided in the ``Content-Type`` header, you can pass
the `X-Content-Type-Options: nosniff`__ header. ``SecurityMiddleware`` will the `X-Content-Type-Options: nosniff`__ header. ``SecurityMiddleware`` will
do this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting do this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting
is ``True``. is ``True``.

View File

@ -1146,7 +1146,7 @@ If you want to manually associate file data with
method is used to persist that file data. method is used to persist that file data.
Takes two required arguments: ``name`` which is the name of the file, and Takes two required arguments: ``name`` which is the name of the file, and
``content`` which is an object containing the file's contents. The ``content`` which is an object containing the file's contents. The
optional ``save`` argument controls whether or not the model instance is optional ``save`` argument controls whether or not the model instance is
saved after the file associated with this field has been altered. Defaults to saved after the file associated with this field has been altered. Defaults to
``True``. ``True``.
@ -1230,14 +1230,14 @@ directory on the filesystem. Has some special arguments, of which the first is
.. attribute:: FilePathField.allow_files .. attribute:: FilePathField.allow_files
Optional. Either ``True`` or ``False``. Default is ``True``. Specifies Optional. Either ``True`` or ``False``. Default is ``True``. Specifies
whether files in the specified location should be included. Either this or whether files in the specified location should be included. Either this or
:attr:`~FilePathField.allow_folders` must be ``True``. :attr:`~FilePathField.allow_folders` must be ``True``.
.. attribute:: FilePathField.allow_folders .. attribute:: FilePathField.allow_folders
Optional. Either ``True`` or ``False``. Default is ``False``. Specifies Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
whether folders in the specified location should be included. Either this whether folders in the specified location should be included. Either this
or :attr:`~FilePathField.allow_files` must be ``True``. or :attr:`~FilePathField.allow_files` must be ``True``.
The one potential gotcha is that :attr:`~FilePathField.match` applies to the The one potential gotcha is that :attr:`~FilePathField.match` applies to the
@ -1528,7 +1528,7 @@ default length of 50.
Implies setting :attr:`Field.db_index` to ``True``. Implies setting :attr:`Field.db_index` to ``True``.
It is often useful to automatically prepopulate a SlugField based on the value It is often useful to automatically prepopulate a SlugField based on the value
of some other value. You can do this automatically in the admin using of some other value. You can do this automatically in the admin using
:attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`. :attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.
It uses :class:`~django.core.validators.validate_slug` or It uses :class:`~django.core.validators.validate_slug` or
@ -1681,7 +1681,7 @@ See :attr:`ForeignKey.on_delete` for details on the second positional
argument. argument.
A database index is automatically created on the ``ForeignKey``. You can A database index is automatically created on the ``ForeignKey``. You can
disable this by setting :attr:`~Field.db_index` to ``False``. You may want to disable this by setting :attr:`~Field.db_index` to ``False``. You may want to
avoid the overhead of an index if you are creating a foreign key for avoid the overhead of an index if you are creating a foreign key for
consistency rather than joins, or if you will be creating an alternative index consistency rather than joins, or if you will be creating an alternative index
like a partial or multiple column index. like a partial or multiple column index.

View File

@ -959,7 +959,7 @@ Examples:
.. method:: all() .. method:: all()
Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass). This Returns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass). This
can be useful in situations where you might want to pass in either a model can be useful in situations where you might want to pass in either a model
manager or a ``QuerySet`` and do further filtering on the result. After calling manager or a ``QuerySet`` and do further filtering on the result. After calling
``all()`` on either object, you'll definitely have a ``QuerySet`` to work with. ``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.
@ -1562,7 +1562,7 @@ of the arguments is required, but you should use at least one of them.
* ``select`` * ``select``
The ``select`` argument lets you put extra fields in the ``SELECT`` The ``select`` argument lets you put extra fields in the ``SELECT``
clause. It should be a dictionary mapping attribute names to SQL clause. It should be a dictionary mapping attribute names to SQL
clauses to use to calculate that attribute. clauses to use to calculate that attribute.
Example:: Example::
@ -1895,7 +1895,7 @@ are in your ``only()`` call.
.. method:: using(alias) .. method:: using(alias)
This method is for controlling which database the ``QuerySet`` will be This method is for controlling which database the ``QuerySet`` will be
evaluated against if you are using more than one database. The only argument evaluated against if you are using more than one database. The only argument
this method takes is the alias of a database, as defined in this method takes is the alias of a database, as defined in
:setting:`DATABASES`. :setting:`DATABASES`.

View File

@ -58,7 +58,7 @@ For examples, see the :doc:`Pagination topic guide </topics/pagination>`.
.. attribute:: Paginator.allow_empty_first_page .. attribute:: Paginator.allow_empty_first_page
Optional. Whether or not the first page is allowed to be empty. If Optional. Whether or not the first page is allowed to be empty. If
``False`` and ``object_list`` is empty, then an ``EmptyPage`` error will ``False`` and ``object_list`` is empty, then an ``EmptyPage`` error will
be raised. be raised.

View File

@ -1255,7 +1255,7 @@ using non-dict objects in JSON-encoded response.
<https://262.ecma-international.org/5.1/#sec-11.1.4>`_ it was possible to <https://262.ecma-international.org/5.1/#sec-11.1.4>`_ it was possible to
poison the JavaScript ``Array`` constructor. For this reason, Django does poison the JavaScript ``Array`` constructor. For this reason, Django does
not allow passing non-dict objects to the not allow passing non-dict objects to the
:class:`~django.http.JsonResponse` constructor by default. However, most :class:`~django.http.JsonResponse` constructor by default. However, most
modern browsers implement ECMAScript 5 which removes this attack vector. modern browsers implement ECMAScript 5 which removes this attack vector.
Therefore it is possible to disable this security precaution. Therefore it is possible to disable this security precaution.

View File

@ -311,9 +311,9 @@ keep the cookies in-memory instead of on persistent storage.
Default: ``None`` Default: ``None``
The domain to be used when setting the CSRF cookie. This can be useful for The domain to be used when setting the CSRF cookie. This can be useful for
easily allowing cross-subdomain requests to be excluded from the normal cross easily allowing cross-subdomain requests to be excluded from the normal cross
site request forgery protection. It should be set to a string such as site request forgery protection. It should be set to a string such as
``".example.com"`` to allow a POST request from a form on one subdomain to be ``".example.com"`` to allow a POST request from a form on one subdomain to be
accepted by a view served from another subdomain. accepted by a view served from another subdomain.

View File

@ -40,8 +40,9 @@ model system.
methods for these signals to be sent. methods for these signals to be sent.
Note also that Django stores signal handlers as weak references by default, 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 so if your handler is a local function, it may be garbage collected. To
prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`. prevent this, pass ``weak=False`` when you call the signal's
:meth:`~django.dispatch.Signal.connect`.
.. note:: .. note::
@ -687,7 +688,7 @@ initiated.
:module: :module:
Sent when the database wrapper makes the initial connection to the Sent when the database wrapper makes the initial connection to the
database. This is particularly useful if you'd like to send any post database. This is particularly useful if you'd like to send any post
connection commands to the SQL backend. connection commands to the SQL backend.
Arguments sent with this signal: Arguments sent with this signal:

View File

@ -368,7 +368,7 @@ straight lookups. Here are some things to keep in mind:
To prevent this, set an ``alters_data`` attribute on the callable To prevent this, set an ``alters_data`` attribute on the callable
variable. The template system won't call a variable if it has variable. The template system won't call a variable if it has
``alters_data=True`` set, and will instead replace the variable with ``alters_data=True`` set, and will instead replace the variable with
``string_if_invalid``, unconditionally. The ``string_if_invalid``, unconditionally. The
dynamically-generated :meth:`~django.db.models.Model.delete` and dynamically-generated :meth:`~django.db.models.Model.delete` and
:meth:`~django.db.models.Model.save` methods on Django model objects get :meth:`~django.db.models.Model.save` methods on Django model objects get
``alters_data=True`` automatically. Example:: ``alters_data=True`` automatically. Example::
@ -381,8 +381,8 @@ straight lookups. Here are some things to keep in mind:
* Occasionally you may want to turn off this feature for other reasons, * Occasionally you may want to turn off this feature for other reasons,
and tell the template system to leave a variable uncalled no matter and tell the template system to leave a variable uncalled no matter
what. To do so, set a ``do_not_call_in_templates`` attribute on the what. To do so, set a ``do_not_call_in_templates`` attribute on the
callable with the value ``True``. The template system then will act as callable with the value ``True``. The template system then will act as
if your variable is not callable (allowing you to access attributes of if your variable is not callable (allowing you to access attributes of
the callable, for example). the callable, for example).
@ -666,7 +666,7 @@ processors::
] ]
In addition to these, :class:`RequestContext` always enables In addition to these, :class:`RequestContext` always enables
``'django.template.context_processors.csrf'``. This is a security related ``'django.template.context_processors.csrf'``. This is a security related
context processor required by the admin and other contrib apps, and, in case context processor required by the admin and other contrib apps, and, in case
of accidental misconfiguration, it is deliberately hardcoded in and cannot be of accidental misconfiguration, it is deliberately hardcoded in and cannot be
turned off in the ``context_processors`` option. turned off in the ``context_processors`` option.
@ -1100,7 +1100,7 @@ Loader methods
source. source.
For example, the filesystem loader may receive ``'index.html'`` as a For example, the filesystem loader may receive ``'index.html'`` as a
``template_name`` argument. This method would yield origins for the ``template_name`` argument. This method would yield origins for the
full path of ``index.html`` as it appears in each template directory full path of ``index.html`` as it appears in each template directory
the loader looks at. the loader looks at.

View File

@ -137,7 +137,7 @@ this:
</tr> </tr>
{% endfor %} {% endfor %}
Variables included in the cycle will be escaped. You can disable auto-escaping Variables included in the cycle will be escaped. You can disable auto-escaping
with: with:
.. code-block:: html+django .. code-block:: html+django
@ -1754,32 +1754,32 @@ Format character Description Example output
leading zeros. leading zeros.
``j`` Day of the month without leading ``'1'`` to ``'31'`` ``j`` Day of the month without leading ``'1'`` to ``'31'``
zeros. zeros.
``D`` Day of the week, textual, 3 letters. ``'Fri'`` ``D`` Day of the week, textual, 3 letters. ``'Fri'``
``l`` Day of the week, textual, long. ``'Friday'`` ``l`` Day of the week, textual, long. ``'Friday'``
``S`` English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'`` ``S`` English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
month, 2 characters. month, 2 characters.
``w`` Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday) ``w`` Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
leading zeros. leading zeros.
``z`` Day of the year. ``1`` to ``366`` ``z`` Day of the year. ``1`` to ``366``
**Week** **Week**
``W`` ISO-8601 week number of year, with ``1``, ``53`` ``W`` ISO-8601 week number of year, with ``1``, ``53``
weeks starting on Monday. weeks starting on Monday.
**Month** **Month**
``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'`` ``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
``n`` Month without leading zeros. ``'1'`` to ``'12'`` ``n`` Month without leading zeros. ``'1'`` to ``'12'``
``M`` Month, textual, 3 letters. ``'Jan'`` ``M`` Month, textual, 3 letters. ``'Jan'``
``b`` Month, textual, 3 letters, lowercase. ``'jan'`` ``b`` Month, textual, 3 letters, lowercase. ``'jan'``
``E`` Month, locale specific alternative ``E`` Month, locale specific alternative
representation usually used for long representation usually used for long
date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``) date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)
``F`` Month, textual, long. ``'January'`` ``F`` Month, textual, long. ``'January'``
``N`` Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'`` ``N`` Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
style. Proprietary extension. 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** **Year**
``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'`` ``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'``
``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'`` ``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'``
``L`` Boolean for whether it's a leap year. ``True`` or ``False`` ``L`` Boolean for whether it's a leap year. ``True`` or ``False``
``o`` ISO-8601 week-numbering year, ``'1999'`` ``o`` ISO-8601 week-numbering year, ``'1999'``
corresponding to the ISO-8601 week corresponding to the ISO-8601 week
number (W) which uses leap weeks. See Y number (W) which uses leap weeks. See Y
@ -1789,16 +1789,16 @@ Format character Description Example output
zeros. zeros.
``G`` Hour, 24-hour format without leading ``'0'`` to ``'23'`` ``G`` Hour, 24-hour format without leading ``'0'`` to ``'23'``
zeros. zeros.
``h`` Hour, 12-hour format. ``'01'`` to ``'12'`` ``h`` Hour, 12-hour format. ``'01'`` to ``'12'``
``H`` Hour, 24-hour format. ``'00'`` to ``'23'`` ``H`` Hour, 24-hour format. ``'00'`` to ``'23'``
``i`` Minutes. ``'00'`` to ``'59'`` ``i`` Minutes. ``'00'`` to ``'59'``
``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'`` ``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
``u`` Microseconds. ``000000`` to ``999999`` ``u`` Microseconds. ``000000`` to ``999999``
``a`` ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'`` ``a`` ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
this is slightly different than PHP's this is slightly different than PHP's
output, because this includes periods output, because this includes periods
to match Associated Press style.) 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'`` ``f`` Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
with minutes left off if they're zero. with minutes left off if they're zero.
Proprietary extension. Proprietary extension.
@ -1813,8 +1813,8 @@ Format character Description Example output
depending on the datetime. depending on the datetime.
``I`` Daylight saving time, whether it's in ``'1'`` or ``'0'`` ``I`` Daylight saving time, whether it's in ``'1'`` or ``'0'``
effect or not. effect or not.
``O`` Difference to Greenwich time in hours. ``'+0200'`` ``O`` Difference to Greenwich time in hours. ``'+0200'``
``T`` Time zone of this machine. ``'EST'``, ``'MDT'`` ``T`` Time zone of this machine. ``'EST'``, ``'MDT'``
``Z`` Time zone offset in seconds. The ``-43200`` to ``43200`` ``Z`` Time zone offset in seconds. The ``-43200`` to ``43200``
offset for timezones west of UTC is offset for timezones west of UTC is
always negative, and for those east of always negative, and for those east of

View File

@ -208,7 +208,7 @@ you a taste of what's available, here are some of the more commonly used
tags: tags:
:ttag:`for` :ttag:`for`
Loop over each item in an array. For example, to display a list of athletes Loop over each item in an array. For example, to display a list of athletes
provided in ``athlete_list``: provided in ``athlete_list``:
.. code-block:: html+django .. code-block:: html+django

View File

@ -282,7 +282,7 @@ The functions defined in this module share the following properties:
:class:`~pathlib.Path`. :class:`~pathlib.Path`.
This method will encode certain characters that would normally be This method will encode certain characters that would normally be
recognized as special characters for URIs. Note that this method does not recognized as special characters for URIs. Note that this method does not
encode the ' character, as it is a valid character within URIs. See encode the ' character, as it is a valid character within URIs. See
``encodeURIComponent()`` JavaScript function for more details. ``encodeURIComponent()`` JavaScript function for more details.

View File

@ -133,7 +133,7 @@ New forms library
``django.newforms`` is Django's new form-handling library. It's a ``django.newforms`` is Django's new form-handling library. It's a
replacement for ``django.forms``, the old form/manipulator/validation replacement for ``django.forms``, the old form/manipulator/validation
framework. Both APIs are available in 0.96, but over the next two framework. Both APIs are available in 0.96, but over the next two
releases we plan to switch completely to the new forms system, and releases we plan to switch completely to the new forms system, and
deprecate and remove the old system. deprecate and remove the old system.
@ -142,7 +142,7 @@ There are three elements to this transition:
* We've copied the current ``django.forms`` to * We've copied the current ``django.forms`` to
``django.oldforms``. This allows you to upgrade your code *now* ``django.oldforms``. This allows you to upgrade your code *now*
rather than waiting for the backwards-incompatible change and rather than waiting for the backwards-incompatible change and
rushing to fix your code after the fact. Just change your rushing to fix your code after the fact. Just change your
import statements like this:: import statements like this::
from django import forms # 0.95-style from django import forms # 0.95-style

View File

@ -23,9 +23,9 @@ Test runner exit status code
The exit status code of the test runners (``tests/runtests.py`` and ``python The exit status code of the test runners (``tests/runtests.py`` and ``python
manage.py test``) no longer represents the number of failed tests, since a manage.py test``) no longer represents the number of failed tests, since a
failure of 256 or more tests resulted in a wrong exit status code. The exit failure of 256 or more tests resulted in a wrong exit status code. The exit
status code for the test runner is now 0 for success (no failing tests) and 1 status code for the test runner is now 0 for success (no failing tests) and 1
for any number of test failures. If needed, the number of test failures can be for any number of test failures. If needed, the number of test failures can be
found at the end of the test runner's output. found at the end of the test runner's output.
Cookie encoding Cookie encoding
@ -34,7 +34,7 @@ Cookie encoding
To fix bugs with cookies in Internet Explorer, Safari, and possibly other To fix bugs with cookies in Internet Explorer, Safari, and possibly other
browsers, our encoding of cookie values was changed so that the characters browsers, our encoding of cookie values was changed so that the characters
comma and semi-colon are treated as non-safe characters, and are therefore comma and semi-colon are treated as non-safe characters, and are therefore
encoded as ``\054`` and ``\073`` respectively. This could produce backwards encoded as ``\054`` and ``\073`` respectively. This could produce backwards
incompatibilities, especially if you are storing comma or semi-colon in incompatibilities, especially if you are storing comma or semi-colon in
cookies and have JavaScript code that parses and manipulates cookie values cookies and have JavaScript code that parses and manipulates cookie values
client-side. client-side.

View File

@ -581,7 +581,7 @@ to generate and apply a database migration for your user model.
We considered an increase to 254 characters to more easily allow the use of We considered an increase to 254 characters to more easily allow the use of
email addresses (which are limited to 254 characters) as usernames but rejected email addresses (which are limited to 254 characters) as usernames but rejected
it due to a MySQL limitation. When using the ``utf8mb4`` encoding (recommended it due to a MySQL limitation. When using the ``utf8mb4`` encoding (recommended
for proper Unicode support), MySQL can only create unique indexes with 191 for proper Unicode support), MySQL can only create unique indexes with 191
characters by default. Therefore, if you need a longer length, please use a characters by default. Therefore, if you need a longer length, please use a
custom user model. custom user model.
@ -850,7 +850,7 @@ Miscellaneous
* The ``base_field`` attribute of * The ``base_field`` attribute of
:class:`~django.contrib.postgres.fields.RangeField` is now a type of field, :class:`~django.contrib.postgres.fields.RangeField` is now a type of field,
not an instance of a field. If you have created a custom subclass of not an instance of a field. If you have created a custom subclass of
:class:`~django.contrib.postgres.fields.RangeField`, you should change the :class:`~django.contrib.postgres.fields.RangeField`, you should change the
``base_field`` attribute. ``base_field`` attribute.

View File

@ -7,7 +7,7 @@ Django 1.2.6 release notes
Welcome to Django 1.2.6! Welcome to Django 1.2.6!
This is the sixth bugfix/security release in the Django 1.2 series, fixing This is the sixth bugfix/security release in the Django 1.2 series, fixing
several security issues present in Django 1.2.5. Django 1.2.6 is a several security issues present in Django 1.2.5. Django 1.2.6 is a
recommended upgrade for all users of any Django release in the 1.2.X series. recommended upgrade for all users of any Django release in the 1.2.X series.
For a full list of issues addressed in this release, see the `security For a full list of issues addressed in this release, see the `security

View File

@ -173,7 +173,7 @@ Permissions for anonymous users
If you provide a custom auth backend with ``supports_anonymous_user`` set to If you provide a custom auth backend with ``supports_anonymous_user`` set to
``True``, AnonymousUser will check the backend for permissions, just like ``True``, AnonymousUser will check the backend for permissions, just like
User already did. This is useful for centralizing permission handling - apps User already did. This is useful for centralizing permission handling - apps
can always delegate the question of whether something is allowed or not to can always delegate the question of whether something is allowed or not to
the authorization/authentication backend. See the :doc:`authentication the authorization/authentication backend. See the :doc:`authentication
docs </topics/auth/index>` for more details. docs </topics/auth/index>` for more details.
@ -276,7 +276,7 @@ untouched up to and including the Django 1.3 release.
If you have developed your own custom template loaders we suggest to consider If you have developed your own custom template loaders we suggest to consider
porting them to a class-based implementation because the code for backwards porting them to a class-based implementation because the code for backwards
compatibility with function-based loaders starts its deprecation process in compatibility with function-based loaders starts its deprecation process in
Django 1.2 and will be removed in Django 1.4. There is a description of the Django 1.2 and will be removed in Django 1.4. There is a description of the
API these loader classes must implement in the template API reference and you API these loader classes must implement in the template API reference and you
can also examine the source code of the loaders shipped with Django. can also examine the source code of the loaders shipped with Django.
@ -342,7 +342,7 @@ GeoDjango
--------- ---------
The most significant new feature for :doc:`GeoDjango </ref/contrib/gis/index>` The most significant new feature for :doc:`GeoDjango </ref/contrib/gis/index>`
in 1.2 is support for multiple spatial databases. As a result, in 1.2 is support for multiple spatial databases. As a result,
the following :ref:`spatial database backends <spatial-backends>` the following :ref:`spatial database backends <spatial-backends>`
are now included: are now included:
@ -680,7 +680,7 @@ Cookie encoding
To fix bugs with cookies in Internet Explorer, Safari, and possibly To fix bugs with cookies in Internet Explorer, Safari, and possibly
other browsers, our encoding of cookie values was changed so that the other browsers, our encoding of cookie values was changed so that the
comma and semicolon are treated as non-safe characters, and are comma and semicolon are treated as non-safe characters, and are
therefore encoded as ``\054`` and ``\073`` respectively. This could therefore encoded as ``\054`` and ``\073`` respectively. This could
produce backwards incompatibilities, especially if you are storing produce backwards incompatibilities, especially if you are storing
comma or semi-colon in cookies and have JavaScript code that parses comma or semi-colon in cookies and have JavaScript code that parses
and manipulates cookie values client-side. and manipulates cookie values client-side.
@ -702,7 +702,7 @@ In previous versions of Django, a model's ``BooleanField`` under MySQL
would return its value as either ``1`` or ``0``, instead of ``True`` would return its value as either ``1`` or ``0``, instead of ``True``
or ``False``; for most people this wasn't a problem because ``bool`` or ``False``; for most people this wasn't a problem because ``bool``
is a subclass of ``int`` in Python. In Django 1.2, however, is a subclass of ``int`` in Python. In Django 1.2, however,
``BooleanField`` on MySQL correctly returns a real ``bool``. The only ``BooleanField`` on MySQL correctly returns a real ``bool``. The only
time this should ever be an issue is if you were expecting the time this should ever be an issue is if you were expecting the
``repr`` of a ``BooleanField`` to print ``1`` or ``0``. ``repr`` of a ``BooleanField`` to print ``1`` or ``0``.
@ -1094,10 +1094,10 @@ GeoDjango
--------- ---------
To allow support for multiple databases, the GeoDjango database internals were To allow support for multiple databases, the GeoDjango database internals were
changed substantially. The largest backwards-incompatible change is that changed substantially. The largest backwards-incompatible change is that
the module ``django.contrib.gis.db.backend`` was renamed to the module ``django.contrib.gis.db.backend`` was renamed to
:mod:`django.contrib.gis.db.backends`, where the full-fledged :mod:`django.contrib.gis.db.backends`, where the full-fledged
:ref:`spatial database backends <spatial-backends>` now exist. The :ref:`spatial database backends <spatial-backends>` now exist. The
following sections provide information on the most-popular APIs that following sections provide information on the most-popular APIs that
were affected by these changes. were affected by these changes.
@ -1107,7 +1107,7 @@ were affected by these changes.
Prior to the creation of the separate spatial backends, the Prior to the creation of the separate spatial backends, the
``django.contrib.gis.db.backend.SpatialBackend`` object was ``django.contrib.gis.db.backend.SpatialBackend`` object was
provided as an abstraction to introspect on the capabilities of provided as an abstraction to introspect on the capabilities of
the spatial database. All of the attributes and routines provided by the spatial database. All of the attributes and routines provided by
``SpatialBackend`` are now a part of the ``ops`` attribute of the ``SpatialBackend`` are now a part of the ``ops`` attribute of the
database backend. database backend.
@ -1147,7 +1147,7 @@ is using a supported spatial database backend.
Because the table structure of the OGC spatial metadata tables Because the table structure of the OGC spatial metadata tables
differs across spatial databases, the ``SpatialRefSys`` and differs across spatial databases, the ``SpatialRefSys`` and
``GeometryColumns`` models can no longer be associated with ``GeometryColumns`` models can no longer be associated with
the ``gis`` application name. Thus, no models will be returned the ``gis`` application name. Thus, no models will be returned
when using the ``get_models`` method in the following example: when using the ``get_models`` method in the following example:
.. code-block:: pycon .. code-block:: pycon

View File

@ -7,7 +7,7 @@ Django 1.3.1 release notes
Welcome to Django 1.3.1! Welcome to Django 1.3.1!
This is the first security release in the Django 1.3 series, fixing several This is the first security release in the Django 1.3 series, fixing several
security issues in Django 1.3. Django 1.3.1 is a recommended upgrade for security issues in Django 1.3. Django 1.3.1 is a recommended upgrade for
all users of Django 1.3. all users of Django 1.3.
For a full list of issues addressed in this release, see the `security For a full list of issues addressed in this release, see the `security

View File

@ -78,7 +78,7 @@ Logging
------- -------
Django 1.3 adds framework-level support for Python's ``logging`` Django 1.3 adds framework-level support for Python's ``logging``
module. This means you can now easily configure and control logging module. This means you can now easily configure and control logging
as part of your Django project. A number of logging handlers and as part of your Django project. A number of logging handlers and
logging calls have been added to Django's own code as well -- most logging calls have been added to Django's own code as well -- most
notably, the error emails sent on an HTTP 500 server error are now notably, the error emails sent on an HTTP 500 server error are now
@ -236,7 +236,7 @@ Permissions for inactive users
If you provide a custom auth backend with ``supports_inactive_user`` If you provide a custom auth backend with ``supports_inactive_user``
set to ``True``, an inactive ``User`` instance will check the backend set to ``True``, an inactive ``User`` instance will check the backend
for permissions. This is useful for further centralizing the for permissions. This is useful for further centralizing the
permission handling. See the :doc:`authentication docs </topics/auth/index>` permission handling. See the :doc:`authentication docs </topics/auth/index>`
for more details. for more details.
@ -808,9 +808,9 @@ GeoDjango
* Previously, calling * Previously, calling
:meth:`~django.contrib.gis.geos.GEOSGeometry.transform` would :meth:`~django.contrib.gis.geos.GEOSGeometry.transform` would
silently do nothing when GDAL wasn't available. Now, a silently do nothing when GDAL wasn't available. Now, a
:class:`~django.contrib.gis.geos.GEOSException` is properly raised :class:`~django.contrib.gis.geos.GEOSException` is properly raised
to indicate possible faulty application code. A warning is now to indicate possible faulty application code. A warning is now
raised if :meth:`~django.contrib.gis.geos.GEOSGeometry.transform` is raised if :meth:`~django.contrib.gis.geos.GEOSGeometry.transform` is
called when the SRID of the geometry is less than 0 or ``None``. called when the SRID of the geometry is less than 0 or ``None``.

View File

@ -389,7 +389,7 @@ Context in year archive class-based views
For consistency with the other date-based generic views, For consistency with the other date-based generic views,
:class:`~django.views.generic.dates.YearArchiveView` now passes ``year`` in :class:`~django.views.generic.dates.YearArchiveView` now passes ``year`` in
the context as a :class:`datetime.date` rather than a string. If you are the context as a :class:`datetime.date` rather than a string. If you are
using ``{{ year }}`` in your templates, you must replace it with ``{{ using ``{{ year }}`` in your templates, you must replace it with ``{{
year|date:"Y" }}``. year|date:"Y" }}``.

View File

@ -248,8 +248,8 @@ Minor features
* The ``validate_max`` parameter was added to ``BaseFormSet`` and * The ``validate_max`` parameter was added to ``BaseFormSet`` and
:func:`~django.forms.formsets.formset_factory`, and ``ModelForm`` and inline :func:`~django.forms.formsets.formset_factory`, and ``ModelForm`` and inline
versions of the same. The behavior of validation for formsets with versions of the same. The behavior of validation for formsets with
``max_num`` was clarified. The previously undocumented behavior that ``max_num`` was clarified. The previously undocumented behavior that
hardened formsets against memory exhaustion attacks was documented, hardened formsets against memory exhaustion attacks was documented,
and the undocumented limit of the higher of 1000 or ``max_num`` forms and the undocumented limit of the higher of 1000 or ``max_num`` forms
was changed so it is always 1000 more than ``max_num``. was changed so it is always 1000 more than ``max_num``.

View File

@ -1668,7 +1668,7 @@ Model ``Field.related``
----------------------- -----------------------
Private attribute ``django.db.models.Field.related`` is deprecated in favor Private attribute ``django.db.models.Field.related`` is deprecated in favor
of ``Field.rel``. The latter is an instance of of ``Field.rel``. The latter is an instance of
``django.db.models.fields.related.ForeignObjectRel`` which replaces ``django.db.models.fields.related.ForeignObjectRel`` which replaces
``django.db.models.related.RelatedObject``. The ``django.db.models.related`` ``django.db.models.related.RelatedObject``. The ``django.db.models.related``
module has been removed and the ``Field.related`` attribute will be removed in module has been removed and the ``Field.related`` attribute will be removed in

View File

@ -357,7 +357,7 @@ Forms
* :class:`~django.forms.CharField` now accepts a * :class:`~django.forms.CharField` now accepts a
:attr:`~django.forms.CharField.strip` argument to strip input data of leading :attr:`~django.forms.CharField.strip` argument to strip input data of leading
and trailing whitespace. As this defaults to ``True`` this is different and trailing whitespace. As this defaults to ``True`` this is different
behavior from previous releases. behavior from previous releases.
* Form fields now support the :attr:`~django.forms.Field.disabled` argument, * Form fields now support the :attr:`~django.forms.Field.disabled` argument,

View File

@ -20,7 +20,7 @@ Python compatibility
==================== ====================
Django 2.1 supports Python 3.5, 3.6, and 3.7. Django 2.0 is the last version to Django 2.1 supports Python 3.5, 3.6, and 3.7. Django 2.0 is the last version to
support Python 3.4. We **highly recommend** and only officially support the support Python 3.4. We **highly recommend** and only officially support the
latest release of each series. latest release of each series.
.. _whats-new-2.1: .. _whats-new-2.1:

View File

@ -616,7 +616,7 @@ password resets. You must then provide some key implementation details:
.. attribute:: is_active .. attribute:: is_active
A boolean attribute that indicates whether the user is considered A boolean attribute that indicates whether the user is considered
"active". This attribute is provided as an attribute on "active". This attribute is provided as an attribute on
``AbstractBaseUser`` defaulting to ``True``. How you choose to ``AbstractBaseUser`` defaulting to ``True``. How you choose to
implement it will depend on the details of your chosen auth backends. implement it will depend on the details of your chosen auth backends.
See the documentation of the :attr:`is_active attribute on the built-in See the documentation of the :attr:`is_active attribute on the built-in
@ -708,7 +708,7 @@ The following attributes and methods are available on any subclass of
.. method:: models.AbstractBaseUser.set_unusable_password() .. method:: models.AbstractBaseUser.set_unusable_password()
Marks the user as having no password set. This isn't the same as Marks the user as having no password set. This isn't the same as
having a blank string for a password. having a blank string for a password.
:meth:`~django.contrib.auth.models.AbstractBaseUser.check_password` for this user :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password` for this user
will never return ``True``. Doesn't save the will never return ``True``. Doesn't save the

View File

@ -873,7 +873,7 @@ the login page or shown an HTTP 403 Forbidden response, depending on the
.. attribute:: login_url .. attribute:: login_url
Default return value for :meth:`get_login_url`. Defaults to ``None`` Default return value for :meth:`get_login_url`. Defaults to ``None``
in which case :meth:`get_login_url` falls back to in which case :meth:`get_login_url` falls back to
:setting:`settings.LOGIN_URL <LOGIN_URL>`. :setting:`settings.LOGIN_URL <LOGIN_URL>`.
@ -891,7 +891,7 @@ the login page or shown an HTTP 403 Forbidden response, depending on the
If this attribute is set to ``True``, a If this attribute is set to ``True``, a
:class:`~django.core.exceptions.PermissionDenied` exception is raised :class:`~django.core.exceptions.PermissionDenied` exception is raised
when the conditions are not met. When ``False`` (the default), when the conditions are not met. When ``False`` (the default),
anonymous users are redirected to the login page. anonymous users are redirected to the login page.
.. method:: get_login_url() .. method:: get_login_url()

View File

@ -33,7 +33,7 @@ The :attr:`~django.contrib.auth.models.User.password` attribute of a
Those are the components used for storing a User's password, separated by the Those are the components used for storing a User's password, separated by the
dollar-sign character and consist of: the hashing algorithm, the number of dollar-sign character and consist of: the hashing algorithm, the number of
algorithm iterations (work factor), the random salt, and the resulting password algorithm iterations (work factor), the random salt, and the resulting password
hash. The algorithm is one of a number of one-way hashing or password storage hash. The algorithm is one of a number of one-way hashing or password storage
algorithms Django can use; see below. Iterations describe the number of times algorithms Django can use; see below. Iterations describe the number of times
the algorithm is run over the hash. Salt is the random seed used and the hash the algorithm is run over the hash. Salt is the random seed used and the hash
is the result of the one-way function. is the result of the one-way function.
@ -46,7 +46,7 @@ amounts of computing time to break.
However, depending on your requirements, you may choose a different However, depending on your requirements, you may choose a different
algorithm, or even use a custom algorithm to match your specific algorithm, or even use a custom algorithm to match your specific
security situation. Again, most users shouldn't need to do this -- if security situation. Again, most users shouldn't need to do this -- if
you're not sure, you probably don't. If you do, please read on: you're not sure, you probably don't. If you do, please read on:
Django chooses the algorithm to use by consulting the Django chooses the algorithm to use by consulting the
:setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm :setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm

View File

@ -710,7 +710,7 @@ want::
You can also override the cache prefix on a per-view basis. ``cache_page`` You can also override the cache prefix on a per-view basis. ``cache_page``
takes an optional keyword argument, ``key_prefix``, takes an optional keyword argument, ``key_prefix``,
which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`
setting for the middleware. It can be used like this:: setting for the middleware. It can be used like this::
@cache_page(60 * 15, key_prefix="site1") @cache_page(60 * 15, key_prefix="site1")
def my_view(request): ... def my_view(request): ...
@ -860,7 +860,7 @@ cache the entire result (since some of the data changes often), but you'd still
want to cache the results that rarely change. want to cache the results that rarely change.
For cases like this, Django exposes a low-level cache API. You can use this API For cases like this, Django exposes a low-level cache API. You can use this API
to store objects in the cache with any level of granularity you like. You can to store objects in the cache with any level of granularity you like. You can
cache any Python object that can be pickled safely: strings, dictionaries, cache any Python object that can be pickled safely: strings, dictionaries,
lists of model objects, and so forth. (Most common Python objects can be lists of model objects, and so forth. (Most common Python objects can be
pickled; refer to the Python documentation for more information about pickled; refer to the Python documentation for more information about
@ -1052,7 +1052,7 @@ of keys to be cleared:
.. method:: cache.clear() .. method:: cache.clear()
Finally, if you want to delete all the keys in the cache, use Finally, if you want to delete all the keys in the cache, use
``cache.clear()``. Be careful with this; ``clear()`` will remove *everything* ``cache.clear()``. Be careful with this; ``clear()`` will remove *everything*
from the cache, not just the keys set by your application: from the cache, not just the keys set by your application:
.. code-block:: pycon .. code-block:: pycon
@ -1312,7 +1312,7 @@ expose incorrect or sensitive data to subsequent visitors to those pages.
For example, if you operate a web email system, then the contents of the For example, if you operate a web email system, then the contents of the
"inbox" page depend on which user is logged in. If an ISP blindly cached your "inbox" page depend on which user is logged in. If an ISP blindly cached your
site, then the first user who logged in through that ISP would have their site, then the first user who logged in through that ISP would have their
user-specific inbox page cached for subsequent visitors to the site. That's user-specific inbox page cached for subsequent visitors to the site. That's
not cool. not cool.
Fortunately, HTTP provides a solution to this problem. A number of HTTP headers Fortunately, HTTP provides a solution to this problem. A number of HTTP headers

View File

@ -306,8 +306,8 @@ We'll deal with this problem in the next section.
.. note:: .. note::
If you get a 404 when requesting ``/books/acme/``, check to ensure you If you get a 404 when requesting ``/books/acme/``, check to ensure you
actually have a Publisher with the name 'ACME Publishing'. Generic actually have a Publisher with the name 'ACME Publishing'. Generic
views have an ``allow_empty`` parameter for this case. See the views have an ``allow_empty`` parameter for this case. See the
:doc:`class-based-views reference</ref/class-based-views/index>` for more :doc:`class-based-views reference</ref/class-based-views/index>` for more
details. details.

View File

@ -65,7 +65,7 @@ Notes:
Model forms Model forms
=========== ===========
Generic views really shine when working with models. These generic Generic views really shine when working with models. These generic
views will automatically create a :class:`~django.forms.ModelForm`, so long as views will automatically create a :class:`~django.forms.ModelForm`, so long as
they can work out which model class to use: they can work out which model class to use:
@ -78,7 +78,7 @@ they can work out which model class to use:
Model form views provide a Model form views provide a
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid` implementation :meth:`~django.views.generic.edit.ModelFormMixin.form_valid` implementation
that saves the model automatically. You can override this if you have any that saves the model automatically. You can override this if you have any
special requirements; see below for examples. special requirements; see below for examples.
You don't even need to provide a ``success_url`` for You don't even need to provide a ``success_url`` for

View File

@ -132,7 +132,7 @@ And the view::
If the view is accessed from a ``GET`` request, an object list is returned in If the view is accessed from a ``GET`` request, an object list is returned in
the response (using the ``book_list.html`` template). But if the client issues the response (using the ``book_list.html`` template). But if the client issues
a ``HEAD`` request, the response has an empty body and the ``Last-Modified`` a ``HEAD`` request, the response has an empty body and the ``Last-Modified``
header indicates when the most recent book was published. Based on this header indicates when the most recent book was published. Based on this
information, the client may or may not download the full object list. information, the client may or may not download the full object list.
.. _async-class-based-views: .. _async-class-based-views:

View File

@ -22,7 +22,7 @@ last modification time it was sent, or either :rfc:`If-Match
containing the last ``ETag`` it was sent. If the current version of the page containing the last ``ETag`` it was sent. If the current version of the page
matches the ``ETag`` sent by the client, or if the resource has not been matches the ``ETag`` sent by the client, or if the resource has not been
modified, a 304 status code can be sent back, instead of a full response, modified, a 304 status code can be sent back, instead of a full response,
telling the client that nothing has changed. Depending on the header, if the telling the client that nothing has changed. Depending on the header, if the
page has been modified or does not match the ``ETag`` sent by the client, a 412 page has been modified or does not match the ``ETag`` sent by the client, a 412
status code (Precondition Failed) may be returned. status code (Precondition Failed) may be returned.

View File

@ -106,7 +106,7 @@ Returns a context manager which, when entered, installs a wrapper around
database query executions, and when exited, removes the wrapper. The wrapper is database query executions, and when exited, removes the wrapper. The wrapper is
installed on the thread-local connection object. installed on the thread-local connection object.
``wrapper`` is a callable taking five arguments. It is called for every query ``wrapper`` is a callable taking five arguments. It is called for every query
execution in the scope of the context manager, with arguments ``execute``, execution in the scope of the context manager, with arguments ``execute``,
``sql``, ``params``, ``many``, and ``context`` as described above. It's ``sql``, ``params``, ``many``, and ``context`` as described above. It's
expected to call ``execute(sql, params, many, context)`` and return the return expected to call ``execute(sql, params, many, context)`` and return the return

View File

@ -1300,7 +1300,7 @@ the parent, it's possible to move from the parent down to the child,
as in the above example. However, this uses up the name that is the as in the above example. However, this uses up the name that is the
default :attr:`~django.db.models.ForeignKey.related_name` value for default :attr:`~django.db.models.ForeignKey.related_name` value for
:class:`~django.db.models.ForeignKey` and :class:`~django.db.models.ForeignKey` and
:class:`~django.db.models.ManyToManyField` relations. If you :class:`~django.db.models.ManyToManyField` relations. If you
are putting those types of relations on a subclass of the parent model, you are putting those types of relations on a subclass of the parent model, you
**must** specify the :attr:`~django.db.models.ForeignKey.related_name` **must** specify the :attr:`~django.db.models.ForeignKey.related_name`
attribute on each such field. If you forget, Django will raise a validation attribute on each such field. If you forget, Django will raise a validation

View File

@ -900,7 +900,7 @@ reuse it:
When ``QuerySet``\s are not cached When ``QuerySet``\s are not cached
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Querysets do not always cache their results. When evaluating only *part* of Querysets do not always cache their results. When evaluating only *part* of
the queryset, the cache is checked, but if it is not populated then the items the queryset, the cache is checked, but if it is not populated then the items
returned by the subsequent query are not cached. Specifically, this means that returned by the subsequent query are not cached. Specifically, this means that
:ref:`limiting the queryset <limiting-querysets>` using an array slice or an :ref:`limiting the queryset <limiting-querysets>` using an array slice or an

View File

@ -540,7 +540,7 @@ rather than the functions described below, but they're still part of the
public API, and there's no plan to deprecate them. public API, and there's no plan to deprecate them.
Each of these functions takes a ``using`` argument which should be the name of Each of these functions takes a ``using`` argument which should be the name of
a database for which the behavior applies. If no ``using`` argument is a database for which the behavior applies. If no ``using`` argument is
provided then the ``"default"`` database is used. provided then the ``"default"`` database is used.
Savepoints are controlled by three functions in :mod:`django.db.transaction`: Savepoints are controlled by three functions in :mod:`django.db.transaction`:

View File

@ -139,9 +139,9 @@ A ``max_num`` value of ``None`` (the default) puts a high limit on the number
of forms displayed (1000). In practice this is equivalent to no limit. of forms displayed (1000). In practice this is equivalent to no limit.
By default, ``max_num`` only affects how many forms are displayed and does not By default, ``max_num`` only affects how many forms are displayed and does not
affect validation. If ``validate_max=True`` is passed to the affect validation. If ``validate_max=True`` is passed to the
:func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect :func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect
validation. See :ref:`validate_max`. validation. See :ref:`validate_max`.
.. _formsets-absolute-max: .. _formsets-absolute-max:
@ -695,7 +695,7 @@ model instances for deleted forms will be deleted when you call
``formset.save()``. ``formset.save()``.
If you call ``formset.save(commit=False)``, objects will not be deleted If you call ``formset.save(commit=False)``, objects will not be deleted
automatically. You'll need to call ``delete()`` on each of the automatically. You'll need to call ``delete()`` on each of the
:attr:`formset.deleted_objects :attr:`formset.deleted_objects
<django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete <django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete
them: them:

View File

@ -211,7 +211,7 @@ complete control over which files are inherited, and which are not.
If you need to perform some more sophisticated manipulation of asset If you need to perform some more sophisticated manipulation of asset
requirements, you can define the ``media`` property directly. This is requirements, you can define the ``media`` property directly. This is
done by defining a widget property that returns an instance of done by defining a widget property that returns an instance of
``forms.Media``. The constructor for ``forms.Media`` accepts ``css`` ``forms.Media``. The constructor for ``forms.Media`` accepts ``css``
and ``js`` keyword arguments in the same format as that used in a and ``js`` keyword arguments in the same format as that used in a
static media definition. static media definition.

View File

@ -410,7 +410,7 @@ you've manually saved the instance produced by the form, you can invoke
Calling ``save_m2m()`` is only required if you use ``save(commit=False)``. Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
When you use a ``save()`` on a form, all data -- including many-to-many data -- When you use a ``save()`` on a form, all data -- including many-to-many data --
is saved without the need for any additional method calls. For example: is saved without the need for any additional method calls. For example:
.. code-block:: pycon .. code-block:: pycon
@ -490,7 +490,7 @@ include that field.
Django will prevent any attempt to save an incomplete model, so if Django will prevent any attempt to save an incomplete model, so if
the model does not allow the missing fields to be empty, and does the model does not allow the missing fields to be empty, and does
not provide a default value for the missing fields, any attempt to not provide a default value for the missing fields, any attempt to
``save()`` a ``ModelForm`` with missing fields will fail. To ``save()`` a ``ModelForm`` with missing fields will fail. To
avoid this failure, you must instantiate your model with initial avoid this failure, you must instantiate your model with initial
values for the missing, but required fields:: values for the missing, but required fields::
@ -1107,7 +1107,7 @@ Overriding ``clean()`` on a ``ModelFormSet``
Just like with a ``ModelForm``, by default the ``clean()`` method of a Just like with a ``ModelForm``, by default the ``clean()`` method of a
``ModelFormSet`` will validate that none of the items in the formset violate ``ModelFormSet`` will validate that none of the items in the formset violate
the unique constraints on your model (either ``unique``, ``unique_together`` or the unique constraints on your model (either ``unique``, ``unique_together`` or
``unique_for_date|month|year``). If you want to override the ``clean()`` method ``unique_for_date|month|year``). If you want to override the ``clean()`` method
on a ``ModelFormSet`` and maintain this validation, you must call the parent on a ``ModelFormSet`` and maintain this validation, you must call the parent
class's ``clean`` method:: class's ``clean`` method::

View File

@ -313,9 +313,9 @@ list::
:class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by
default. This means you will need to use default. This means you will need to use
:func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you
to change the upload handlers. You will then need to use to change the upload handlers. You will then need to use
:func:`~django.views.decorators.csrf.csrf_protect` on the function that :func:`~django.views.decorators.csrf.csrf_protect` on the function that
actually processes the request. Note that this means that the handlers may actually processes the request. Note that this means that the handlers may
start receiving the file upload before the CSRF checks have been done. start receiving the file upload before the CSRF checks have been done.
Example code:: Example code::

View File

@ -699,7 +699,7 @@ way to tell these named URLs apart.
Django applications that make proper use of URL namespacing can be deployed Django applications that make proper use of URL namespacing can be deployed
more than once for a particular site. For example :mod:`django.contrib.admin` more than once for a particular site. For example :mod:`django.contrib.admin`
has an :class:`~django.contrib.admin.AdminSite` class which allows you to has an :class:`~django.contrib.admin.AdminSite` class which allows you to
:ref:`deploy more than one instance of the admin <multiple-admin-sites>`. In a :ref:`deploy more than one instance of the admin <multiple-admin-sites>`. In a
later example, we'll discuss the idea of deploying the polls application from later example, we'll discuss the idea of deploying the polls application from
the tutorial in two different locations so we can serve the same functionality the tutorial in two different locations so we can serve the same functionality
to two different audiences (authors and publishers). to two different audiences (authors and publishers).

View File

@ -150,7 +150,7 @@ want to create your own, because a format file doesn't exist for your locale,
or because you want to overwrite some of the values. or because you want to overwrite some of the values.
To use custom formats, specify the path where you'll place format files To use custom formats, specify the path where you'll place format files
first. To do that, set your :setting:`FORMAT_MODULE_PATH` setting to the first. To do that, set your :setting:`FORMAT_MODULE_PATH` setting to the
package where format files will exist, for instance:: package where format files will exist, for instance::
FORMAT_MODULE_PATH = [ FORMAT_MODULE_PATH = [

View File

@ -560,7 +560,7 @@ languages:
The ``name``, ``name_local``, and ``name_translated`` attributes of the The ``name``, ``name_local``, and ``name_translated`` attributes of the
dictionary contain the name of the language in English, in the language dictionary contain the name of the language in English, in the language
itself, and in your current active language respectively. The ``bidi`` itself, and in your current active language respectively. The ``bidi``
attribute is True only for bi-directional languages. attribute is True only for bi-directional languages.
The source of the language information is the ``django.conf.locale`` module. The source of the language information is the ``django.conf.locale`` module.
@ -1704,7 +1704,7 @@ otherwise, they'll be tacked together without whitespace!
Due to the way the ``gettext`` tools work internally and because we want to Due to the way the ``gettext`` tools work internally and because we want to
allow non-ASCII source strings in Django's core and your applications, you allow non-ASCII source strings in Django's core and your applications, you
**must** use UTF-8 as the encoding for your ``.po`` files (the default when **must** use UTF-8 as the encoding for your ``.po`` files (the default when
``.po`` files are created). This means that everybody will be using the ``.po`` files are created). This means that everybody will be using the
same encoding, which is important when Django processes the ``.po`` files. same encoding, which is important when Django processes the ``.po`` files.
.. admonition:: Fuzzy entries .. admonition:: Fuzzy entries
@ -2082,7 +2082,7 @@ For example, your :setting:`MIDDLEWARE` might look like this::
``LocaleMiddleware`` tries to determine the user's language preference by ``LocaleMiddleware`` tries to determine the user's language preference by
following this algorithm: following this algorithm:
* First, it looks for the language prefix in the requested URL. This is * First, it looks for the language prefix in the requested URL. This is
only performed when you are using the ``i18n_patterns`` function in your only performed when you are using the ``i18n_patterns`` function in your
root URLconf. See :ref:`url-internationalization` for more information root URLconf. See :ref:`url-internationalization` for more information
about the language prefix and how to internationalize URL patterns. about the language prefix and how to internationalize URL patterns.
@ -2178,7 +2178,7 @@ translations for the same literal:
precedence, with the ones appearing first having higher precedence than precedence, with the ones appearing first having higher precedence than
the ones appearing later. the ones appearing later.
#. Then, it looks for and uses if it exists a ``locale`` directory in each #. Then, it looks for and uses if it exists a ``locale`` directory in each
of the installed apps listed in :setting:`INSTALLED_APPS`. The ones of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
appearing first have higher precedence than the ones appearing later. appearing first have higher precedence than the ones appearing later.
#. Finally, the Django-provided base translation in :source:`django/conf/locale` #. Finally, the Django-provided base translation in :source:`django/conf/locale`
is used as a fallback. is used as a fallback.

View File

@ -148,7 +148,7 @@ your :setting:`SECRET_KEY`:
{'message': 'Hello!'} {'message': 'Hello!'}
Using salt in this way puts the different signatures into different Using salt in this way puts the different signatures into different
namespaces. A signature that comes from one namespace (a particular salt namespaces. A signature that comes from one namespace (a particular salt
value) cannot be used to validate the same plaintext string in a different value) cannot be used to validate the same plaintext string in a different
namespace that is using a different salt setting. The result is to prevent an namespace that is using a different salt setting. The result is to prevent an
attacker from using a signed string generated in one place in the code as input attacker from using a signed string generated in one place in the code as input

View File

@ -560,7 +560,7 @@ and tear down the test suite.
``debug_mode`` specifies what the :setting:`DEBUG` setting should be ``debug_mode`` specifies what the :setting:`DEBUG` setting should be
set to prior to running tests. set to prior to running tests.
``parallel`` specifies the number of processes. If ``parallel`` is greater ``parallel`` specifies the number of processes. If ``parallel`` is greater
than ``1``, the test suite will run in ``parallel`` processes. If there are than ``1``, the test suite will run in ``parallel`` processes. If there are
fewer test case classes than configured processes, Django will reduce the fewer test case classes than configured processes, Django will reduce the
number of processes accordingly. Each process gets its own database. This number of processes accordingly. Each process gets its own database. This

View File

@ -84,7 +84,7 @@ your project's ``manage.py`` utility:
$ ./manage.py test $ ./manage.py test
Test discovery is based on the unittest module's :py:ref:`built-in test Test discovery is based on the unittest module's :py:ref:`built-in test
discovery <unittest-test-discovery>`. By default, this will discover tests in discovery <unittest-test-discovery>`. By default, this will discover tests in
any file named ``test*.py`` under the current working directory. any file named ``test*.py`` under the current working directory.
You can specify particular tests to run by supplying any number of "test You can specify particular tests to run by supplying any number of "test

View File

@ -2057,7 +2057,7 @@ Django, such as your machine's mail server, if you're running one.)
During test running, each outgoing email is saved in During test running, each outgoing email is saved in
``django.core.mail.outbox``. This is a list of all ``django.core.mail.outbox``. This is a list of all
:class:`~django.core.mail.EmailMessage` instances that have been sent. The :class:`~django.core.mail.EmailMessage` instances that have been sent. The
``outbox`` attribute is a special attribute that is created *only* when the ``outbox`` attribute is a special attribute that is created *only* when the
``locmem`` email backend is used. It doesn't normally exist as part of the ``locmem`` email backend is used. It doesn't normally exist as part of the
:mod:`django.core.mail` module and you can't import it directly. The code below :mod:`django.core.mail` module and you can't import it directly. The code below