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

Refs #36485 -- Rewrapped docs to 79 columns line length.

Lines in the docs files were manually adjusted to conform to the
79 columns limit per line (plus newline), improving readability and
consistency across the content.
This commit is contained in:
David Smith
2025-07-25 10:24:17 +01:00
committed by nessita
parent 4286a23df6
commit f81e6e3a53
230 changed files with 3250 additions and 2914 deletions

View File

@@ -189,8 +189,8 @@ You can do it like this::
Notice first that we've moved ``make_published`` into a method and renamed the
``modeladmin`` parameter to ``self``, and second that we've now put the string
``'make_published'`` in ``actions`` instead of a direct function reference. This
tells the :class:`ModelAdmin` to look up the action as a method.
``'make_published'`` in ``actions`` instead of a direct function reference.
This tells the :class:`ModelAdmin` to look up the action as a method.
Defining actions as methods gives the action more idiomatic access to the
:class:`ModelAdmin` itself, allowing the action to call any of the methods
@@ -286,10 +286,10 @@ Making actions available site-wide
.. method:: AdminSite.add_action(action, name=None)
Some actions are best if they're made available to *any* object in the admin
site -- the export action defined above would be a good candidate. You can
make an action globally available using :meth:`AdminSite.add_action`. For
example::
Some actions are best if they're made available to *any* object in the
admin site -- the export action defined above would be a good candidate.
You can make an action globally available using
:meth:`AdminSite.add_action`. For example::
from django.contrib import admin
@@ -297,8 +297,8 @@ Making actions available site-wide
This makes the ``export_selected_objects`` action globally available as an
action named "export_selected_objects". You can explicitly give the action
a name -- good if you later want to programmatically :ref:`remove the action
<disabling-admin-actions>` -- by passing a second argument to
a name -- good if you later want to programmatically :ref:`remove the
action <disabling-admin-actions>` -- by passing a second argument to
:meth:`AdminSite.add_action`::
admin.site.add_action(export_selected_objects, "export_selected")
@@ -317,11 +317,11 @@ Disabling a site-wide action
.. method:: AdminSite.disable_action(name)
If you need to disable a :ref:`site-wide action <adminsite-actions>` you can
call :meth:`AdminSite.disable_action`.
If you need to disable a :ref:`site-wide action <adminsite-actions>` you
can call :meth:`AdminSite.disable_action`.
For example, you can use this method to remove the built-in "delete selected
objects" action::
For example, you can use this method to remove the built-in "delete
selected objects" action::
admin.site.disable_action("delete_selected")
@@ -367,8 +367,8 @@ Conditionally enabling or disabling actions
Finally, you can conditionally enable or disable actions on a per-request
(and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
This returns a dictionary of actions allowed. The keys are action names, and
the values are ``(function, name, short_description)`` tuples.
This returns a dictionary of actions allowed. The keys are action names,
and the values are ``(function, name, short_description)`` tuples.
For example, if you only want users whose names begin with 'J' to be able
to delete objects in bulk::

View File

@@ -127,8 +127,8 @@ The ``register`` decorator
pass
It's given one or more model classes to register with the ``ModelAdmin``.
If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword
argument::
If you're using a custom :class:`AdminSite`, pass it using the ``site``
keyword argument::
from django.contrib import admin
from .models import Author, Editor, Reader
@@ -174,7 +174,8 @@ application and imports it.
application. Such modules are expected to register models with the admin.
Typically you won't need to call this function directly as
:class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts.
:class:`~django.contrib.admin.apps.AdminConfig` calls it when Django
starts.
If you are using a custom ``AdminSite``, it is common to import all of the
``ModelAdmin`` subclasses into your code and register them to the custom
@@ -204,13 +205,13 @@ subclass::
.. attribute:: ModelAdmin.actions_on_bottom
Controls where on the page the actions bar appears. By default, the admin
changelist displays actions at the top of the page (``actions_on_top = True;
actions_on_bottom = False``).
changelist displays actions at the top of the page (``actions_on_top =
True; actions_on_bottom = False``).
.. attribute:: ModelAdmin.actions_selection_counter
Controls whether a selection counter is displayed next to the action dropdown.
By default, the admin changelist will display it
Controls whether a selection counter is displayed next to the action
dropdown. By default, the admin changelist will display it
(``actions_selection_counter = True``).
.. attribute:: ModelAdmin.date_hierarchy
@@ -313,7 +314,8 @@ subclass::
values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
read-only.
For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option.
For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets`
option.
The ``fields`` option accepts the same types of values as
:attr:`~ModelAdmin.list_display`, except that callables and ``__`` lookups
@@ -321,8 +323,8 @@ subclass::
will only be used if they're listed in :attr:`~ModelAdmin.readonly_fields`.
To display multiple fields on the same line, wrap those fields in their own
tuple. In this example, the ``url`` and ``title`` fields will display on the
same line and the ``content`` field will be displayed below them on its
tuple. In this example, the ``url`` and ``title`` fields will display on
the same line and the ``content`` field will be displayed below them on its
own line::
class FlatPageAdmin(admin.ModelAdmin):
@@ -334,11 +336,11 @@ subclass::
dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
as described in the next section.
If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
Django will default to displaying each field that isn't an ``AutoField`` and
has ``editable=True``, in a single fieldset, in the same order as the fields
are defined in the model, followed by any fields defined in
:attr:`~ModelAdmin.readonly_fields`.
If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are
present, Django will default to displaying each field that isn't an
``AutoField`` and has ``editable=True``, in a single fieldset, in the same
order as the fields are defined in the model, followed by any fields
defined in :attr:`~ModelAdmin.readonly_fields`.
.. attribute:: ModelAdmin.fieldsets
@@ -380,10 +382,10 @@ subclass::
.. image:: _images/fieldsets.png
If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
Django will default to displaying each field that isn't an ``AutoField`` and
has ``editable=True``, in a single fieldset, in the same order as the fields
are defined in the model.
If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are
present, Django will default to displaying each field that isn't an
``AutoField`` and has ``editable=True``, in a single fieldset, in the same
order as the fields are defined in the model.
The ``field_options`` dictionary can have the following keys:
@@ -489,11 +491,11 @@ subclass::
since the admin has its own way of defining fields, the ``Meta.fields``
attribute will be ignored.
If the ``ModelForm`` is only going to be used for the admin, the easiest
solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
will provide the correct model to use. Alternatively, you can set
``fields = []`` in the ``Meta`` class to satisfy the validation on the
``ModelForm``.
If the ``ModelForm`` is only going to be used for the admin, the
easiest solution is to omit the ``Meta.model`` attribute, since
``ModelAdmin`` will provide the correct model to use. Alternatively,
you can set ``fields = []`` in the ``Meta`` class to satisfy the
validation on the ``ModelForm``.
.. admonition:: ``ModelAdmin.exclude`` takes precedence
@@ -922,9 +924,9 @@ subclass::
.. attribute:: ModelAdmin.list_max_show_all
Set ``list_max_show_all`` to control how many items can appear on a "Show
all" admin change list page. The admin will display a "Show all" link on the
change list only if the total result count is less than or equal to this
setting. By default, this is set to ``200``.
all" admin change list page. The admin will display a "Show all" link on
the change list only if the total result count is less than or equal to
this setting. By default, this is set to ``200``.
.. attribute:: ModelAdmin.list_per_page
@@ -1080,8 +1082,8 @@ subclass::
You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
``django.contrib.admin`` module.
Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
``choices`` set.
Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or
has ``choices`` set.
.. attribute:: ModelAdmin.autocomplete_fields
@@ -1270,8 +1272,8 @@ subclass::
WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
If you don't want to use ``icontains`` as the lookup, you can use any
lookup by appending it the field. For example, you could use :lookup:`exact`
by setting ``search_fields`` to ``['first_name__exact']``.
lookup by appending it the field. For example, you could use
:lookup:`exact` by setting ``search_fields`` to ``['first_name__exact']``.
Some (older) shortcuts for specifying a field lookup are also available.
You can prefix a field in ``search_fields`` with the following characters
@@ -1298,9 +1300,9 @@ subclass::
.. attribute:: ModelAdmin.show_full_result_count
Set ``show_full_result_count`` to control whether the full count of objects
should be displayed on a filtered admin page (e.g. ``99 results (103 total)``).
If this option is set to ``False``, a text like ``99 results (Show all)``
is displayed instead.
should be displayed on a filtered admin page (e.g. ``99 results (103
total)``). If this option is set to ``False``, a text like ``99 results
(Show all)`` is displayed instead.
The default of ``show_full_result_count=True`` generates a query to perform
a full count on the table which can be expensive if the table contains a
@@ -1323,16 +1325,17 @@ subclass::
.. attribute:: ModelAdmin.view_on_site
Set ``view_on_site`` to control whether or not to display the "View on site" link.
This link should bring you to a URL where you can display the saved object.
Set ``view_on_site`` to control whether or not to display the "View on
site" link. This link should bring you to a URL where you can display the
saved object.
This value can be either a boolean flag or a callable. If ``True`` (the
default), the object's :meth:`~django.db.models.Model.get_absolute_url`
method will be used to generate the url.
If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
but you don't want the "View on site" button to appear, you only need to set
``view_on_site`` to ``False``::
but you don't want the "View on site" button to appear, you only need to
set ``view_on_site`` to ``False``::
from django.contrib import admin
@@ -1473,9 +1476,9 @@ default templates used by the :class:`ModelAdmin` views:
readonly.append("age") # Edits the class attribute.
return readonly
This results in ``readonly_fields`` becoming
``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added
each time non-superuser visits the page.
This results in ``readonly_fields`` becoming ``["name", "age", "age",
...]``, even for a superuser, as ``"age"`` is added each time non-superuser
visits the page.
.. method:: ModelAdmin.get_ordering(request)
@@ -1494,11 +1497,12 @@ default templates used by the :class:`ModelAdmin` views:
The ``get_search_results`` method modifies the list of objects displayed
into those that match the provided search term. It accepts the request, a
queryset that applies the current filters, and the user-provided search term.
It returns a tuple containing a queryset modified to implement the search, and
a boolean indicating if the results may contain duplicates.
queryset that applies the current filters, and the user-provided search
term. It returns a tuple containing a queryset modified to implement the
search, and a boolean indicating if the results may contain duplicates.
The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
The default implementation searches the fields named in
:attr:`ModelAdmin.search_fields`.
This method may be overridden with your own custom search method. For
example, you might wish to search by an integer field, or use an external
@@ -1528,8 +1532,8 @@ default templates used by the :class:`ModelAdmin` views:
This implementation is more efficient than ``search_fields =
('name', '=age')`` which results in a string comparison for the numeric
field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')``
on PostgreSQL.
field, for example
``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')`` on PostgreSQL.
.. _Solr: https://solr.apache.org
.. _Haystack: https://haystacksearch.org
@@ -1544,8 +1548,8 @@ default templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.get_autocomplete_fields(request)
The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is
expected to return a ``list`` or ``tuple`` of field names that will be
The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and
is expected to return a ``list`` or ``tuple`` of field names that will be
displayed with an autocomplete widget as described above in the
:attr:`ModelAdmin.autocomplete_fields` section.
@@ -1560,8 +1564,8 @@ default templates used by the :class:`ModelAdmin` views:
The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
``obj`` being edited (or ``None`` on an add form) and is expected to return
a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
section.
a ``dictionary``, as described above in the
:attr:`ModelAdmin.prepopulated_fields` section.
.. method:: ModelAdmin.get_list_display(request)
@@ -1572,11 +1576,11 @@ default templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.get_list_display_links(request, list_display)
The ``get_list_display_links`` method is given the ``HttpRequest`` and
the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
names on the changelist that will be linked to the change view, as described
in the :attr:`ModelAdmin.list_display_links` section.
The ``get_list_display_links`` method is given the ``HttpRequest`` and the
``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`. It
is expected to return either ``None`` or a ``list`` or ``tuple`` of field
names on the changelist that will be linked to the change view, as
described in the :attr:`ModelAdmin.list_display_links` section.
.. method:: ModelAdmin.get_exclude(request, obj=None)
@@ -1595,7 +1599,8 @@ default templates used by the :class:`ModelAdmin` views:
The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
being edited (or ``None`` on an add form) and is expected to return a list
of 2-tuples, in which each 2-tuple represents a ``<fieldset>`` on the
admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
admin form page, as described above in the :attr:`ModelAdmin.fieldsets`
section.
.. method:: ModelAdmin.get_list_filter(request)
@@ -1611,8 +1616,8 @@ default templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.get_search_fields(request)
The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
to return the same kind of sequence type as for the
The ``get_search_fields`` method is given the ``HttpRequest`` and is
expected to return the same kind of sequence type as for the
:attr:`~ModelAdmin.search_fields` attribute.
.. method:: ModelAdmin.get_sortable_by(request)
@@ -1635,9 +1640,10 @@ default templates used by the :class:`ModelAdmin` views:
The ``get_inline_instances`` method is given the ``HttpRequest`` and the
``obj`` being edited (or ``None`` on an add form) and is expected to return
a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
section. For example, the following would return inlines without the default
filtering based on add, change, delete, and view permissions::
objects, as described below in the
:class:`~django.contrib.admin.InlineModelAdmin` section. For example, the
following would return inlines without the default filtering based on add,
change, delete, and view permissions::
class MyModelAdmin(admin.ModelAdmin):
inlines = [MyInline]
@@ -1862,8 +1868,8 @@ default templates used by the :class:`ModelAdmin` views:
``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
``ModelAdmin`` ignores this value, overriding it with the
:attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
correct model to use.
omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide
the correct model to use.
.. method:: ModelAdmin.get_changelist_formset(request, **kwargs)
@@ -1892,13 +1898,13 @@ default templates used by the :class:`ModelAdmin` views:
can be manipulated by the user, they must be sanitized to prevent
unauthorized data exposure.
The ``lookup_allowed()`` method is given a lookup path from the query string
(e.g. ``'user__email'``), the corresponding value
(e.g. ``'user@example.com'``), and the request, and returns a boolean
indicating whether filtering the changelist's ``QuerySet`` using the
parameters is permitted. If ``lookup_allowed()`` returns ``False``,
``DisallowedModelAdminLookup``
(subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
The ``lookup_allowed()`` method is given a lookup path from the query
string (e.g. ``'user__email'``), the corresponding value (e.g.
``'user@example.com'``), and the request, and returns a boolean indicating
whether filtering the changelist's ``QuerySet`` using the parameters is
permitted. If ``lookup_allowed()`` returns ``False``,
``DisallowedModelAdminLookup`` (subclass of
:exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
By default, ``lookup_allowed()`` allows access to a model's local fields,
field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from
@@ -1911,11 +1917,11 @@ default templates used by the :class:`ModelAdmin` views:
.. method:: ModelAdmin.has_view_permission(request, obj=None)
Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.
If obj is ``None``, should return ``True`` or ``False`` to indicate whether
viewing of objects of this type is permitted in general (e.g., ``False``
will be interpreted as meaning that the current user is not permitted to
view any object of this type).
Should return ``True`` if viewing ``obj`` is permitted, ``False``
otherwise. If obj is ``None``, should return ``True`` or ``False`` to
indicate whether viewing of objects of this type is permitted in general
(e.g., ``False`` will be interpreted as meaning that the current user is
not permitted to view any object of this type).
The default implementation returns ``True`` if the user has either the
"change" or "view" permission.
@@ -2067,8 +2073,9 @@ default templates used by the :class:`ModelAdmin` views:
:attr:`~django.db.models.Options.verbose_name_plural` to the number of
objects that will be deleted.
``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s
of the models that the user doesn't have permission to delete.
``perms_needed`` is a set of
:attr:`~django.db.models.Options.verbose_name`\s of the models that the
user doesn't have permission to delete.
``protected`` is a list of strings representing of all the protected
related objects that can't be deleted. The list is displayed in the
@@ -2676,7 +2683,8 @@ If you want to allow editing and creating an ``Image`` instance on the
``Product``, add/change views you can use
:class:`~django.contrib.contenttypes.admin.GenericTabularInline`
or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both
subclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
subclasses of
:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular
and stacked visual layouts for the forms representing the inline objects,
respectively, just like their non-generic counterparts. They behave just like
@@ -2735,8 +2743,8 @@ directory, so make sure you name the directory in all lowercase if you are
going to run your app on a case-sensitive filesystem.
To override an admin template for a specific app, copy and edit the template
from the :source:`django/contrib/admin/templates/admin` directory, and save it to one
of the directories you just created.
from the :source:`django/contrib/admin/templates/admin` directory, and save it
to one of the directories you just created.
For example, if we wanted to add a tool to the change list view for all the
models in an app named ``my_app``, we would copy
@@ -2856,8 +2864,8 @@ The list of CSS variables are defined at
:source:`django/contrib/admin/static/admin/css/base.css`.
Dark mode variables, respecting the `prefers-color-scheme`_ media query, are
defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This is
linked to the document in ``{% block dark-mode-vars %}``.
defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This
is linked to the document in ``{% block dark-mode-vars %}``.
.. _prefers-color-scheme: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
@@ -2949,7 +2957,8 @@ Templates can override or extend base admin templates as described in
.. attribute:: AdminSite.app_index_template
Path to a custom template that will be used by the admin site app index view.
Path to a custom template that will be used by the admin site app index
view.
.. attribute:: AdminSite.empty_value_display
@@ -3019,14 +3028,15 @@ Templates can override or extend base admin templates as described in
* ``site_title``: :attr:`AdminSite.site_title`
* ``site_url``: :attr:`AdminSite.site_url`
* ``has_permission``: :meth:`AdminSite.has_permission`
* ``available_apps``: a list of applications from the :doc:`application registry
</ref/applications/>` available for the current user. Each entry in the
list is a dict representing an application with the following keys:
* ``available_apps``: a list of applications from the :doc:`application
registry </ref/applications/>` available for the current user. Each entry
in the list is a dict representing an application with the following
keys:
* ``app_label``: the application label
* ``app_url``: the URL of the application index in the admin
* ``has_module_perms``: a boolean indicating if displaying and accessing of
the module's index page is permitted for the current user
* ``has_module_perms``: a boolean indicating if displaying and accessing
of the module's index page is permitted for the current user
* ``models``: a list of the models available in the application
Each model is a dict with the following keys:
@@ -3102,7 +3112,8 @@ Templates can override or extend base admin templates as described in
.. method:: AdminSite.get_model_admin(model)
Returns an admin class for the given model class. Raises
``django.contrib.admin.exceptions.NotRegistered`` if a model isn't registered.
``django.contrib.admin.exceptions.NotRegistered`` if a model isn't
registered.
.. method:: AdminSite.get_log_entries(request)
@@ -3357,10 +3368,10 @@ password box.
The detailed description of the modification. In the case of an edit, for
example, the message contains a list of the edited fields. The Django admin
site formats this content as a JSON structure, so that
:meth:`get_change_message` can recompose a message translated in the current
user language. Custom code might set this as a plain string though. You are
advised to use the :meth:`get_change_message` method to retrieve this value
instead of accessing it directly.
:meth:`get_change_message` can recompose a message translated in the
current user language. Custom code might set this as a plain string though.
You are advised to use the :meth:`get_change_message` method to retrieve
this value instead of accessing it directly.
``LogEntry`` methods
--------------------

View File

@@ -61,7 +61,8 @@ Fields
.. attribute:: user_permissions
Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`
Many-to-many relationship to
:class:`~django.contrib.auth.models.Permission`
.. attribute:: is_staff
@@ -79,8 +80,8 @@ Fields
flag but the default backend
(:class:`~django.contrib.auth.backends.ModelBackend`) and the
:class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can
use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`
or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend` or
:class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
if you want to allow inactive users to login. In this case, you'll also
want to customize the
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
@@ -124,9 +125,9 @@ Attributes
.. attribute:: is_anonymous
Read-only attribute which is always ``False``. This is a way of
differentiating :class:`~models.User` and :class:`~models.AnonymousUser`
objects. Generally, you should prefer using
:attr:`~django.contrib.auth.models.User.is_authenticated` to this
differentiating :class:`~models.User` and
:class:`~models.AnonymousUser` objects. Generally, you should prefer
using :attr:`~django.contrib.auth.models.User.is_authenticated` to this
attribute.
Methods
@@ -246,8 +247,8 @@ Methods
Returns ``True`` if the user has the specified permission, where perm
is in the format ``"<app label>.<permission codename>"``. (see
documentation on :ref:`permissions <topic-authorization>`). If the user is
inactive, this method will always return ``False``. For an active
documentation on :ref:`permissions <topic-authorization>`). If the user
is inactive, this method will always return ``False``. For an active
superuser, this method will always return ``True``.
If ``obj`` is passed in, this method won't check for a permission for
@@ -330,7 +331,8 @@ Manager methods
allow setting arbitrary fields on a :ref:`custom user model
<auth-custom-user>`.
See :ref:`Creating users <topics-auth-creating-users>` for example usage.
See :ref:`Creating users <topics-auth-creating-users>` for example
usage.
.. versionchanged:: 5.2
@@ -523,10 +525,11 @@ can be used for notification when a user logs in or out.
The name of the module used for authentication.
``credentials``
A dictionary of keyword arguments containing the user credentials that were
passed to :func:`~django.contrib.auth.authenticate` or your own custom
authentication backend. Credentials matching a set of 'sensitive' patterns,
(including password) will not be sent in the clear as part of the signal.
A dictionary of keyword arguments containing the user credentials that
were passed to :func:`~django.contrib.auth.authenticate` or your own
custom authentication backend. Credentials matching a set of
'sensitive' patterns (including password) will not be sent in the clear
as part of the signal.
``request``
The :class:`~django.http.HttpRequest` object, if one was provided to
@@ -615,11 +618,11 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
:class:`~django.contrib.auth.models.User` and
:class:`~django.contrib.auth.models.PermissionsMixin`.
:meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`,
and :meth:`get_group_permissions` allow an object to be passed as a
parameter for object-specific permissions, but this backend does not
implement them other than returning an empty set of permissions if
``obj is not None``.
:meth:`has_perm`, :meth:`get_all_permissions`,
:meth:`get_user_permissions`, and :meth:`get_group_permissions` allow an
object to be passed as a parameter for object-specific permissions, but
this backend does not implement them other than returning an empty set of
permissions if ``obj is not None``.
:meth:`with_perm` also allows an object to be passed as a parameter, but
unlike others methods it returns an empty queryset if ``obj is not None``.
@@ -678,8 +681,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
*Asynchronous version*: ``aget_all_permissions()``
Returns the set of permission strings the ``user_obj`` has, including both
user permissions and group permissions. Returns an empty set if
Returns the set of permission strings the ``user_obj`` has, including
both user permissions and group permissions. Returns an empty set if
:attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or
:attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
@@ -740,7 +743,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
.. class:: AllowAllUsersModelBackend
Same as :class:`ModelBackend` except that it doesn't reject inactive users
because :meth:`~ModelBackend.user_can_authenticate` always returns ``True``.
because :meth:`~ModelBackend.user_can_authenticate` always returns
``True``.
When using this backend, you'll likely want to customize the
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the

View File

@@ -188,8 +188,8 @@ The ``ContentTypeManager``
.. method:: get_for_id(id)
Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.
Since this method uses the same shared cache as
Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by
ID. Since this method uses the same shared cache as
:meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
it's preferred to use this method over the usual
``ContentType.objects.get(pk=id)``
@@ -338,10 +338,11 @@ model:
.. admonition:: Serializing references to ``ContentType`` objects
If you're serializing data (for example, when generating
:class:`~django.test.TransactionTestCase.fixtures`) from a model that implements
generic relations, you should probably be using a natural key to uniquely
identify related :class:`~django.contrib.contenttypes.models.ContentType`
objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
:class:`~django.test.TransactionTestCase.fixtures`) from a model that
implements generic relations, you should probably be using a natural key to
uniquely identify related
:class:`~django.contrib.contenttypes.models.ContentType` objects. See
:ref:`natural keys<topics-serialization-natural-keys>` and
:option:`dumpdata --natural-foreign` for more information.
This will enable an API similar to the one used for a normal

View File

@@ -3,7 +3,8 @@ The flatpages app
=================
.. module:: django.contrib.flatpages
:synopsis: A framework for managing simple ?flat? HTML content in a database.
:synopsis: A framework for managing simple ?flat? HTML content in a
database.
Django comes with an optional "flatpages" application. It lets you store "flat"
HTML content in a database and handles the management for you via Django's

View File

@@ -68,7 +68,8 @@ of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.
.. django-admin-option:: --no-imports
Suppresses the ``from django.contrib.gis.db import models`` import statement.
Suppresses the ``from django.contrib.gis.db import models`` import
statement.
.. django-admin-option:: --null NULL

View File

@@ -45,7 +45,8 @@ model):
>>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
>>> z.save()
:class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models:
:class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save
geometric models:
.. code-block:: pycon
@@ -72,8 +73,8 @@ transform procedure:
... ) # printing the last SQL statement executed (requires DEBUG=True)
INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT
(Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object,
WKT (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
hexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the
input is not a ``GEOSGeometry`` object, the geometry field will attempt to
create a ``GEOSGeometry`` instance from the input.
@@ -169,10 +170,10 @@ For example:
>>> qs = Zipcode.objects.filter(poly__contains=pnt)
>>> qs = Elevation.objects.filter(poly__contains=rst)
In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
is the spatial lookup type, ``pnt`` is the parameter (which may be a
:class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
In this case, ``poly`` is the geographic field,
:lookup:`contains <gis-contains>` is the spatial lookup type, ``pnt`` is the
parameter (which may be a :class:`~django.contrib.gis.geos.GEOSGeometry` object
or a string of GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
:class:`~django.contrib.gis.gdal.GDALRaster` object.
.. _spatial-lookup-raster:
@@ -181,9 +182,9 @@ Raster Lookups
--------------
The raster lookup syntax is similar to the syntax for geometries. The only
difference is that a band index can be specified as additional input. If no band
index is specified, the first band is used by default (index ``0``). In that
case the syntax is identical to the syntax for geometry lookups.
difference is that a band index can be specified as additional input. If no
band index is specified, the first band is used by default (index ``0``). In
that case the syntax is identical to the syntax for geometry lookups.
To specify the band index, an additional parameter can be specified on both
sides of the lookup. On the left hand side, the double underscore syntax is
@@ -215,10 +216,11 @@ hand side, ``geom`` is a geometry input and ``rst`` is a
:class:`~django.contrib.gis.gdal.GDALRaster` object. The band index defaults to
``0`` in the first two queries and is set to ``1`` on the others.
While all spatial lookups can be used with raster objects on both sides, not all
underlying operators natively accept raster input. For cases where the operator
expects geometry input, the raster is automatically converted to a geometry.
It's important to keep this in mind when interpreting the lookup results.
While all spatial lookups can be used with raster objects on both sides, not
all underlying operators natively accept raster input. For cases where the
operator expects geometry input, the raster is automatically converted to a
geometry. It's important to keep this in mind when interpreting the lookup
results.
The type of raster support is listed for all lookups in the :ref:`compatibility
table <spatial-lookup-compatibility>`. Lookups involving rasters are currently
@@ -261,7 +263,8 @@ The following distance lookups are available:
Distance lookups take a tuple parameter comprising:
#. A geometry or raster to base calculations from; and
#. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.
#. A number or :class:`~django.contrib.gis.measure.Distance` object containing
the distance.
If a :class:`~django.contrib.gis.measure.Distance` object is used,
it may be expressed in any units (the SQL generated will use units
@@ -271,16 +274,16 @@ to be in the units of the field.
.. note::
In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
geographic distance queries are performed with. [#fndistsphere15]_ However,
these queries may take a long time, as great-circle distances must be
calculated on the fly for *every* row in the query. This is because the
geographic distance queries are performed with. [#fndistsphere15]_
However, these queries may take a long time, as great-circle distances must
be calculated on the fly for *every* row in the query. This is because the
spatial index on traditional geometry fields cannot be used.
For much better performance on WGS84 distance queries, consider using
:ref:`geography columns <geography-type>` in your database instead because
they are able to use their spatial index in distance queries.
You can tell GeoDjango to use a geography column by setting ``geography=True``
in your field definition.
You can tell GeoDjango to use a geography column by setting
``geography=True`` in your field definition.
For example, let's say we have a ``SouthTexasCity`` model (from the
:source:`GeoDjango distance tests <tests/gis_tests/distapp/models.py>` ) on a

View File

@@ -5,10 +5,10 @@ Geographic Feeds
.. module:: django.contrib.gis.feeds
:synopsis: GeoDjango's framework for generating spatial feeds.
GeoDjango has its own :class:`Feed` subclass that may embed location information
in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or
`W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of
Django's, please consult :doc:`Django's syndication documentation
GeoDjango has its own :class:`Feed` subclass that may embed location
information in RSS/Atom feeds formatted according to either the `Simple
GeoRSS`__ or `W3C Geo`_ standards. Because GeoDjango's syndication API is a
superset of Django's, please consult :doc:`Django's syndication documentation
</ref/contrib/syndication>` for details on general usage.
.. _W3C Geo: https://www.w3.org/2003/01/geo/

View File

@@ -5,8 +5,8 @@ GeoDjango Forms API
.. module:: django.contrib.gis.forms
:synopsis: GeoDjango forms API.
GeoDjango provides some specialized form fields and widgets in order to visually
display and edit geolocalized data on a map. By default, they use
GeoDjango provides some specialized form fields and widgets in order to
visually display and edit geolocalized data on a map. By default, they use
`OpenLayers`_-powered maps, with a base WMS layer provided by `NASA`_.
.. _OpenLayers: https://openlayers.org/

View File

@@ -29,7 +29,7 @@ Measurements
.. class:: Area(expression, **extra)
*Availability*: MariaDB, `MySQL
<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-area>`_,
<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-area>`__,
Oracle, `PostGIS <https://postgis.net/docs/ST_Area.html>`__, SpatiaLite
Accepts a single geographic field or expression and returns the area of the
@@ -48,8 +48,8 @@ geographic SRSes.
`PostGIS <https://postgis.net/docs/ST_Distance.html>`__, Oracle, SpatiaLite
Accepts two geographic fields or expressions and returns the distance between
them, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a raw
float value is returned when the coordinates are geodetic.
them, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a
raw float value is returned when the coordinates are geodetic.
On backends that support distance calculation on geodetic coordinates, the
proper backend function is automatically chosen depending on the SRID value of
@@ -81,18 +81,19 @@ queryset is calculated:
.. note::
Because the ``distance`` attribute is a
:class:`~django.contrib.gis.measure.Distance` object, you can easily express
the value in the units of your choice. For example, ``city.distance.mi`` is
the distance value in miles and ``city.distance.km`` is the distance value
in kilometers. See :doc:`measure` for usage details and the list of
:ref:`supported_units`.
:class:`~django.contrib.gis.measure.Distance` object, you can easily
express the value in the units of your choice. For example,
``city.distance.mi`` is the distance value in miles and
``city.distance.km`` is the distance value in kilometers. See
:doc:`measure` for usage details and the list of :ref:`supported_units`.
``GeometryDistance``
--------------------
.. class:: GeometryDistance(expr1, expr2, **extra)
*Availability*: `PostGIS <https://postgis.net/docs/geometry_distance_knn.html>`__
*Availability*: `PostGIS
<https://postgis.net/docs/geometry_distance_knn.html>`__
Accepts two geographic fields or expressions and returns the distance between
them. When used in an :meth:`~django.db.models.query.QuerySet.order_by` clause,
@@ -126,8 +127,8 @@ MySQL doesn't support length calculations on geographic SRSes.
*Availability*: `PostGIS <https://postgis.net/docs/ST_Perimeter.html>`__,
Oracle, SpatiaLite
Accepts a single geographic field or expression and returns the perimeter of the
geometry field as a :class:`~django.contrib.gis.measure.Distance` object.
Accepts a single geographic field or expression and returns the perimeter of
the geometry field as a :class:`~django.contrib.gis.measure.Distance` object.
Relationships
=============
@@ -150,8 +151,9 @@ south = ``π``; west = ``3π/2``.
.. class:: BoundingCircle(expression, num_seg=48, **extra)
*Availability*: `PostGIS <https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__,
`Oracle <https://docs.oracle.com/en/database/oracle/oracle-database/21/spatl/
*Availability*: `PostGIS
<https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__, `Oracle
<https://docs.oracle.com/en/database/oracle/oracle-database/21/spatl/
SDO_GEOM-reference.html#GUID-82A61626-BB64-4793-B53D-A0DBEC91831A>`_,
SpatiaLite 5.1+
@@ -205,8 +207,8 @@ representing the bounding box of the geometry.
*Availability*: `PostGIS <https://postgis.net/docs/ST_LineLocatePoint.html>`__,
SpatiaLite
Returns a float between 0 and 1 representing the location of the closest point on
``linestring`` to the given ``point``, as a fraction of the 2D line length.
Returns a float between 0 and 1 representing the location of the closest point
on ``linestring`` to the given ``point``, as a fraction of the 2D line length.
``PointOnSurface``
------------------
@@ -216,8 +218,9 @@ Returns a float between 0 and 1 representing the location of the closest point o
*Availability*: `PostGIS <https://postgis.net/docs/ST_PointOnSurface.html>`__,
MariaDB, Oracle, SpatiaLite
Accepts a single geographic field or expression and returns a ``Point`` geometry
guaranteed to lie on the surface of the field; otherwise returns ``None``.
Accepts a single geographic field or expression and returns a ``Point``
geometry guaranteed to lie on the surface of the field; otherwise returns
``None``.
Operations
==========
@@ -334,7 +337,8 @@ parameter.
.. class:: Scale(expression, x, y, z=0.0, **extra)
*Availability*: `PostGIS <https://postgis.net/docs/ST_Scale.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_Scale.html>`__,
SpatiaLite
Accepts a single geographic field or expression and returns a geometry with
scaled coordinates by multiplying them with the ``x``, ``y``, and optionally
@@ -469,8 +473,8 @@ Keyword Argument Description
*Availability*: Oracle, `PostGIS <https://postgis.net/docs/ST_AsGML.html>`__,
SpatiaLite
Accepts a single geographic field or expression and returns a `Geographic Markup
Language (GML)`__ representation of the geometry.
Accepts a single geographic field or expression and returns a `Geographic
Markup Language (GML)`__ representation of the geometry.
Example:
@@ -498,7 +502,8 @@ __ https://en.wikipedia.org/wiki/Geography_Markup_Language
.. class:: AsKML(expression, precision=8, **extra)
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsKML.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsKML.html>`__,
SpatiaLite
Accepts a single geographic field or expression and returns a `Keyhole Markup
Language (KML)`__ representation of the geometry.
@@ -527,7 +532,8 @@ __ https://developers.google.com/kml/documentation/
.. class:: AsSVG(expression, relative=False, precision=8, **extra)
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsSVG.html>`__, SpatiaLite
*Availability*: `PostGIS <https://postgis.net/docs/ST_AsSVG.html>`__,
SpatiaLite
Accepts a single geographic field or expression and returns a `Scalable Vector
Graphics (SVG)`__ representation of the geometry.
@@ -668,8 +674,8 @@ Accepts a single geographic field or expression and returns the memory size
SpatiaLite
Accepts a single geographic field or expression and returns the number of
geometries if the geometry field is a collection (e.g., a ``GEOMETRYCOLLECTION``
or ``MULTI*`` field). Returns 1 for single geometries.
geometries if the geometry field is a collection (e.g., a
``GEOMETRYCOLLECTION`` or ``MULTI*`` field). Returns 1 for single geometries.
On MySQL, returns ``None`` for single geometries.
@@ -682,7 +688,7 @@ On MySQL, returns ``None`` for single geometries.
<https://dev.mysql.com/doc/refman/en/gis-linestring-property-functions.html#function_st-numpoints>`__,
`PostGIS <https://postgis.net/docs/ST_NPoints.html>`__, Oracle, SpatiaLite
Accepts a single geographic field or expression and returns the number of points
in a geometry.
Accepts a single geographic field or expression and returns the number of
points in a geometry.
On MySQL, returns ``None`` for any non-``LINESTRING`` geometry.

View File

@@ -299,11 +299,11 @@ __ https://gdal.org/drivers/vector/
``Feature`` wraps an OGR feature. You never create a ``Feature`` object
directly. Instead, you retrieve them from a :class:`Layer` object. Each
feature consists of a geometry and a set of fields containing additional
properties. The geometry of a field is accessible via its ``geom`` property,
which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a
standard Python container for its fields, which it returns as :class:`Field`
objects: you can access a field directly by its index or name, or you can
iterate over a feature's fields, e.g. in a ``for`` loop.
properties. The geometry of a field is accessible via its ``geom``
property, which returns an :class:`OGRGeometry` object. A ``Feature``
behaves like a standard Python container for its fields, which it returns
as :class:`Field` objects: you can access a field directly by its index or
name, or you can iterate over a feature's fields, e.g. in a ``for`` loop.
.. attribute:: geom
@@ -537,9 +537,9 @@ coordinate transformation:
.. method:: __getitem__()
Returns the point at the specified index for a :class:`LineString`, the
interior ring at the specified index for a :class:`Polygon`, or the geometry
at the specified index in a :class:`GeometryCollection`. Not applicable to
other geometry types.
interior ring at the specified index for a :class:`Polygon`, or the
geometry at the specified index in a :class:`GeometryCollection`. Not
applicable to other geometry types.
.. attribute:: dimension
@@ -1273,28 +1273,28 @@ Raster Data Objects
----------------
:class:`GDALRaster` is a wrapper for the GDAL raster source object that
supports reading data from a variety of GDAL-supported geospatial file
formats and data sources using a consistent interface. Each
data source is represented by a :class:`GDALRaster` object which contains
one or more layers of data named bands. Each band, represented by a
:class:`GDALBand` object, contains georeferenced image data. For example, an RGB
image is represented as three bands: one for red, one for green, and one for
blue.
supports reading data from a variety of GDAL-supported geospatial file formats
and data sources using a consistent interface. Each data source is represented
by a :class:`GDALRaster` object which contains one or more layers of data named
bands. Each band, represented by a :class:`GDALBand` object, contains
georeferenced image data. For example, an RGB image is represented as three
bands: one for red, one for green, and one for blue.
.. note::
For raster data there is no difference between a raster instance and its
data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
always a data source. Temporary rasters can be instantiated in memory
using the corresponding driver, but they will be of the same class as file-based
raster sources.
data source. Unlike for the Geometry objects, :class:`GDALRaster` objects
are always a data source. Temporary rasters can be instantiated in memory
using the corresponding driver, but they will be of the same class as
file-based raster sources.
.. class:: GDALRaster(ds_input, write=False)
The constructor for ``GDALRaster`` accepts two parameters. The first
parameter defines the raster source, and the second parameter defines if a
raster should be opened in write mode. For newly-created rasters, the second
parameter is ignored and the new raster is always created in write mode.
raster should be opened in write mode. For newly-created rasters, the
second parameter is ignored and the new raster is always created in write
mode.
The first parameter can take three forms: a string or
:class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
@@ -1358,8 +1358,8 @@ blue.
.. attribute:: name
The name of the source which is equivalent to the input file path or the name
provided upon instantiation.
The name of the source which is equivalent to the input file path or
the name provided upon instantiation.
.. code-block:: pycon
@@ -1368,11 +1368,12 @@ blue.
.. attribute:: driver
The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
from a file, the driver type is detected automatically. The creation of rasters from
scratch is an in-memory raster by default (``'MEM'``), but can be
altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
For a list of file types, see also the `GDAL Raster Formats`__ list.
The name of the GDAL driver used to handle the input file. For
``GDALRaster``\s created from a file, the driver type is detected
automatically. The creation of rasters from scratch is an in-memory
raster by default (``'MEM'``), but can be altered as needed. For
instance, use ``GTiff`` for a ``GeoTiff`` file. For a list of file
types, see also the `GDAL Raster Formats`__ list.
__ https://gdal.org/drivers/raster/
@@ -1572,10 +1573,11 @@ blue.
for file-based rasters the warp function will create a new raster on
disk.
The only parameter that is set differently from the source raster is the
name. The default value of the raster name is the name of the source
raster appended with ``'_copy' + source_driver_name``. For file-based
rasters it is recommended to provide the file path of the target raster.
The only parameter that is set differently from the source raster is
the name. The default value of the raster name is the name of the
source raster appended with ``'_copy' + source_driver_name``. For
file-based rasters it is recommended to provide the file path of the
target raster.
The resampling algorithm used for warping can be specified with the
``resampling`` argument. The default is ``NearestNeighbor``, and the
@@ -1714,7 +1716,8 @@ blue.
.. attribute:: pixel_count
The total number of pixels in this band. Is equal to ``width * height``.
The total number of pixels in this band. Is equal to ``width *
height``.
.. method:: statistics(refresh=False, approximate=False)
@@ -1764,8 +1767,8 @@ blue.
.. attribute:: nodata_value
The "no data" value for a band is generally a special marker value used
to mark pixels that are not valid data. Such pixels should generally not
be displayed, nor contribute to analysis operations.
to mark pixels that are not valid data. Such pixels should generally
not be displayed, nor contribute to analysis operations.
To delete an existing "no data" value, set this property to ``None``.
@@ -1780,31 +1783,32 @@ blue.
The color interpretation for the band, as an integer between 0and 16.
If ``as_string`` is ``True``, the data type is returned as a string
with the following possible values:
``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
with the following possible values: ``GCI_Undefined``,
``GCI_GrayIndex``, ``GCI_PaletteIndex``, ``GCI_RedBand``,
``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
is returned as a string.
because both correspond to the integer 16, but only
``GCI_YCbCr_CrBand`` is returned as a string.
.. method:: data(data=None, offset=None, size=None, shape=None)
The accessor to the pixel values of the ``GDALBand``. Returns the complete
data array if no parameters are provided. A subset of the pixel array can
be requested by specifying an offset and block size as tuples.
The accessor to the pixel values of the ``GDALBand``. Returns the
complete data array if no parameters are provided. A subset of the
pixel array can be requested by specifying an offset and block size as
tuples.
If NumPy is available, the data is returned as NumPy array. For performance
reasons, it is highly recommended to use NumPy.
If NumPy is available, the data is returned as NumPy array. For
performance reasons, it is highly recommended to use NumPy.
Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
The input can be of one of the following types - packed string, buffer, list,
array, and NumPy array. The number of items in the input should normally
correspond to the total number of pixels in the band, or to the number
of pixels for a specific block of pixel values if the ``offset`` and
``size`` parameters are provided.
Data is written to the ``GDALBand`` if the ``data`` parameter is
provided. The input can be of one of the following types - packed
string, buffer, list, array, and NumPy array. The number of items in
the input should normally correspond to the total number of pixels in
the band, or to the number of pixels for a specific block of pixel
values if the ``offset`` and ``size`` parameters are provided.
If the number of items in the input is different from the target pixel
block, the ``shape`` parameter must be specified. The shape is a tuple
@@ -1927,8 +1931,8 @@ Key Default Usage
.. object:: datatype
Integer representing the data type for all the bands. Defaults to ``6``
(Float32). All bands of a new raster are required to have the same datatype.
The value mapping is:
(Float32). All bands of a new raster are required to have the same
datatype. The value mapping is:
===== =============== ===================================
Value GDAL Pixel Type Description

View File

@@ -27,7 +27,8 @@ converted to a geometry where necessary using the `ST_Polygon
<https://postgis.net/docs/RT_ST_Polygon.html>`_ function. See also the
:ref:`introduction to raster lookups <spatial-lookup-raster>`.
The database operators used by the lookups can be divided into three categories:
The database operators used by the lookups can be divided into three
categories:
- Native raster support ``N``: the operator accepts rasters natively on both
sides of the lookup, and raster input can be mixed with geometry inputs.
@@ -65,8 +66,9 @@ Spatial lookups with rasters are only supported for PostGIS backends
``bbcontains``
--------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contain.html>`__,
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Contain.html>`__, MariaDB, MySQL,
SpatiaLite, PGRaster (Native)
Tests if the geometry or raster field's bounding box completely contains the
lookup geometry's bounding box.
@@ -113,8 +115,9 @@ SpatiaLite ``MbrOverlaps(poly, geom)``
``contained``
-------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contained.html>`__,
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Contained.html>`__, MariaDB, MySQL,
SpatiaLite, PGRaster (Native)
Tests if the geometry field's bounding box is completely contained by the
lookup geometry's bounding box.
@@ -161,8 +164,8 @@ SpatiaLite ``Contains(poly, geom)``
``contains_properly``
---------------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_ContainsProperly.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_ContainsProperly.html>`__, PGRaster (Bilateral)
Returns true if the lookup geometry intersects the interior of the
geometry field, but not the boundary (or exterior).
@@ -453,9 +456,10 @@ SpatiaLite ``Overlaps(poly, geom)``
*Availability*: `PostGIS <https://postgis.net/docs/ST_Relate.html>`__,
MariaDB, Oracle, SpatiaLite, PGRaster (Conversion)
Tests if the geometry field is spatially related to the lookup geometry by
the values given in the given pattern. This lookup requires a tuple parameter,
``(geom, pattern)``; the form of ``pattern`` will depend on the spatial backend:
Tests if the geometry field is spatially related to the lookup geometry by the
values given in the given pattern. This lookup requires a tuple parameter,
``(geom, pattern)``; the form of ``pattern`` will depend on the spatial
backend:
MariaDB, PostGIS, and SpatiaLite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -612,11 +616,11 @@ PostGIS equivalent:
``overlaps_left``
-----------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overleft.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overleft.html>`__, PGRaster (Bilateral)
Tests if the geometry field's bounding box overlaps or is to the left of the lookup
geometry's bounding box.
Tests if the geometry field's bounding box overlaps or is to the left of the
lookup geometry's bounding box.
Example::
@@ -634,11 +638,11 @@ PostGIS equivalent:
``overlaps_right``
------------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overright.html>`__,
PGRaster (Bilateral)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overright.html>`__, PGRaster (Bilateral)
Tests if the geometry field's bounding box overlaps or is to the right of the lookup
geometry's bounding box.
Tests if the geometry field's bounding box overlaps or is to the right of the
lookup geometry's bounding box.
Example::
@@ -655,8 +659,8 @@ PostGIS equivalent:
``overlaps_above``
------------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overabove.html>`__,
PGRaster (Conversion)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overabove.html>`__, PGRaster (Conversion)
Tests if the geometry field's bounding box overlaps or is above the lookup
geometry's bounding box.
@@ -676,8 +680,8 @@ PostGIS equivalent:
``overlaps_below``
------------------
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overbelow.html>`__,
PGRaster (Conversion)
*Availability*: `PostGIS
<https://postgis.net/docs/ST_Geometry_Overbelow.html>`__, PGRaster (Conversion)
Tests if the geometry field's bounding box overlaps or is below the lookup
geometry's bounding box.
@@ -918,11 +922,11 @@ Example:
*Availability*: `PostGIS <https://postgis.net/docs/ST_Collect.html>`__,
MariaDB, MySQL, SpatiaLite
Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry
column. This is analogous to a simplified version of the :class:`Union`
aggregate, except it can be several orders of magnitude faster than performing
a union because it rolls up geometries into a collection or multi object, not
caring about dissolving boundaries.
Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the
geometry column. This is analogous to a simplified version of the
:class:`Union` aggregate, except it can be several orders of magnitude faster
than performing a union because it rolls up geometries into a collection or
multi object, not caring about dissolving boundaries.
.. versionchanged:: 6.0
@@ -955,8 +959,8 @@ Example:
*Availability*: `PostGIS <https://postgis.net/docs/ST_3DExtent.html>`__
Returns the 3D extent of all ``geo_field`` in the ``QuerySet`` as a 6-tuple,
comprising the lower left coordinate and upper right coordinate (each with x, y,
and z coordinates).
comprising the lower left coordinate and upper right coordinate (each with x,
y, and z coordinates).
Example:

View File

@@ -101,10 +101,10 @@ Finally, there is the :func:`fromfile` factory method which returns a
You find many ``TypeError`` or ``AttributeError`` exceptions filling your
web server's log files. This generally means that you are creating GEOS
objects at the top level of some of your Python modules. Then, due to a race
condition in the garbage collector, your module is garbage collected before
the GEOS object. To prevent this, create :class:`GEOSGeometry` objects
inside the local scope of your functions/methods.
objects at the top level of some of your Python modules. Then, due to a
race condition in the garbage collector, your module is garbage collected
before the GEOS object. To prevent this, create :class:`GEOSGeometry`
objects inside the local scope of your functions/methods.
Geometries are Pythonic
-----------------------
@@ -439,8 +439,8 @@ return a boolean.
.. method:: GEOSGeometry.contains(other)
Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>` returns
``True``.
Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>`
returns ``True``.
.. method:: GEOSGeometry.covers(other)
@@ -456,8 +456,8 @@ return a boolean.
This predicate is similar to :meth:`GEOSGeometry.contains`, but is more
inclusive (i.e. returns ``True`` for more cases). In particular, unlike
:meth:`~GEOSGeometry.contains` it does not distinguish between points in the
boundary and in the interior of geometries. For most situations,
:meth:`~GEOSGeometry.contains` it does not distinguish between points in
the boundary and in the interior of geometries. For most situations,
``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an
added benefit, ``covers()`` is more amenable to optimization and hence
should outperform :meth:`~GEOSGeometry.contains`.
@@ -507,9 +507,9 @@ return a boolean.
.. method:: GEOSGeometry.relate_pattern(other, pattern)
Returns ``True`` if the elements in the DE-9IM intersection matrix
for this geometry and the other matches the given ``pattern`` --
a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
Returns ``True`` if the elements in the DE-9IM intersection matrix for this
geometry and the other matches the given ``pattern`` -- a string of nine
characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
.. method:: GEOSGeometry.touches(other)
@@ -548,9 +548,9 @@ Topological Methods
.. method:: GEOSGeometry.interpolate_normalized(distance)
Given a distance (float), returns the point (or closest point) within the
geometry (:class:`LineString` or :class:`MultiLineString`) at that distance.
The normalized version takes the distance as a float between 0 (origin) and
1 (endpoint).
geometry (:class:`LineString` or :class:`MultiLineString`) at that
distance. The normalized version takes the distance as a float between 0
(origin) and 1 (endpoint).
Reverse of :meth:`GEOSGeometry.project`.
@@ -583,10 +583,10 @@ Topological Methods
By default, this function does not preserve topology. For example,
:class:`Polygon` objects can be split, be collapsed into lines, or
disappear. :class:`Polygon` holes can be created or disappear, and lines may
cross. By specifying ``preserve_topology=True``, the result will have the
same dimension and number of components as the input; this is significantly
slower, however.
disappear. :class:`Polygon` holes can be created or disappear, and lines
may cross. By specifying ``preserve_topology=True``, the result will have
the same dimension and number of components as the input; this is
significantly slower, however.
.. method:: GEOSGeometry.sym_difference(other)
@@ -633,13 +633,13 @@ Topological Properties
The result obeys the following contract:
* Unioning a set of :class:`LineString`\s has the effect of fully noding and
dissolving the linework.
* Unioning a set of :class:`LineString`\s has the effect of fully noding
and dissolving the linework.
* Unioning a set of :class:`Polygon`\s will always return a :class:`Polygon`
or :class:`MultiPolygon` geometry (unlike :meth:`GEOSGeometry.union`,
which may return geometries of lower dimension if a topology collapse
occurs).
* Unioning a set of :class:`Polygon`\s will always return a
:class:`Polygon` or :class:`MultiPolygon` geometry (unlike
:meth:`GEOSGeometry.union`, which may return geometries of lower
dimension if a topology collapse occurs).
Other Properties & Methods
~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -655,7 +655,8 @@ Other Properties & Methods
.. method:: GEOSGeometry.clone()
This method returns a :class:`GEOSGeometry` that is a clone of the original.
This method returns a :class:`GEOSGeometry` that is a clone of the
original.
.. method:: GEOSGeometry.distance(geom)
@@ -678,8 +679,8 @@ Other Properties & Methods
Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
``PreparedGeometry`` objects are optimized for the contains, intersects,
covers, crosses, disjoint, overlaps, touches and within operations. Refer to
the :ref:`prepared-geometries` documentation for more information.
covers, crosses, disjoint, overlaps, touches and within operations. Refer
to the :ref:`prepared-geometries` documentation for more information.
.. attribute:: GEOSGeometry.srs
@@ -810,8 +811,8 @@ Other Properties & Methods
``Polygon`` objects may be instantiated by passing in parameters that
represent the rings of the polygon. The parameters must either be
:class:`LinearRing` instances, or a sequence that may be used to construct a
:class:`LinearRing`:
:class:`LinearRing` instances, or a sequence that may be used to construct
a :class:`LinearRing`:
.. code-block:: pycon
@@ -973,7 +974,8 @@ Geometry Factories
:param file_h: input file that contains spatial data
:type file_h: a Python ``file`` object or a string path to the file
:rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file
:rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the
file
Example:
@@ -988,7 +990,8 @@ Geometry Factories
:type string: str
:param srid: spatial reference identifier
:type srid: int
:rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
:rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the
string
``fromstr(string, srid)`` is equivalent to
:class:`GEOSGeometry(string, srid) <GEOSGeometry>`.
@@ -1144,8 +1147,8 @@ include the SRID value (in other words, EWKB).
.. class:: WKTWriter(dim=2, trim=False, precision=None)
This class allows outputting the WKT representation of a geometry. See the
:attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes for
details about the constructor arguments.
:attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes
for details about the constructor arguments.
.. method:: WKTWriter.write(geom)

View File

@@ -145,10 +145,11 @@ When GeoDjango can't find GEOS, this error is raised:
ImportError: Could not find the GEOS library (tried "geos_c"). Try setting GEOS_LIBRARY_PATH in your settings.
The most common solution is to properly configure your :ref:`libsettings` *or* set
:ref:`geoslibrarypath` in your settings.
The most common solution is to properly configure your :ref:`libsettings` *or*
set :ref:`geoslibrarypath` in your settings.
If using a binary package of GEOS (e.g., on Ubuntu), you may need to :ref:`binutils`.
If using a binary package of GEOS (e.g., on Ubuntu), you may need to
:ref:`binutils`.
.. _geoslibrarypath:
@@ -169,7 +170,8 @@ GEOS C library. For example:
The setting must be the *full* path to the **C** shared library; in
other words you want to use ``libgeos_c.so``, not ``libgeos.so``.
See also :ref:`My logs are filled with GEOS-related errors <geos-exceptions-in-logfile>`.
See also :ref:`My logs are filled with GEOS-related errors
<geos-exceptions-in-logfile>`.
.. _proj4:
@@ -192,8 +194,8 @@ PROJ < 7.x) [#]_:
$ wget https://download.osgeo.org/proj/proj-data-X.Y.tar.gz
Next, untar the source code archive, and extract the datum shifting files in the
``data`` subdirectory. This must be done *prior* to configuration:
Next, untar the source code archive, and extract the datum shifting files in
the ``data`` subdirectory. This must be done *prior* to configuration:
.. code-block:: shell

View File

@@ -19,11 +19,12 @@ instructions are available for:
.. admonition:: Use the Source
Because GeoDjango takes advantage of the latest in the open source geospatial
software technology, recent versions of the libraries are necessary.
If binary packages aren't available for your platform, installation from
source may be required. When compiling the libraries from source, please
follow the directions closely, especially if you're a beginner.
Because GeoDjango takes advantage of the latest in the open source
geospatial software technology, recent versions of the libraries are
necessary. If binary packages aren't available for your platform,
installation from source may be required. When compiling the libraries from
source, please follow the directions closely, especially if you're a
beginner.
Requirements
============
@@ -99,7 +100,8 @@ Add ``django.contrib.gis`` to :setting:`INSTALLED_APPS`
Like other Django contrib applications, you will *only* need to add
:mod:`django.contrib.gis` to :setting:`INSTALLED_APPS` in your settings.
This is so that the ``gis`` templates can be located -- if not done, then
features such as the geographic admin or KML sitemaps will not function properly.
features such as the geographic admin or KML sitemaps will not function
properly.
Troubleshooting
===============
@@ -145,10 +147,11 @@ could place the following in their bash profile:
Setting system library path
~~~~~~~~~~~~~~~~~~~~~~~~~~~
On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include
additional paths from files in another directory, such as ``/etc/ld.so.conf.d``.
As the root user, add the custom library path (like ``/usr/local/lib``) on a
new line in ``ld.so.conf``. This is *one* example of how to do so:
On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which
may include additional paths from files in another directory, such as
``/etc/ld.so.conf.d``. As the root user, add the custom library path (like
``/usr/local/lib``) on a new line in ``ld.so.conf``. This is *one* example of
how to do so:
.. code-block:: shell
@@ -174,10 +177,11 @@ module) to discover libraries. The ``find_library`` routine uses a program
called ``objdump`` (part of the ``binutils`` package) to verify a shared
library on GNU/Linux systems. Thus, if ``binutils`` is not installed on your
Linux system then Python's ctypes may not be able to find your library even if
your library path is set correctly and geospatial libraries were built perfectly.
your library path is set correctly and geospatial libraries were built
perfectly.
The ``binutils`` package may be installed on Debian and Ubuntu systems using the
following command:
The ``binutils`` package may be installed on Debian and Ubuntu systems using
the following command:
.. code-block:: shell
@@ -279,9 +283,10 @@ __ https://brew.sh/
Fink
^^^^
`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users
of the `Fink`__ package system. `Different packages are available`__ (starting
with ``django-gis``), depending on which version of Python you want to use.
`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for
users of the `Fink`__ package system. `Different packages are available`__
(starting with ``django-gis``), depending on which version of Python you want
to use.
__ https://schwehr.blogspot.com/
__ https://www.finkproject.org/

View File

@@ -39,8 +39,8 @@ command line interface and enter the following query:
sqlite> CREATE VIRTUAL TABLE testrtree USING rtree(id,minX,maxX,minY,maxY);
If you obtain an error, you will have to recompile SQLite from source. Otherwise,
skip this section.
If you obtain an error, you will have to recompile SQLite from source.
Otherwise, skip this section.
To install from sources, download the latest amalgamation source archive from
the `SQLite download page`__, and extract:
@@ -51,8 +51,9 @@ the `SQLite download page`__, and extract:
$ unzip sqlite-amalgamation-XXX0000.zip
$ cd sqlite-amalgamation-XXX0000
Next, run the ``configure`` script -- however the ``CFLAGS`` environment variable
needs to be customized so that SQLite knows to build the R*Tree module:
Next, run the ``configure`` script -- however the ``CFLAGS`` environment
variable needs to be customized so that SQLite knows to build the R*Tree
module:
.. code-block:: shell

View File

@@ -21,12 +21,12 @@ then inserting into a GeoDjango model.
.. warning ::
GIS data sources, like shapefiles, may be very large. If you find
that :class:`LayerMapping` is using too much memory, set
:setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG`
is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>`
*every* SQL query -- and when SQL statements contain geometries, this may
consume more memory than is typical.
GIS data sources, like shapefiles, may be very large. If you find that
:class:`LayerMapping` is using too much memory, set :setting:`DEBUG` to
``False`` in your settings. When :setting:`DEBUG` is set to ``True``,
Django :ref:`automatically logs <faq-see-raw-sql-queries>` *every* SQL
query -- and when SQL statements contain geometries, this may consume more
memory than is typical.
Example
=======
@@ -52,7 +52,8 @@ Example
PRIMEM["Greenwich",0],
UNIT["Degree",0.017453292519943295]]
#. Now we define our corresponding Django model (make sure to use :djadmin:`migrate`)::
#. Now we define our corresponding Django model (make sure to use
:djadmin:`migrate`)::
from django.contrib.gis.db import models

View File

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

View File

@@ -108,9 +108,9 @@ All are optional.
.. attribute:: BaseSpatialField.srid
Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry field to
the given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees
of longitude and latitude).
Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry
field to the given value. Defaults to 4326 (also known as `WGS84`__, units are
in degrees of longitude and latitude).
__ https://en.wikipedia.org/wiki/WGS84
@@ -121,12 +121,12 @@ Selecting an SRID
Choosing an appropriate SRID for your model is an important decision that the
developer should consider carefully. The SRID is an integer specifier that
corresponds to the projection system that will be used to interpret the data
in the spatial database. [#fnsrid]_ Projection systems give the context to the
corresponds to the projection system that will be used to interpret the data in
the spatial database. [#fnsrid]_ Projection systems give the context to the
coordinates that specify a location. Although the details of `geodesy`__ are
beyond the scope of this documentation, the general problem is that the earth
is spherical and representations of the earth (e.g., paper maps, web maps)
are not.
is spherical and representations of the earth (e.g., paper maps, web maps) are
not.
Most people are familiar with using latitude and longitude to reference a
location on the earth's surface. However, latitude and longitude are angles,
@@ -139,7 +139,7 @@ Thus, additional computation is required to obtain distances in planar units
(e.g., kilometers and miles). Using a geographic coordinate system may
introduce complications for the developer later on. For example, SpatiaLite
does not have the capability to perform distance calculations between
geometries using geographic coordinate systems, e.g. constructing a query to
geometries using geographic coordinate systems, e.g. constructing a query to
find all points within 5 miles of a county boundary stored as WGS84. [#fndist]_
Portions of the earth's surface may projected onto a two-dimensional, or
@@ -263,7 +263,7 @@ geography column to a geometry type in the query::
For more information, the PostGIS documentation contains a helpful section on
determining `when to use geography data type over geometry data type
<https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`_.
<https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`__.
.. rubric:: Footnotes
.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.

View File

@@ -13,8 +13,8 @@ __ https://geojson.org/
The ``geojson`` serializer is not meant for round-tripping data, as it has no
deserializer equivalent. For example, you cannot use :djadmin:`loaddata` to
reload the output produced by this serializer. If you plan to reload the
outputted data, use the plain :ref:`json serializer <serialization-formats-json>`
instead.
outputted data, use the plain :ref:`json serializer
<serialization-formats-json>` instead.
In addition to the options of the ``json`` serializer, the ``geojson``
serializer accepts the following additional option when it is called by
@@ -23,7 +23,8 @@ serializer accepts the following additional option when it is called by
* ``geometry_field``: A string containing the name of a geometry field to use
for the ``geometry`` key of the GeoJSON feature. This is only needed when you
have a model with more than one geometry field and you don't want to use the
first defined geometry field (by default, the first geometry field is picked).
first defined geometry field (by default, the first geometry field is
picked).
* ``id_field``: A string containing the name of a field to use for the ``id``
key of the GeoJSON feature. By default, the primary key of objects is used.

View File

@@ -15,7 +15,8 @@ Settings
.. note::
The settings below have sensible defaults, and shouldn't require manual setting.
The settings below have sensible defaults, and shouldn't require manual
setting.
.. setting:: POSTGIS_VERSION

View File

@@ -6,8 +6,8 @@ Introduction
============
GeoDjango is an included contrib module for Django that turns it into a
world-class geographic web framework. GeoDjango strives to make it as simple
as possible to create geographic web applications, like location-based services.
world-class geographic web framework. GeoDjango strives to make it as simple as
possible to create geographic web applications, like location-based services.
Its features include:
* Django model fields for `OGC`_ geometries and raster data.
@@ -310,8 +310,8 @@ database via GeoDjango models using the :doc:`layermapping`.
There are many different ways to import data into a spatial database --
besides the tools included within GeoDjango, you may also use the following:
* `ogr2ogr`_: A command-line utility included with GDAL that
can import many vector data formats into PostGIS, MySQL, and Oracle databases.
* `ogr2ogr`_: A command-line utility included with GDAL that can import many
vector data formats into PostGIS, MySQL, and Oracle databases.
* `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into
PostGIS.
@@ -375,12 +375,12 @@ You can see the layer's geometry type and how many features it contains:
.. note::
Unfortunately, the shapefile data format does not allow for greater
specificity with regards to geometry types. This shapefile, like
many others, actually includes ``MultiPolygon`` geometries, not Polygons.
It's important to use a more general field type in models: a
GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This
is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
specificity with regards to geometry types. This shapefile, like many
others, actually includes ``MultiPolygon`` geometries, not Polygons. It's
important to use a more general field type in models: a GeoDjango
``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This is
why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference
system associated with it. If it does, the ``srs`` attribute will return a
@@ -412,18 +412,22 @@ units of degrees.
In addition, shapefiles also support attribute fields that may contain
additional data. Here are the fields on the World Borders layer:
.. code-block:: pycon
>>> print(lyr.fields)
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
The following code will let you examine the OGR types (e.g. integer or
string) associated with each of the fields:
.. code-block:: pycon
>>> [fld.__name__ for fld in lyr.field_types]
['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger64', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']
You can iterate over each feature in the layer and extract information from both
the feature's geometry (accessed via the ``geom`` attribute) as well as the
feature's attribute fields (whose **values** are accessed via ``get()``
You can iterate over each feature in the layer and extract information from
both the feature's geometry (accessed via the ``geom`` attribute) as well as
the feature's attribute fields (whose **values** are accessed via ``get()``
method):
.. code-block:: pycon
@@ -769,7 +773,8 @@ application with the following code::
admin.site.register(WorldBorder, admin.ModelAdmin)
Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows::
Next, edit your ``urls.py`` in the ``geodjango`` application folder as
follows::
from django.contrib import admin
from django.urls import include, path

View File

@@ -6,9 +6,9 @@ Django aims to follow Python's :ref:`"batteries included" philosophy
<tut-batteries-included>`. It ships with a variety of extra, optional tools
that solve common web development problems.
This code lives in :source:`django/contrib` in the Django distribution. This document
gives a rundown of the packages in ``contrib``, along with any dependencies
those packages have.
This code lives in :source:`django/contrib` in the Django distribution. This
document gives a rundown of the packages in ``contrib``, along with any
dependencies those packages have.
.. admonition:: Including ``contrib`` packages in ``INSTALLED_APPS``

View File

@@ -104,19 +104,19 @@ templates.
The built-in levels, which can be imported from ``django.contrib.messages``
directly, are:
=========== ========
=========== =========================================================================================
Constant Purpose
=========== ========
=========== =========================================================================================
``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
``INFO`` Informational messages for the user
``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
``WARNING`` A failure did not occur but may be imminent
``ERROR`` An action was **not** successful or some other failure occurred
=========== ========
=========== =========================================================================================
The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
(or it can be `changed per request`_). Attempts to add messages of a level less
than this will be ignored.
The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded
level (or it can be `changed per request`_). Attempts to add messages of a
level less than this will be ignored.
.. _`changed per request`: `Changing the minimum recorded level per-request`_

View File

@@ -11,8 +11,8 @@ Indexing these fields
=====================
:class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a
B-tree index, which isn't particularly helpful when querying complex data types.
Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
B-tree index, which isn't particularly helpful when querying complex data
types. Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
:class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though
the index choice is dependent on the queries that you're using. Generally, GiST
may be a good choice for the :ref:`range fields <range-fields>` and
@@ -450,8 +450,8 @@ operator ``?|``. For example:
``has_keys``
~~~~~~~~~~~~
Returns objects where all of the given keys are in the data. Uses the SQL operator
``?&``. For example:
Returns objects where all of the given keys are in the data. Uses the SQL
operator ``?&``. For example:
.. code-block:: pycon
@@ -741,8 +741,8 @@ passed range.
``not_gt``
^^^^^^^^^^
The returned ranges do not contain any points greater than the passed range, that
is the upper bound of the returned range is at most the upper bound of the
The returned ranges do not contain any points greater than the passed range,
that is the upper bound of the returned range is at most the upper bound of the
passed range.
>>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))

View File

@@ -88,7 +88,8 @@ can be chained with other lookup functions. To use it, you need to add
``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS` and activate
the `unaccent extension on PostgreSQL`_. The
:class:`~django.contrib.postgres.operations.UnaccentExtension` migration
operation is available if you want to perform this activation using migrations).
operation is available if you want to perform this activation using
migrations).
.. _unaccent extension on PostgreSQL: https://www.postgresql.org/docs/current/unaccent.html
@@ -105,7 +106,7 @@ The ``unaccent`` lookup can be used on
.. warning::
``unaccent`` lookups should perform fine in most use cases. However, queries
using this filter will generally perform full table scans, which can be slow
on large tables. In those cases, using dedicated full text indexing tools
might be appropriate.
``unaccent`` lookups should perform fine in most use cases. However,
queries using this filter will generally perform full table scans, which
can be slow on large tables. In those cases, using dedicated full text
indexing tools might be appropriate.

View File

@@ -295,8 +295,7 @@ the search vector you wish to use. For example::
name="search_vector_idx",
)
The PostgreSQL documentation has details on
`creating indexes for full text search
The PostgreSQL docs has details on `creating indexes for full text search
<https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.
``SearchVectorField``

View File

@@ -16,7 +16,8 @@ To install the redirects app, follow these steps:
#. Ensure that the ``django.contrib.sites`` framework
:ref:`is installed <enabling-the-sites-framework>`.
#. Add ``'django.contrib.redirects'`` to your :setting:`INSTALLED_APPS` setting.
#. Add ``'django.contrib.redirects'`` to your :setting:`INSTALLED_APPS`
setting.
#. Add ``'django.contrib.redirects.middleware.RedirectFallbackMiddleware'``
to your :setting:`MIDDLEWARE` setting.
#. Run the command :djadmin:`manage.py migrate <migrate>`.
@@ -24,8 +25,8 @@ To install the redirects app, follow these steps:
How it works
============
``manage.py migrate`` creates a ``django_redirect`` table in your database. This
is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
``manage.py migrate`` creates a ``django_redirect`` table in your database.
This is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
The :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
does all of the work. Each time any Django application raises a 404
@@ -71,10 +72,11 @@ Via the Python API
.. class:: models.Redirect
Redirects are represented by a standard :doc:`Django model </topics/db/models>`,
which lives in :source:`django/contrib/redirects/models.py`. You can access
redirect objects via the :doc:`Django database API </topics/db/queries>`.
For example:
Redirects are represented by a standard
:doc:`Django model </topics/db/models>`, which lives in
:source:`django/contrib/redirects/models.py`. You can access redirect
objects via the :doc:`Django database API </topics/db/queries>`. For
example:
.. code-block:: pycon

View File

@@ -61,12 +61,13 @@ To activate sitemap generation on your Django site, add this line to your
name="django.contrib.sitemaps.views.sitemap",
)
This tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`.
This tells Django to build a sitemap when a client accesses
:file:`/sitemap.xml`.
The name of the sitemap file is not important, but the location is. Search
engines will only index links in your sitemap for the current URL level and
below. For instance, if :file:`sitemap.xml` lives in your root directory, it may
reference any URL in your site. However, if your sitemap lives at
below. For instance, if :file:`sitemap.xml` lives in your root directory, it
may reference any URL in your site. However, if your sitemap lives at
:file:`/content/sitemap.xml`, it may only reference URLs that begin with
:file:`/content/`.
@@ -424,8 +425,9 @@ The sitemap framework also has the ability to create a sitemap index that
references individual sitemap files, one per each section defined in your
``sitemaps`` dictionary. The only differences in usage are:
* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
and :func:`django.contrib.sitemaps.views.sitemap`.
* You use two views in your URLconf:
:func:`django.contrib.sitemaps.views.index` and
:func:`django.contrib.sitemaps.views.sitemap`.
* The :func:`django.contrib.sitemaps.views.sitemap` view should take a
``section`` keyword argument.

View File

@@ -160,7 +160,8 @@ it is not.
If you don't have access to the request object, you can use the
``get_current()`` method of the :class:`~django.contrib.sites.models.Site`
model's manager. You should then ensure that your settings file does contain
the :setting:`SITE_ID` setting. This example is equivalent to the previous one::
the :setting:`SITE_ID` setting. This example is equivalent to the previous
one::
from django.contrib.sites.models import Site
@@ -291,9 +292,10 @@ Caching the current ``Site`` object
===================================
As the current site is stored in the database, each call to
``Site.objects.get_current()`` could result in a database query. But Django is a
little cleverer than that: on the first request, the current site is cached, and
any subsequent call returns the cached data instead of hitting the database.
``Site.objects.get_current()`` could result in a database query. But Django is
a little cleverer than that: on the first request, the current site is cached,
and any subsequent call returns the cached data instead of hitting the
database.
If for any reason you want to force a database query, you can tell Django to
clear the cache using ``Site.objects.clear_cache()``::
@@ -344,8 +346,9 @@ your model explicitly. For example::
on_site = CurrentSiteManager()
With this model, ``Photo.objects.all()`` will return all ``Photo`` objects in
the database, but ``Photo.on_site.all()`` will return only the ``Photo`` objects
associated with the current site, according to the :setting:`SITE_ID` setting.
the database, but ``Photo.on_site.all()`` will return only the ``Photo``
objects associated with the current site, according to the :setting:`SITE_ID`
setting.
Put another way, these two statements are equivalent::
@@ -381,8 +384,9 @@ demonstrates this::
objects = models.Manager()
on_site = CurrentSiteManager("publish_on")
If you attempt to use :class:`~django.contrib.sites.managers.CurrentSiteManager`
and pass a field name that doesn't exist, Django will raise a ``ValueError``.
If you attempt to use
:class:`~django.contrib.sites.managers.CurrentSiteManager` and pass a field
name that doesn't exist, Django will raise a ``ValueError``.
Finally, note that you'll probably want to keep a normal
(non-site-specific) ``Manager`` on your model, even if you use

View File

@@ -67,12 +67,12 @@ This is used by the
default.
By default, collected files receive permissions from
:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive permissions
from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would like different
permissions for these files and/or directories, you can subclass either of the
:ref:`static files storage classes <staticfiles-storages>` and specify the
``file_permissions_mode`` and/or ``directory_permissions_mode`` parameters,
respectively. For example::
:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive
permissions from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would
like different permissions for these files and/or directories, you can subclass
either of the :ref:`static files storage classes <staticfiles-storages>` and
specify the ``file_permissions_mode`` and/or ``directory_permissions_mode``
parameters, respectively. For example::
from django.contrib.staticfiles import storage
@@ -280,10 +280,11 @@ counterparts and update the cache appropriately.
.. class:: storage.ManifestStaticFilesStorage
A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
storage backend which stores the file names it handles by appending the MD5
hash of the file's content to the filename. For example, the file
``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
A subclass of the
:class:`~django.contrib.staticfiles.storage.StaticFilesStorage` storage backend
which stores the file names it handles by appending the MD5 hash of the file's
content to the filename. For example, the file ``css/styles.css`` would also be
saved as ``css/styles.55e7cbb9ba48.css``.
The purpose of this storage is to keep serving the old files in case some
pages still refer to those files, e.g. because they are cached by you or
@@ -551,12 +552,13 @@ Specialized test case to support 'live testing'
.. class:: testing.StaticLiveServerTestCase
This unittest TestCase subclass extends :class:`django.test.LiveServerTestCase`.
This unittest TestCase subclass extends
:class:`django.test.LiveServerTestCase`.
Just like its parent, you can use it to write tests that involve running the
code under test and consuming it with testing tools through HTTP (e.g. Selenium,
PhantomJS, etc.), because of which it's needed that the static assets are also
published.
code under test and consuming it with testing tools through HTTP (e.g.
Selenium, PhantomJS, etc.), because of which it's needed that the static assets
are also published.
But given the fact that it makes use of the
:func:`django.contrib.staticfiles.views.serve` view described above, it can

View File

@@ -106,8 +106,8 @@ Note:
See `Publishing Atom and RSS feeds in tandem`_, later, for an example.
One thing is left to do. In an RSS feed, each ``<item>`` has a ``<title>``,
``<link>`` and ``<description>``. We need to tell the framework what data to put
into those elements.
``<link>`` and ``<description>``. We need to tell the framework what data to
put into those elements.
* For the contents of ``<title>`` and ``<description>``, Django tries
calling the methods ``item_title()`` and ``item_description()`` on
@@ -138,10 +138,10 @@ into those elements.
.. method:: Feed.get_context_data(**kwargs)
There is also a way to pass additional information to title and description
templates, if you need to supply more than the two variables mentioned
before. You can provide your implementation of ``get_context_data`` method
in your ``Feed`` subclass. For example::
There is also a way to pass additional information to title and
description templates, if you need to supply more than the two variables
mentioned before. You can provide your implementation of
``get_context_data`` method in your ``Feed`` subclass. For example::
from mysite.models import Article
from django.contrib.syndication.views import Feed
@@ -204,11 +204,11 @@ The framework also supports more complex feeds, via arguments.
For example, a website could offer an RSS feed of recent crimes for every
police beat in a city. It'd be silly to create a separate
:class:`~django.contrib.syndication.views.Feed` class for each police beat; that
would violate the :ref:`DRY principle <dry>` and would couple data to
:class:`~django.contrib.syndication.views.Feed` class for each police beat;
that would violate the :ref:`DRY principle <dry>` and would couple data to
programming logic. Instead, the syndication framework lets you access the
arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output
items based on information in the feed's URL.
arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can
output items based on information in the feed's URL.
The police beat feeds could be accessible via URLs like this:
@@ -311,8 +311,8 @@ Language
Feeds created by the syndication framework automatically include the
appropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). By
default, this is :func:`django.utils.translation.get_language`. You can change it
by setting the ``language`` class attribute.
default, this is :func:`django.utils.translation.get_language`. You can change
it by setting the ``language`` class attribute.
URLs
----
@@ -1033,7 +1033,8 @@ They share this interface:
* ``categories`` should be a sequence of strings.
:meth:`.SyndicationFeed.write`
Outputs the feed in the given encoding to outfile, which is a file-like object.
Outputs the feed in the given encoding to outfile, which is a file-like
object.
:meth:`.SyndicationFeed.writeString`
Returns the feed as a string in the given encoding.
@@ -1078,8 +1079,8 @@ If the feed format is totally custom, you'll want to subclass
However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS_, Apple's
`iTunes podcast format`_, etc.), you've got a better choice. These types of
feeds typically add extra elements and/or attributes to the underlying format,
and there are a set of methods that ``SyndicationFeed`` calls to get these extra
attributes. Thus, you can subclass the appropriate feed generator class
and there are a set of methods that ``SyndicationFeed`` calls to get these
extra attributes. Thus, you can subclass the appropriate feed generator class
(``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:
.. _georss: https://georss.org
@@ -1106,10 +1107,11 @@ attributes. Thus, you can subclass the appropriate feed generator class
.. warning::
If you override any of these methods, be sure to call the superclass methods
since they add the required elements for each feed format.
If you override any of these methods, be sure to call the superclass
methods since they add the required elements for each feed format.
For example, you might start implementing an iTunes RSS feed generator like so::
For example, you might start implementing an iTunes RSS feed generator like
so::
class iTunesFeed(Rss201rev2Feed):
def root_attributes(self):