mirror of
https://github.com/django/django.git
synced 2025-08-26 11:49:12 +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:
parent
4286a23df6
commit
f81e6e3a53
@ -22,8 +22,8 @@ only allows access to users with those two fields both set to True.
|
|||||||
How do I automatically set a field's value to the user who last edited the object in the admin?
|
How do I automatically set a field's value to the user who last edited the object in the admin?
|
||||||
===============================================================================================
|
===============================================================================================
|
||||||
|
|
||||||
The :class:`~django.contrib.admin.ModelAdmin` class provides customization hooks
|
The :class:`~django.contrib.admin.ModelAdmin` class provides customization
|
||||||
that allow you to transform an object as it saved, using details from the
|
hooks that allow you to transform an object as it saved, using details from the
|
||||||
request. By extracting the current user from the request, and customizing the
|
request. By extracting the current user from the request, and customizing the
|
||||||
:meth:`~django.contrib.admin.ModelAdmin.save_model` hook, you can update an
|
:meth:`~django.contrib.admin.ModelAdmin.save_model` hook, you can update an
|
||||||
object to reflect the user that edited it. See :ref:`the documentation on
|
object to reflect the user that edited it. See :ref:`the documentation on
|
||||||
@ -33,8 +33,8 @@ How do I limit admin access so that objects can only be edited by the users who
|
|||||||
=============================================================================================
|
=============================================================================================
|
||||||
|
|
||||||
The :class:`~django.contrib.admin.ModelAdmin` class also provides customization
|
The :class:`~django.contrib.admin.ModelAdmin` class also provides customization
|
||||||
hooks that allow you to control the visibility and editability of objects in the
|
hooks that allow you to control the visibility and editability of objects in
|
||||||
admin. Using the same trick of extracting the user from the request, the
|
the admin. Using the same trick of extracting the user from the request, the
|
||||||
:meth:`~django.contrib.admin.ModelAdmin.get_queryset` and
|
:meth:`~django.contrib.admin.ModelAdmin.get_queryset` and
|
||||||
:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` can be used to
|
:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` can be used to
|
||||||
control the visibility and editability of objects in the admin.
|
control the visibility and editability of objects in the admin.
|
||||||
|
@ -32,8 +32,9 @@ thrilled to be able to give something back to the open-source community.
|
|||||||
What does "Django" mean, and how do you pronounce it?
|
What does "Django" mean, and how do you pronounce it?
|
||||||
=====================================================
|
=====================================================
|
||||||
|
|
||||||
Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the 1930s
|
Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the
|
||||||
to early 1950s. To this day, he's considered one of the best guitarists of all time.
|
1930s to early 1950s. To this day, he's considered one of the best guitarists
|
||||||
|
of all time.
|
||||||
|
|
||||||
Listen to his music. You'll like it.
|
Listen to his music. You'll like it.
|
||||||
|
|
||||||
@ -185,9 +186,10 @@ corresponds to a web page on the official Django site.
|
|||||||
Because the documentation is :source:`stored in revision control <docs>`, you
|
Because the documentation is :source:`stored in revision control <docs>`, you
|
||||||
can browse documentation changes just like you can browse code changes.
|
can browse documentation changes just like you can browse code changes.
|
||||||
|
|
||||||
Technically, the docs on Django's site are generated from the latest development
|
Technically, the docs on Django's site are generated from the latest
|
||||||
versions of those reST documents, so the docs on the Django site may offer more
|
development versions of those reST documents, so the docs on the Django site
|
||||||
information than the docs that come with the latest Django release.
|
may offer more information than the docs that come with the latest Django
|
||||||
|
release.
|
||||||
|
|
||||||
How do I cite Django?
|
How do I cite Django?
|
||||||
=====================
|
=====================
|
||||||
|
@ -8,8 +8,8 @@ How do I get started?
|
|||||||
#. `Download the code`_.
|
#. `Download the code`_.
|
||||||
#. Install Django (read the :doc:`installation guide </intro/install>`).
|
#. Install Django (read the :doc:`installation guide </intro/install>`).
|
||||||
#. Walk through the :doc:`tutorial </intro/tutorial01>`.
|
#. Walk through the :doc:`tutorial </intro/tutorial01>`.
|
||||||
#. Check out the rest of the :doc:`documentation </index>`, and `ask questions`_ if you
|
#. Check out the rest of the :doc:`documentation </index>`, and
|
||||||
run into trouble.
|
`ask questions`_ if you run into trouble.
|
||||||
|
|
||||||
.. _`Download the code`: https://www.djangoproject.com/download/
|
.. _`Download the code`: https://www.djangoproject.com/download/
|
||||||
.. _ask questions: https://www.djangoproject.com/community/
|
.. _ask questions: https://www.djangoproject.com/community/
|
||||||
|
@ -27,8 +27,8 @@ the following:
|
|||||||
``connection.queries`` includes all SQL statements -- INSERTs, UPDATES,
|
``connection.queries`` includes all SQL statements -- INSERTs, UPDATES,
|
||||||
SELECTs, etc. Each time your app hits the database, the query will be recorded.
|
SELECTs, etc. Each time your app hits the database, the query will be recorded.
|
||||||
|
|
||||||
If you are using :doc:`multiple databases</topics/db/multi-db>`, you can use the
|
If you are using :doc:`multiple databases</topics/db/multi-db>`, you can use
|
||||||
same interface on each member of the ``connections`` dictionary:
|
the same interface on each member of the ``connections`` dictionary:
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
|
|
||||||
|
@ -51,7 +51,8 @@ Glossary
|
|||||||
See :class:`property`.
|
See :class:`property`.
|
||||||
|
|
||||||
queryset
|
queryset
|
||||||
An object representing some set of rows to be fetched from the database.
|
An object representing some set of rows to be fetched from the
|
||||||
|
database.
|
||||||
|
|
||||||
See :doc:`/topics/db/queries`.
|
See :doc:`/topics/db/queries`.
|
||||||
|
|
||||||
|
@ -37,9 +37,9 @@ Using CSRF protection with AJAX
|
|||||||
===============================
|
===============================
|
||||||
|
|
||||||
While the above method can be used for AJAX POST requests, it has some
|
While the above method can be used for AJAX POST requests, it has some
|
||||||
inconveniences: you have to remember to pass the CSRF token in as POST data with
|
inconveniences: you have to remember to pass the CSRF token in as POST data
|
||||||
every POST request. For this reason, there is an alternative method: on each
|
with every POST request. For this reason, there is an alternative method: on
|
||||||
XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
|
each XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
|
||||||
:setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is
|
:setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is
|
||||||
often easier because many JavaScript frameworks provide hooks that allow
|
often easier because many JavaScript frameworks provide hooks that allow
|
||||||
headers to be set on every request.
|
headers to be set on every request.
|
||||||
@ -217,11 +217,11 @@ Testing and CSRF protection
|
|||||||
===========================
|
===========================
|
||||||
|
|
||||||
The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
|
The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
|
||||||
functions, due to the need for the CSRF token which must be sent with every POST
|
functions, due to the need for the CSRF token which must be sent with every
|
||||||
request. For this reason, Django's HTTP client for tests has been modified to
|
POST request. For this reason, Django's HTTP client for tests has been modified
|
||||||
set a flag on requests which relaxes the middleware and the ``csrf_protect``
|
to set a flag on requests which relaxes the middleware and the ``csrf_protect``
|
||||||
decorator so that they no longer rejects requests. In every other respect
|
decorator so that they no longer rejects requests. In every other respect (e.g.
|
||||||
(e.g. sending cookies etc.), they behave the same.
|
sending cookies etc.), they behave the same.
|
||||||
|
|
||||||
If, for some reason, you *want* the test client to perform CSRF
|
If, for some reason, you *want* the test client to perform CSRF
|
||||||
checks, you can create an instance of the test client that enforces
|
checks, you can create an instance of the test client that enforces
|
||||||
@ -237,8 +237,8 @@ Edge cases
|
|||||||
|
|
||||||
Certain views can have unusual requirements that mean they don't fit the normal
|
Certain views can have unusual requirements that mean they don't fit the normal
|
||||||
pattern envisaged here. A number of utilities can be useful in these
|
pattern envisaged here. A number of utilities can be useful in these
|
||||||
situations. The scenarios they might be needed in are described in the following
|
situations. The scenarios they might be needed in are described in the
|
||||||
section.
|
following section.
|
||||||
|
|
||||||
Disabling CSRF protection for just a few views
|
Disabling CSRF protection for just a few views
|
||||||
----------------------------------------------
|
----------------------------------------------
|
||||||
@ -265,8 +265,8 @@ There may be some views that are unprotected and have been exempted by
|
|||||||
``csrf_exempt``, but still need to include the CSRF token.
|
``csrf_exempt``, but still need to include the CSRF token.
|
||||||
|
|
||||||
Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
|
Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
|
||||||
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
|
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e.
|
||||||
should be the innermost decorator).
|
``requires_csrf_token`` should be the innermost decorator).
|
||||||
|
|
||||||
Protecting a view for only one path
|
Protecting a view for only one path
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
@ -304,8 +304,8 @@ view that sends the page.
|
|||||||
CSRF protection in reusable applications
|
CSRF protection in reusable applications
|
||||||
========================================
|
========================================
|
||||||
|
|
||||||
Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
|
Because it is possible for the developer to turn off the
|
||||||
all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
|
``CsrfViewMiddleware``, all relevant views in contrib apps use the
|
||||||
the security of these applications against CSRF. It is recommended that the
|
``csrf_protect`` decorator to ensure the security of these applications against
|
||||||
developers of other reusable apps that want the same guarantees also use the
|
CSRF. It is recommended that the developers of other reusable apps that want
|
||||||
``csrf_protect`` decorator on their views.
|
the same guarantees also use the ``csrf_protect`` decorator on their views.
|
||||||
|
@ -16,8 +16,9 @@ You'll need to follow these steps:
|
|||||||
|
|
||||||
class MyStorage(Storage): ...
|
class MyStorage(Storage): ...
|
||||||
|
|
||||||
#. Django must be able to instantiate your storage system without any arguments.
|
#. Django must be able to instantiate your storage system without any
|
||||||
This means that any settings should be taken from ``django.conf.settings``::
|
arguments. This means that any settings should be taken from
|
||||||
|
``django.conf.settings``::
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.files.storage import Storage
|
from django.core.files.storage import Storage
|
||||||
@ -36,10 +37,10 @@ You'll need to follow these steps:
|
|||||||
In addition, if your class provides local file storage, it must override
|
In addition, if your class provides local file storage, it must override
|
||||||
the ``path()`` method.
|
the ``path()`` method.
|
||||||
|
|
||||||
#. Your storage class must be :ref:`deconstructible <custom-deconstruct-method>`
|
#. Your storage class must be :ref:`deconstructible
|
||||||
so it can be serialized when it's used on a field in a migration. As long
|
<custom-deconstruct-method>` so it can be serialized when it's used on a
|
||||||
as your field has arguments that are themselves
|
field in a migration. As long as your field has arguments that are
|
||||||
:ref:`serializable <migration-serializing>`, you can use the
|
themselves :ref:`serializable <migration-serializing>`, you can use the
|
||||||
``django.utils.deconstruct.deconstructible`` class decorator for this
|
``django.utils.deconstruct.deconstructible`` class decorator for this
|
||||||
(that's what Django uses on FileSystemStorage).
|
(that's what Django uses on FileSystemStorage).
|
||||||
|
|
||||||
@ -73,16 +74,16 @@ objects. These are:
|
|||||||
**Required**.
|
**Required**.
|
||||||
|
|
||||||
Called by ``Storage.open()``, this is the actual mechanism the storage class
|
Called by ``Storage.open()``, this is the actual mechanism the storage class
|
||||||
uses to open the file. This must return a ``File`` object, though in most cases,
|
uses to open the file. This must return a ``File`` object, though in most
|
||||||
you'll want to return some subclass here that implements logic specific to the
|
cases, you'll want to return some subclass here that implements logic specific
|
||||||
backend storage system. The :exc:`FileNotFoundError` exception should be raised
|
to the backend storage system. The :exc:`FileNotFoundError` exception should be
|
||||||
when a file doesn't exist.
|
raised when a file doesn't exist.
|
||||||
|
|
||||||
.. method:: _save(name, content)
|
.. method:: _save(name, content)
|
||||||
|
|
||||||
Called by ``Storage.save()``. The ``name`` will already have gone through
|
Called by ``Storage.save()``. The ``name`` will already have gone through
|
||||||
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
|
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be
|
||||||
``File`` object itself.
|
a ``File`` object itself.
|
||||||
|
|
||||||
Should return the actual name of the file saved (usually the ``name`` passed
|
Should return the actual name of the file saved (usually the ``name`` passed
|
||||||
in, but if the storage needs to change the file name return the new name
|
in, but if the storage needs to change the file name return the new name
|
||||||
|
@ -39,9 +39,9 @@ lookup, then we need to tell Django about it::
|
|||||||
return "%s <> %s" % (lhs, rhs), params
|
return "%s <> %s" % (lhs, rhs), params
|
||||||
|
|
||||||
To register the ``NotEqual`` lookup we will need to call ``register_lookup`` on
|
To register the ``NotEqual`` lookup we will need to call ``register_lookup`` on
|
||||||
the field class we want the lookup to be available for. In this case, the lookup
|
the field class we want the lookup to be available for. In this case, the
|
||||||
makes sense on all ``Field`` subclasses, so we register it with ``Field``
|
lookup makes sense on all ``Field`` subclasses, so we register it with
|
||||||
directly::
|
``Field`` directly::
|
||||||
|
|
||||||
from django.db.models import Field
|
from django.db.models import Field
|
||||||
|
|
||||||
@ -61,10 +61,10 @@ could place the implementation in a ``models.py`` file, or register the lookup
|
|||||||
in the ``ready()`` method of an ``AppConfig``.
|
in the ``ready()`` method of an ``AppConfig``.
|
||||||
|
|
||||||
Taking a closer look at the implementation, the first required attribute is
|
Taking a closer look at the implementation, the first required attribute is
|
||||||
``lookup_name``. This allows the ORM to understand how to interpret ``name__ne``
|
``lookup_name``. This allows the ORM to understand how to interpret
|
||||||
and use ``NotEqual`` to generate the SQL. By convention, these names are always
|
``name__ne`` and use ``NotEqual`` to generate the SQL. By convention, these
|
||||||
lowercase strings containing only letters, but the only hard requirement is
|
names are always lowercase strings containing only letters, but the only hard
|
||||||
that it must not contain the string ``__``.
|
requirement is that it must not contain the string ``__``.
|
||||||
|
|
||||||
We then need to define the ``as_sql`` method. This takes a ``SQLCompiler``
|
We then need to define the ``as_sql`` method. This takes a ``SQLCompiler``
|
||||||
object, called ``compiler``, and the active database connection.
|
object, called ``compiler``, and the active database connection.
|
||||||
@ -112,8 +112,8 @@ or where it did not exceed a certain amount
|
|||||||
functionality which is possible in a database backend independent manner,
|
functionality which is possible in a database backend independent manner,
|
||||||
and without duplicating functionality already in Django.
|
and without duplicating functionality already in Django.
|
||||||
|
|
||||||
We will start by writing an ``AbsoluteValue`` transformer. This will use the SQL
|
We will start by writing an ``AbsoluteValue`` transformer. This will use the
|
||||||
function ``ABS()`` to transform the value before comparison::
|
SQL function ``ABS()`` to transform the value before comparison::
|
||||||
|
|
||||||
from django.db.models import Transform
|
from django.db.models import Transform
|
||||||
|
|
||||||
@ -227,16 +227,16 @@ Notice also that as both sides are used multiple times in the query the params
|
|||||||
need to contain ``lhs_params`` and ``rhs_params`` multiple times.
|
need to contain ``lhs_params`` and ``rhs_params`` multiple times.
|
||||||
|
|
||||||
The final query does the inversion (``27`` to ``-27``) directly in the
|
The final query does the inversion (``27`` to ``-27``) directly in the
|
||||||
database. The reason for doing this is that if the ``self.rhs`` is something else
|
database. The reason for doing this is that if the ``self.rhs`` is something
|
||||||
than a plain integer value (for example an ``F()`` reference) we can't do the
|
else than a plain integer value (for example an ``F()`` reference) we can't do
|
||||||
transformations in Python.
|
the transformations in Python.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
In fact, most lookups with ``__abs`` could be implemented as range queries
|
In fact, most lookups with ``__abs`` could be implemented as range queries
|
||||||
like this, and on most database backends it is likely to be more sensible to
|
like this, and on most database backends it is likely to be more sensible
|
||||||
do so as you can make use of the indexes. However with PostgreSQL you may
|
to do so as you can make use of the indexes. However with PostgreSQL you
|
||||||
want to add an index on ``abs(change)`` which would allow these queries to
|
may want to add an index on ``abs(change)`` which would allow these queries
|
||||||
be very efficient.
|
to be very efficient.
|
||||||
|
|
||||||
A bilateral transformer example
|
A bilateral transformer example
|
||||||
===============================
|
===============================
|
||||||
@ -252,10 +252,10 @@ very useful in practice as Django already comes with a bunch of built-in
|
|||||||
case-insensitive lookups, but it will be a nice demonstration of bilateral
|
case-insensitive lookups, but it will be a nice demonstration of bilateral
|
||||||
transformations in a database-agnostic way.
|
transformations in a database-agnostic way.
|
||||||
|
|
||||||
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to
|
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()``
|
||||||
transform the values before comparison. We define
|
to transform the values before comparison. We define :attr:`bilateral = True
|
||||||
:attr:`bilateral = True <django.db.models.Transform.bilateral>` to indicate that
|
<django.db.models.Transform.bilateral>` to indicate that this transformation
|
||||||
this transformation should apply to both ``lhs`` and ``rhs``::
|
should apply to both ``lhs`` and ``rhs``::
|
||||||
|
|
||||||
from django.db.models import Transform
|
from django.db.models import Transform
|
||||||
|
|
||||||
@ -272,8 +272,8 @@ Next, let's register it::
|
|||||||
CharField.register_lookup(UpperCase)
|
CharField.register_lookup(UpperCase)
|
||||||
TextField.register_lookup(UpperCase)
|
TextField.register_lookup(UpperCase)
|
||||||
|
|
||||||
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a case
|
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a
|
||||||
insensitive query like this:
|
case insensitive query like this:
|
||||||
|
|
||||||
.. code-block:: sql
|
.. code-block:: sql
|
||||||
|
|
||||||
|
@ -28,8 +28,8 @@ whose name doesn't begin with an underscore. For example:
|
|||||||
tests.py
|
tests.py
|
||||||
views.py
|
views.py
|
||||||
|
|
||||||
In this example, the ``closepoll`` command will be made available to any project
|
In this example, the ``closepoll`` command will be made available to any
|
||||||
that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
|
project that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
|
||||||
|
|
||||||
The ``_private.py`` module will not be available as a management command.
|
The ``_private.py`` module will not be available as a management command.
|
||||||
|
|
||||||
@ -73,13 +73,12 @@ look like this::
|
|||||||
.. _management-commands-output:
|
.. _management-commands-output:
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
When you are using management commands and wish to provide console
|
When you are using management commands and wish to provide console output,
|
||||||
output, you should write to ``self.stdout`` and ``self.stderr``,
|
you should write to ``self.stdout`` and ``self.stderr``, instead of
|
||||||
instead of printing to ``stdout`` and ``stderr`` directly. By
|
printing to ``stdout`` and ``stderr`` directly. By using these proxies, it
|
||||||
using these proxies, it becomes much easier to test your custom
|
becomes much easier to test your custom command. Note also that you don't
|
||||||
command. Note also that you don't need to end messages with a newline
|
need to end messages with a newline character, it will be added
|
||||||
character, it will be added automatically, unless you specify the ``ending``
|
automatically, unless you specify the ``ending`` parameter::
|
||||||
parameter::
|
|
||||||
|
|
||||||
self.stdout.write("Unterminated line", ending="")
|
self.stdout.write("Unterminated line", ending="")
|
||||||
|
|
||||||
@ -99,7 +98,8 @@ Accepting optional arguments
|
|||||||
|
|
||||||
The same ``closepoll`` could be easily modified to delete a given poll instead
|
The same ``closepoll`` could be easily modified to delete a given poll instead
|
||||||
of closing it by accepting additional command line options. These custom
|
of closing it by accepting additional command line options. These custom
|
||||||
options can be added in the :meth:`~BaseCommand.add_arguments` method like this::
|
options can be added in the :meth:`~BaseCommand.add_arguments` method like
|
||||||
|
this::
|
||||||
|
|
||||||
class Command(BaseCommand):
|
class Command(BaseCommand):
|
||||||
def add_arguments(self, parser):
|
def add_arguments(self, parser):
|
||||||
@ -273,7 +273,8 @@ the :meth:`~BaseCommand.handle` method must be implemented.
|
|||||||
Django.
|
Django.
|
||||||
|
|
||||||
You can customize the instance by overriding this method and calling
|
You can customize the instance by overriding this method and calling
|
||||||
``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters.
|
``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser`
|
||||||
|
parameters.
|
||||||
|
|
||||||
.. method:: BaseCommand.add_arguments(parser)
|
.. method:: BaseCommand.add_arguments(parser)
|
||||||
|
|
||||||
|
@ -7,17 +7,18 @@ How to create custom model fields
|
|||||||
Introduction
|
Introduction
|
||||||
============
|
============
|
||||||
|
|
||||||
The :doc:`model reference </topics/db/models>` documentation explains how to use
|
The :doc:`model reference </topics/db/models>` documentation explains how to
|
||||||
Django's standard field classes -- :class:`~django.db.models.CharField`,
|
use Django's standard field classes -- :class:`~django.db.models.CharField`,
|
||||||
:class:`~django.db.models.DateField`, etc. For many purposes, those classes are
|
:class:`~django.db.models.DateField`, etc. For many purposes, those classes are
|
||||||
all you'll need. Sometimes, though, the Django version won't meet your precise
|
all you'll need. Sometimes, though, the Django version won't meet your precise
|
||||||
requirements, or you'll want to use a field that is entirely different from
|
requirements, or you'll want to use a field that is entirely different from
|
||||||
those shipped with Django.
|
those shipped with Django.
|
||||||
|
|
||||||
Django's built-in field types don't cover every possible database column type --
|
Django's built-in field types don't cover every possible database column type
|
||||||
only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
|
-- only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
|
||||||
column types, such as geographic polygons or even user-created types such as
|
column types, such as geographic polygons or even user-created types such as
|
||||||
`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.
|
`PostgreSQL custom types`_, you can define your own Django ``Field``
|
||||||
|
subclasses.
|
||||||
|
|
||||||
.. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html
|
.. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html
|
||||||
|
|
||||||
@ -106,13 +107,13 @@ What does a field class do?
|
|||||||
---------------------------
|
---------------------------
|
||||||
|
|
||||||
All of Django's fields (and when we say *fields* in this document, we always
|
All of Django's fields (and when we say *fields* in this document, we always
|
||||||
mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
|
mean model fields and not :doc:`form fields </ref/forms/fields>`) are
|
||||||
of :class:`django.db.models.Field`. Most of the information that Django records
|
subclasses of :class:`django.db.models.Field`. Most of the information that
|
||||||
about a field is common to all fields -- name, help text, uniqueness and so
|
Django records about a field is common to all fields -- name, help text,
|
||||||
forth. Storing all that information is handled by ``Field``. We'll get into the
|
uniqueness and so forth. Storing all that information is handled by ``Field``.
|
||||||
precise details of what ``Field`` can do later on; for now, suffice it to say
|
We'll get into the precise details of what ``Field`` can do later on; for now,
|
||||||
that everything descends from ``Field`` and then customizes key pieces of the
|
suffice it to say that everything descends from ``Field`` and then customizes
|
||||||
class behavior.
|
key pieces of the class behavior.
|
||||||
|
|
||||||
It's important to realize that a Django field class is not what is stored in
|
It's important to realize that a Django field class is not what is stored in
|
||||||
your model attributes. The model attributes contain normal Python objects. The
|
your model attributes. The model attributes contain normal Python objects. The
|
||||||
@ -149,9 +150,9 @@ is most similar to. Can you subclass an existing Django field and save yourself
|
|||||||
some work? If not, you should subclass the :class:`~django.db.models.Field`
|
some work? If not, you should subclass the :class:`~django.db.models.Field`
|
||||||
class, from which everything is descended.
|
class, from which everything is descended.
|
||||||
|
|
||||||
Initializing your new field is a matter of separating out any arguments that are
|
Initializing your new field is a matter of separating out any arguments that
|
||||||
specific to your case from the common arguments and passing the latter to the
|
are specific to your case from the common arguments and passing the latter to
|
||||||
``__init__()`` method of :class:`~django.db.models.Field` (or your parent
|
the ``__init__()`` method of :class:`~django.db.models.Field` (or your parent
|
||||||
class).
|
class).
|
||||||
|
|
||||||
In our example, we'll call our field ``HandField``. (It's a good idea to call
|
In our example, we'll call our field ``HandField``. (It's a good idea to call
|
||||||
@ -214,9 +215,9 @@ The ``Field.__init__()`` method takes the following parameters:
|
|||||||
* :attr:`~django.db.models.Field.choices`
|
* :attr:`~django.db.models.Field.choices`
|
||||||
* :attr:`~django.db.models.Field.help_text`
|
* :attr:`~django.db.models.Field.help_text`
|
||||||
* :attr:`~django.db.models.Field.db_column`
|
* :attr:`~django.db.models.Field.db_column`
|
||||||
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
|
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if
|
||||||
backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
|
the backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can
|
||||||
ignore this option.
|
usually ignore this option.
|
||||||
* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was
|
* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was
|
||||||
automatically created, as for the :class:`~django.db.models.OneToOneField`
|
automatically created, as for the :class:`~django.db.models.OneToOneField`
|
||||||
used by model inheritance. For advanced use only.
|
used by model inheritance. For advanced use only.
|
||||||
@ -253,9 +254,9 @@ name and import path. You do, however, have to care about the positional
|
|||||||
and keyword arguments, as these are likely the things you are changing.
|
and keyword arguments, as these are likely the things you are changing.
|
||||||
|
|
||||||
For example, in our ``HandField`` class we're always forcibly setting
|
For example, in our ``HandField`` class we're always forcibly setting
|
||||||
max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``
|
max_length in ``__init__()``. The ``deconstruct()`` method on the base
|
||||||
class will see this and try to return it in the keyword arguments; thus,
|
``Field`` class will see this and try to return it in the keyword arguments;
|
||||||
we can drop it from the keyword arguments for readability::
|
thus, we can drop it from the keyword arguments for readability::
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
@ -471,10 +472,11 @@ over this field. You are then responsible for creating the column in the right
|
|||||||
table in some other way, but this gives you a way to tell Django to get out of
|
table in some other way, but this gives you a way to tell Django to get out of
|
||||||
the way.
|
the way.
|
||||||
|
|
||||||
The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``
|
The :meth:`~Field.rel_db_type` method is called by fields such as
|
||||||
and ``OneToOneField`` that point to another field to determine their database
|
``ForeignKey`` and ``OneToOneField`` that point to another field to determine
|
||||||
column data types. For example, if you have an ``UnsignedAutoField``, you also
|
their database column data types. For example, if you have an
|
||||||
need the foreign keys that point to that field to use the same data type::
|
``UnsignedAutoField``, you also need the foreign keys that point to that field
|
||||||
|
to use the same data type::
|
||||||
|
|
||||||
# MySQL unsigned integer (range 0 to 4294967295).
|
# MySQL unsigned integer (range 0 to 4294967295).
|
||||||
class UnsignedAutoField(models.AutoField):
|
class UnsignedAutoField(models.AutoField):
|
||||||
@ -648,8 +650,8 @@ a custom form field (and even a form widget). See the :doc:`forms documentation
|
|||||||
If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you
|
If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you
|
||||||
can override the :meth:`~Field.formfield` method to return ``None``.
|
can override the :meth:`~Field.formfield` method to return ``None``.
|
||||||
|
|
||||||
Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
|
Continuing our ongoing example, we can write the :meth:`~Field.formfield`
|
||||||
as::
|
method as::
|
||||||
|
|
||||||
class HandField(models.Field):
|
class HandField(models.Field):
|
||||||
# ...
|
# ...
|
||||||
|
@ -285,13 +285,13 @@ Template filter code falls into one of two situations:
|
|||||||
order to make things easier for your template authors.
|
order to make things easier for your template authors.
|
||||||
|
|
||||||
In order for your filter to know the current auto-escaping state, set the
|
In order for your filter to know the current auto-escaping state, set the
|
||||||
``needs_autoescape`` flag to ``True`` when you register your filter function.
|
``needs_autoescape`` flag to ``True`` when you register your filter
|
||||||
(If you don't specify this flag, it defaults to ``False``). This flag tells
|
function. (If you don't specify this flag, it defaults to ``False``). This
|
||||||
Django that your filter function wants to be passed an extra keyword
|
flag tells Django that your filter function wants to be passed an extra
|
||||||
argument, called ``autoescape``, that is ``True`` if auto-escaping is in
|
keyword argument, called ``autoescape``, that is ``True`` if auto-escaping
|
||||||
effect and ``False`` otherwise. It is recommended to set the default of the
|
is in effect and ``False`` otherwise. It is recommended to set the default
|
||||||
``autoescape`` parameter to ``True``, so that if you call the function
|
of the ``autoescape`` parameter to ``True``, so that if you call the
|
||||||
from Python code it will have escaping enabled by default.
|
function from Python code it will have escaping enabled by default.
|
||||||
|
|
||||||
For example, let's write a filter that emphasizes the first character of
|
For example, let's write a filter that emphasizes the first character of
|
||||||
a string::
|
a string::
|
||||||
@ -827,8 +827,8 @@ Advanced custom template tags
|
|||||||
-----------------------------
|
-----------------------------
|
||||||
|
|
||||||
Sometimes the basic features for custom template tag creation aren't enough.
|
Sometimes the basic features for custom template tag creation aren't enough.
|
||||||
Don't worry, Django gives you complete access to the internals required to build
|
Don't worry, Django gives you complete access to the internals required to
|
||||||
a template tag from the ground up.
|
build a template tag from the ground up.
|
||||||
|
|
||||||
A quick overview
|
A quick overview
|
||||||
----------------
|
----------------
|
||||||
@ -856,10 +856,10 @@ function with the tag contents and the parser object itself. This function is
|
|||||||
responsible for returning a ``Node`` instance based on the contents of the tag.
|
responsible for returning a ``Node`` instance based on the contents of the tag.
|
||||||
|
|
||||||
For example, let's write a full implementation of our template tag,
|
For example, let's write a full implementation of our template tag,
|
||||||
``{% current_time %}``, that displays the current date/time, formatted according
|
``{% current_time %}``, that displays the current date/time, formatted
|
||||||
to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good
|
according to a parameter given in the tag, in :func:`~time.strftime` syntax.
|
||||||
idea to decide the tag syntax before anything else. In our case, let's say the
|
It's a good idea to decide the tag syntax before anything else. In our case,
|
||||||
tag should be used like this:
|
let's say the tag should be used like this:
|
||||||
|
|
||||||
.. code-block:: html+django
|
.. code-block:: html+django
|
||||||
|
|
||||||
@ -1300,9 +1300,10 @@ Here's how a simplified ``{% comment %}`` tag might be implemented::
|
|||||||
The actual implementation of :ttag:`{% comment %}<comment>` is slightly
|
The actual implementation of :ttag:`{% comment %}<comment>` is slightly
|
||||||
different in that it allows broken template tags to appear between
|
different in that it allows broken template tags to appear between
|
||||||
``{% comment %}`` and ``{% endcomment %}``. It does so by calling
|
``{% comment %}`` and ``{% endcomment %}``. It does so by calling
|
||||||
``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))``
|
``parser.skip_past('endcomment')`` instead of
|
||||||
followed by ``parser.delete_first_token()``, thus avoiding the generation of a
|
``parser.parse(('endcomment',))`` followed by
|
||||||
node list.
|
``parser.delete_first_token()``, thus avoiding the generation of a node
|
||||||
|
list.
|
||||||
|
|
||||||
``parser.parse()`` takes a tuple of names of block tags *to parse until*. It
|
``parser.parse()`` takes a tuple of names of block tags *to parse until*. It
|
||||||
returns an instance of ``django.template.NodeList``, which is a list of
|
returns an instance of ``django.template.NodeList``, which is a list of
|
||||||
|
@ -40,8 +40,9 @@ For more advanced usage, please read the `Uvicorn documentation <Uvicorn_>`_.
|
|||||||
Deploying Django using Uvicorn and Gunicorn
|
Deploying Django using Uvicorn and Gunicorn
|
||||||
===========================================
|
===========================================
|
||||||
|
|
||||||
Gunicorn_ is a robust web server that implements process monitoring and automatic
|
Gunicorn_ is a robust web server that implements process monitoring and
|
||||||
restarts. This can be useful when running Uvicorn in a production environment.
|
automatic restarts. This can be useful when running Uvicorn in a production
|
||||||
|
environment.
|
||||||
|
|
||||||
To install Uvicorn and Gunicorn, use the following:
|
To install Uvicorn and Gunicorn, use the following:
|
||||||
|
|
||||||
|
@ -2,10 +2,10 @@
|
|||||||
How to authenticate against Django's user database from Apache
|
How to authenticate against Django's user database from Apache
|
||||||
==============================================================
|
==============================================================
|
||||||
|
|
||||||
Since keeping multiple authentication databases in sync is a common problem when
|
Since keeping multiple authentication databases in sync is a common problem
|
||||||
dealing with Apache, you can configure Apache to authenticate against Django's
|
when dealing with Apache, you can configure Apache to authenticate against
|
||||||
:doc:`authentication system </topics/auth/index>` directly. This requires Apache
|
Django's :doc:`authentication system </topics/auth/index>` directly. This
|
||||||
version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
|
requires Apache version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
|
||||||
|
|
||||||
* Serve static/media files directly from Apache only to authenticated users.
|
* Serve static/media files directly from Apache only to authenticated users.
|
||||||
|
|
||||||
|
@ -37,9 +37,9 @@ deployments.
|
|||||||
|
|
||||||
WSGI servers obtain the path to the ``application`` callable from their
|
WSGI servers obtain the path to the ``application`` callable from their
|
||||||
configuration. Django's built-in server, namely the :djadmin:`runserver`
|
configuration. Django's built-in server, namely the :djadmin:`runserver`
|
||||||
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's
|
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default,
|
||||||
set to ``<project_name>.wsgi.application``, which points to the ``application``
|
it's set to ``<project_name>.wsgi.application``, which points to the
|
||||||
callable in :file:`<project_name>/wsgi.py`.
|
``application`` callable in :file:`<project_name>/wsgi.py`.
|
||||||
|
|
||||||
Configuring the settings module
|
Configuring the settings module
|
||||||
===============================
|
===============================
|
||||||
|
@ -124,8 +124,8 @@ use ``WSGIPythonPath``; instead you should use the ``python-path`` option to
|
|||||||
WSGIProcessGroup example.com
|
WSGIProcessGroup example.com
|
||||||
|
|
||||||
If you want to serve your project in a subdirectory
|
If you want to serve your project in a subdirectory
|
||||||
(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias``
|
(``https://example.com/mysite`` in this example), you can add
|
||||||
to the configuration above:
|
``WSGIScriptAlias`` to the configuration above:
|
||||||
|
|
||||||
.. code-block:: apache
|
.. code-block:: apache
|
||||||
|
|
||||||
|
@ -4,8 +4,8 @@ How to manage error reporting
|
|||||||
|
|
||||||
When you're running a public site you should always turn off the
|
When you're running a public site you should always turn off the
|
||||||
:setting:`DEBUG` setting. That will make your server run much faster, and will
|
:setting:`DEBUG` setting. That will make your server run much faster, and will
|
||||||
also prevent malicious users from seeing details of your application that can be
|
also prevent malicious users from seeing details of your application that can
|
||||||
revealed by the error pages.
|
be revealed by the error pages.
|
||||||
|
|
||||||
However, running with :setting:`DEBUG` set to ``False`` means you'll never see
|
However, running with :setting:`DEBUG` set to ``False`` means you'll never see
|
||||||
errors generated by your site -- everyone will instead see your public error
|
errors generated by your site -- everyone will instead see your public error
|
||||||
@ -87,11 +87,11 @@ regular expression objects. For example::
|
|||||||
re.compile(r"^/phpmyadmin/"),
|
re.compile(r"^/phpmyadmin/"),
|
||||||
]
|
]
|
||||||
|
|
||||||
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
|
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not*
|
||||||
reported. Neither will any URL starting with ``/phpmyadmin/``.
|
be reported. Neither will any URL starting with ``/phpmyadmin/``.
|
||||||
|
|
||||||
The following example shows how to exclude some conventional URLs that browsers and
|
The following example shows how to exclude some conventional URLs that browsers
|
||||||
crawlers often request::
|
and crawlers often request::
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@ -220,7 +220,8 @@ filtered out of error reports in a production environment (that is, where
|
|||||||
disclosed.
|
disclosed.
|
||||||
|
|
||||||
To systematically hide all POST parameters of a request in error reports,
|
To systematically hide all POST parameters of a request in error reports,
|
||||||
do not provide any argument to the ``sensitive_post_parameters`` decorator::
|
do not provide any argument to the ``sensitive_post_parameters``
|
||||||
|
decorator::
|
||||||
|
|
||||||
@sensitive_post_parameters()
|
@sensitive_post_parameters()
|
||||||
def my_view(request): ...
|
def my_view(request): ...
|
||||||
@ -379,5 +380,5 @@ within any given view by setting the ``HttpRequest``’s
|
|||||||
|
|
||||||
You can also set up custom error reporting by writing a custom piece of
|
You can also set up custom error reporting by writing a custom piece of
|
||||||
:ref:`exception middleware <exception-middleware>`. If you do write custom
|
:ref:`exception middleware <exception-middleware>`. If you do write custom
|
||||||
error handling, it's a good idea to emulate Django's built-in error handling
|
error handling, it's a good idea to emulate Django's built-in error
|
||||||
and only report/log errors if :setting:`DEBUG` is ``False``.
|
handling and only report/log errors if :setting:`DEBUG` is ``False``.
|
||||||
|
@ -26,8 +26,8 @@ however, this data isn't loaded automatically, except if you use
|
|||||||
A fixture is a collection of data that Django knows how to import into a
|
A fixture is a collection of data that Django knows how to import into a
|
||||||
database. The most straightforward way of creating a fixture if you've already
|
database. The most straightforward way of creating a fixture if you've already
|
||||||
got some data is to use the :djadmin:`manage.py dumpdata <dumpdata>` command.
|
got some data is to use the :djadmin:`manage.py dumpdata <dumpdata>` command.
|
||||||
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML
|
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or
|
||||||
(with PyYAML_ installed) documents. The :doc:`serialization documentation
|
YAML (with PyYAML_ installed) documents. The :doc:`serialization documentation
|
||||||
</topics/serialization>` has more details about each of these supported
|
</topics/serialization>` has more details about each of these supported
|
||||||
:ref:`serialization formats <serialization-formats>`.
|
:ref:`serialization formats <serialization-formats>`.
|
||||||
|
|
||||||
|
@ -44,8 +44,8 @@ Save this as a file by using standard Unix output redirection:
|
|||||||
|
|
||||||
$ python manage.py inspectdb > models.py
|
$ python manage.py inspectdb > models.py
|
||||||
|
|
||||||
This feature is meant as a shortcut, not as definitive model generation. See the
|
This feature is meant as a shortcut, not as definitive model generation. See
|
||||||
:djadmin:`documentation of inspectdb <inspectdb>` for more information.
|
the :djadmin:`documentation of inspectdb <inspectdb>` for more information.
|
||||||
|
|
||||||
Once you've cleaned up your models, name the file ``models.py`` and put it in
|
Once you've cleaned up your models, name the file ``models.py`` and put it in
|
||||||
the Python package that holds your app. Then add the app to your
|
the Python package that holds your app. Then add the app to your
|
||||||
|
@ -3,8 +3,8 @@ How to create CSV output
|
|||||||
========================
|
========================
|
||||||
|
|
||||||
This document explains how to output CSV (Comma Separated Values) dynamically
|
This document explains how to output CSV (Comma Separated Values) dynamically
|
||||||
using Django views. To do this, you can either use the Python CSV library or the
|
using Django views. To do this, you can either use the Python CSV library or
|
||||||
Django template system.
|
the Django template system.
|
||||||
|
|
||||||
Using the Python CSV library
|
Using the Python CSV library
|
||||||
============================
|
============================
|
||||||
@ -101,9 +101,10 @@ the assembly and transmission of a large CSV file::
|
|||||||
Using the template system
|
Using the template system
|
||||||
=========================
|
=========================
|
||||||
|
|
||||||
Alternatively, you can use the :doc:`Django template system </topics/templates>`
|
Alternatively, you can use the :doc:`Django template system
|
||||||
to generate CSV. This is lower-level than using the convenient Python :mod:`csv`
|
</topics/templates>` to generate CSV. This is lower-level than using the
|
||||||
module, but the solution is presented here for completeness.
|
convenient Python :mod:`csv` module, but the solution is presented here for
|
||||||
|
completeness.
|
||||||
|
|
||||||
The idea here is to pass a list of items to your template, and have the
|
The idea here is to pass a list of items to your template, and have the
|
||||||
template output the commas in a :ttag:`for` loop.
|
template output the commas in a :ttag:`for` loop.
|
||||||
|
@ -87,8 +87,8 @@ mention:
|
|||||||
browsers will handle the PDF using whatever program/plugin they've been
|
browsers will handle the PDF using whatever program/plugin they've been
|
||||||
configured to use for PDFs.
|
configured to use for PDFs.
|
||||||
|
|
||||||
* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers
|
* You can provide an arbitrary ``filename`` parameter. It'll be used by
|
||||||
in the "Save as..." dialog.
|
browsers in the "Save as..." dialog.
|
||||||
|
|
||||||
* You can hook into the ReportLab API: The same buffer passed as the first
|
* You can hook into the ReportLab API: The same buffer passed as the first
|
||||||
argument to ``canvas.Canvas`` can be fed to the
|
argument to ``canvas.Canvas`` can be fed to the
|
||||||
@ -112,8 +112,8 @@ Other formats
|
|||||||
Notice that there isn't a lot in these examples that's PDF-specific -- just the
|
Notice that there isn't a lot in these examples that's PDF-specific -- just the
|
||||||
bits using ``reportlab``. You can use a similar technique to generate any
|
bits using ``reportlab``. You can use a similar technique to generate any
|
||||||
arbitrary format that you can find a Python library for. Also see
|
arbitrary format that you can find a Python library for. Also see
|
||||||
:doc:`/howto/outputting-csv` for another example and some techniques you can use
|
:doc:`/howto/outputting-csv` for another example and some techniques you can
|
||||||
when generated text-based formats.
|
use when generated text-based formats.
|
||||||
|
|
||||||
.. seealso::
|
.. seealso::
|
||||||
|
|
||||||
|
@ -63,7 +63,8 @@ in the ``templates`` directory, and add the template files to that folder:
|
|||||||
|
|
||||||
The template loader first looks for templates in the ``DIRS`` directory. When
|
The template loader first looks for templates in the ``DIRS`` directory. When
|
||||||
the views in the ``blog`` app ask for the ``blog/post.html`` and
|
the views in the ``blog`` app ask for the ``blog/post.html`` and
|
||||||
``blog/list.html`` templates, the loader will return the files you just created.
|
``blog/list.html`` templates, the loader will return the files you just
|
||||||
|
created.
|
||||||
|
|
||||||
Overriding from an app's template directory
|
Overriding from an app's template directory
|
||||||
===========================================
|
===========================================
|
||||||
|
@ -155,10 +155,10 @@ file-serving functionality: It doesn't know about the finders feature of the
|
|||||||
collected under :setting:`STATIC_ROOT`.
|
collected under :setting:`STATIC_ROOT`.
|
||||||
|
|
||||||
Because of this, ``staticfiles`` ships its own
|
Because of this, ``staticfiles`` ships its own
|
||||||
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass
|
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a
|
||||||
of the built-in one that has the ability to transparently serve all the assets
|
subclass of the built-in one that has the ability to transparently serve all
|
||||||
during execution of these tests in a way very similar to what we get at
|
the assets during execution of these tests in a way very similar to what we get
|
||||||
development time with ``DEBUG = True``, i.e. without having to collect them
|
at development time with ``DEBUG = True``, i.e. without having to collect them
|
||||||
using :djadmin:`collectstatic` first.
|
using :djadmin:`collectstatic` first.
|
||||||
|
|
||||||
Deployment
|
Deployment
|
||||||
|
@ -91,7 +91,8 @@ Once you're ready, it is time to :doc:`install the new Django version
|
|||||||
is a major upgrade, you might want to set up a new environment with all the
|
is a major upgrade, you might want to set up a new environment with all the
|
||||||
dependencies first.
|
dependencies first.
|
||||||
|
|
||||||
If you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` flag:
|
If you installed Django with pip_, you can use the ``--upgrade`` or ``-U``
|
||||||
|
flag:
|
||||||
|
|
||||||
.. console::
|
.. console::
|
||||||
|
|
||||||
@ -127,6 +128,6 @@ If you are using caching provided by Django, you should consider clearing your
|
|||||||
cache after upgrading. Otherwise you may run into problems, for example, if you
|
cache after upgrading. Otherwise you may run into problems, for example, if you
|
||||||
are caching pickled objects as these objects are not guaranteed to be
|
are caching pickled objects as these objects are not guaranteed to be
|
||||||
pickle-compatible across Django versions. A past instance of incompatibility
|
pickle-compatible across Django versions. A past instance of incompatibility
|
||||||
was caching pickled :class:`~django.http.HttpResponse` objects, either
|
was caching pickled :class:`~django.http.HttpResponse` objects, either directly
|
||||||
directly or indirectly via the :func:`~django.views.decorators.cache.cache_page`
|
or indirectly via the :func:`~django.views.decorators.cache.cache_page`
|
||||||
decorator.
|
decorator.
|
||||||
|
@ -173,7 +173,8 @@ the respective field according to your needs.
|
|||||||
migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
|
migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
|
||||||
]
|
]
|
||||||
|
|
||||||
* Now you can apply the migrations as usual with the :djadmin:`migrate` command.
|
* Now you can apply the migrations as usual with the :djadmin:`migrate`
|
||||||
|
command.
|
||||||
|
|
||||||
Note there is a race condition if you allow objects to be created while this
|
Note there is a race condition if you allow objects to be created while this
|
||||||
migration is running. Objects created after the ``AddField`` and before
|
migration is running. Objects created after the ``AddField`` and before
|
||||||
@ -277,12 +278,13 @@ Migrating data between third-party apps
|
|||||||
You can use a data migration to move data from one third-party application to
|
You can use a data migration to move data from one third-party application to
|
||||||
another.
|
another.
|
||||||
|
|
||||||
If you plan to remove the old app later, you'll need to set the ``dependencies``
|
If you plan to remove the old app later, you'll need to set the
|
||||||
property based on whether or not the old app is installed. Otherwise, you'll
|
``dependencies`` property based on whether or not the old app is installed.
|
||||||
have missing dependencies once you uninstall the old app. Similarly, you'll
|
Otherwise, you'll have missing dependencies once you uninstall the old app.
|
||||||
need to catch :exc:`LookupError` in the ``apps.get_model()`` call that
|
Similarly, you'll need to catch :exc:`LookupError` in the ``apps.get_model()``
|
||||||
retrieves models from the old app. This approach allows you to deploy your
|
call that retrieves models from the old app. This approach allows you to deploy
|
||||||
project anywhere without first installing and then uninstalling the old app.
|
your project anywhere without first installing and then uninstalling the old
|
||||||
|
app.
|
||||||
|
|
||||||
Here's a sample migration:
|
Here's a sample migration:
|
||||||
|
|
||||||
|
@ -4,7 +4,8 @@ Committing code
|
|||||||
|
|
||||||
This section is addressed to the mergers and to anyone interested in knowing
|
This section is addressed to the mergers and to anyone interested in knowing
|
||||||
how code gets committed into Django. If you're a community member who wants to
|
how code gets committed into Django. If you're a community member who wants to
|
||||||
contribute code to Django, look at :doc:`writing-code/working-with-git` instead.
|
contribute code to Django, look at :doc:`writing-code/working-with-git`
|
||||||
|
instead.
|
||||||
|
|
||||||
.. _handling-pull-requests:
|
.. _handling-pull-requests:
|
||||||
|
|
||||||
|
@ -438,10 +438,10 @@ Next, we mark the current point in history as being "bad" since the test fails:
|
|||||||
|
|
||||||
Now, we need to find a point in git history before the regression was
|
Now, we need to find a point in git history before the regression was
|
||||||
introduced (i.e. a point where the test passes). Use something like
|
introduced (i.e. a point where the test passes). Use something like
|
||||||
``git checkout HEAD~100`` to check out an earlier revision (100 commits earlier,
|
``git checkout HEAD~100`` to check out an earlier revision (100 commits
|
||||||
in this case). Check if the test fails. If so, mark that point as "bad"
|
earlier, in this case). Check if the test fails. If so, mark that point as
|
||||||
(``git bisect bad``), then check out an earlier revision and recheck. Once you
|
"bad" (``git bisect bad``), then check out an earlier revision and recheck.
|
||||||
find a revision where your test passes, mark it as "good":
|
Once you find a revision where your test passes, mark it as "good":
|
||||||
|
|
||||||
.. code-block:: shell
|
.. code-block:: shell
|
||||||
|
|
||||||
|
@ -96,13 +96,12 @@ Python style
|
|||||||
|
|
||||||
* In docstrings, follow the style of existing docstrings and :pep:`257`.
|
* In docstrings, follow the style of existing docstrings and :pep:`257`.
|
||||||
|
|
||||||
* In tests, use
|
* In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and
|
||||||
:meth:`~django.test.SimpleTestCase.assertRaisesMessage` and
|
:meth:`~django.test.SimpleTestCase.assertWarnsMessage` instead of
|
||||||
:meth:`~django.test.SimpleTestCase.assertWarnsMessage`
|
:meth:`~unittest.TestCase.assertRaises` and
|
||||||
instead of :meth:`~unittest.TestCase.assertRaises` and
|
:meth:`~unittest.TestCase.assertWarns` so you can check the exception or
|
||||||
:meth:`~unittest.TestCase.assertWarns` so you can check the
|
warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` and
|
||||||
exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex`
|
:meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular
|
||||||
and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular
|
|
||||||
expression matching.
|
expression matching.
|
||||||
|
|
||||||
Use :meth:`assertIs(…, True/False)<unittest.TestCase.assertIs>` for testing
|
Use :meth:`assertIs(…, True/False)<unittest.TestCase.assertIs>` for testing
|
||||||
@ -149,9 +148,10 @@ Imports
|
|||||||
|
|
||||||
* Put imports in these groups: future, standard library, third-party libraries,
|
* Put imports in these groups: future, standard library, third-party libraries,
|
||||||
other Django components, local Django component, try/excepts. Sort lines in
|
other Django components, local Django component, try/excepts. Sort lines in
|
||||||
each group alphabetically by the full module name. Place all ``import module``
|
each group alphabetically by the full module name. Place all
|
||||||
statements before ``from module import objects`` in each section. Use absolute
|
``import module`` statements before ``from module import objects`` in each
|
||||||
imports for other Django components and relative imports for local components.
|
section. Use absolute imports for other Django components and relative
|
||||||
|
imports for local components.
|
||||||
|
|
||||||
* On each line, alphabetize the items with the upper case items grouped before
|
* On each line, alphabetize the items with the upper case items grouped before
|
||||||
the lowercase items.
|
the lowercase items.
|
||||||
|
@ -17,8 +17,8 @@ Code style
|
|||||||
for indentation, but there are some exceptions.
|
for indentation, but there are some exceptions.
|
||||||
|
|
||||||
* When naming variables, use ``camelCase`` instead of ``underscore_case``.
|
* When naming variables, use ``camelCase`` instead of ``underscore_case``.
|
||||||
Different JavaScript files sometimes use a different code style. Please try to
|
Different JavaScript files sometimes use a different code style. Please try
|
||||||
conform to the code style of each file.
|
to conform to the code style of each file.
|
||||||
|
|
||||||
* Use the `ESLint`_ code linter to check your code for bugs and style errors.
|
* Use the `ESLint`_ code linter to check your code for bugs and style errors.
|
||||||
ESLint will be run when you run the JavaScript tests. We also recommended
|
ESLint will be run when you run the JavaScript tests. We also recommended
|
||||||
@ -89,8 +89,8 @@ The JavaScript tests may be run from a web browser or from the command line.
|
|||||||
Testing from a web browser
|
Testing from a web browser
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
To run the tests from a web browser, open up :source:`js_tests/tests.html` in your
|
To run the tests from a web browser, open up :source:`js_tests/tests.html` in
|
||||||
browser.
|
your browser.
|
||||||
|
|
||||||
To measure code coverage when running the tests, you need to view that file
|
To measure code coverage when running the tests, you need to view that file
|
||||||
over HTTP. To view code coverage:
|
over HTTP. To view code coverage:
|
||||||
|
@ -204,9 +204,12 @@ whether to accept it.
|
|||||||
|
|
||||||
Some examples of DEPs that have been approved and fully implemented:
|
Some examples of DEPs that have been approved and fully implemented:
|
||||||
|
|
||||||
* `DEP 181: ORM Expressions <https://github.com/django/deps/blob/main/final/0181-orm-expressions.rst>`_
|
* `DEP 181: ORM Expressions
|
||||||
* `DEP 182: Multiple Template Engines <https://github.com/django/deps/blob/main/final/0182-multiple-template-engines.rst>`_
|
<https://github.com/django/deps/blob/main/final/0181-orm-expressions.rst>`_
|
||||||
* `DEP 201: Simplified routing syntax <https://github.com/django/deps/blob/main/final/0201-simplified-routing-syntax.rst>`_
|
* `DEP 182: Multiple Template Engines
|
||||||
|
<https://github.com/django/deps/blob/main/final/0182-multiple-template-engines.rst>`_
|
||||||
|
* `DEP 201: Simplified routing syntax
|
||||||
|
<https://github.com/django/deps/blob/main/final/0201-simplified-routing-syntax.rst>`_
|
||||||
|
|
||||||
.. _Django Forum: https://forum.djangoproject.com/
|
.. _Django Forum: https://forum.djangoproject.com/
|
||||||
.. _Django Enhancement Proposals: https://github.com/django/deps
|
.. _Django Enhancement Proposals: https://github.com/django/deps
|
||||||
@ -226,19 +229,19 @@ There are a couple of reasons that code in Django might be deprecated:
|
|||||||
no longer needs to support the older version of Python that doesn't include
|
no longer needs to support the older version of Python that doesn't include
|
||||||
the library, the library will be deprecated in Django.
|
the library, the library will be deprecated in Django.
|
||||||
|
|
||||||
As the :ref:`deprecation policy<internal-release-deprecation-policy>` describes,
|
As the :ref:`deprecation policy<internal-release-deprecation-policy>`
|
||||||
the first release of Django that deprecates a feature (``A.B``) should raise a
|
describes, the first release of Django that deprecates a feature (``A.B``)
|
||||||
``RemovedInDjangoXXWarning`` (where XX is the Django version where the feature
|
should raise a ``RemovedInDjangoXXWarning`` (where XX is the Django version
|
||||||
will be removed) when the deprecated feature is invoked. Assuming we have good
|
where the feature will be removed) when the deprecated feature is invoked.
|
||||||
test coverage, these warnings are converted to errors when :ref:`running the
|
Assuming we have good test coverage, these warnings are converted to errors
|
||||||
test suite <running-unit-tests>` with warnings enabled:
|
when :ref:`running the test suite <running-unit-tests>` with warnings enabled:
|
||||||
``python -Wa runtests.py``. Thus, when adding a ``RemovedInDjangoXXWarning``
|
``python -Wa runtests.py``. Thus, when adding a ``RemovedInDjangoXXWarning``
|
||||||
you need to eliminate or silence any warnings generated when running the tests.
|
you need to eliminate or silence any warnings generated when running the tests.
|
||||||
|
|
||||||
The first step is to remove any use of the deprecated behavior by Django itself.
|
The first step is to remove any use of the deprecated behavior by Django
|
||||||
Next you can silence warnings in tests that actually test the deprecated
|
itself. Next you can silence warnings in tests that actually test the
|
||||||
behavior by using the ``ignore_warnings`` decorator, either at the test or class
|
deprecated behavior by using the ``ignore_warnings`` decorator, either at the
|
||||||
level:
|
test or class level:
|
||||||
|
|
||||||
#) In a particular test::
|
#) In a particular test::
|
||||||
|
|
||||||
@ -305,8 +308,9 @@ Finally, there are a couple of updates to Django's documentation to make:
|
|||||||
applicable, to the current release notes (``docs/releases/A.B.txt``) under
|
applicable, to the current release notes (``docs/releases/A.B.txt``) under
|
||||||
the "Features deprecated in A.B" heading.
|
the "Features deprecated in A.B" heading.
|
||||||
|
|
||||||
#) Add an entry in the deprecation timeline (``docs/internals/deprecation.txt``)
|
#) Add an entry in the deprecation timeline
|
||||||
under the appropriate version describing what code will be removed.
|
(``docs/internals/deprecation.txt``) under the appropriate version
|
||||||
|
describing what code will be removed.
|
||||||
|
|
||||||
Once you have completed these steps, you are finished with the deprecation.
|
Once you have completed these steps, you are finished with the deprecation.
|
||||||
In each :term:`feature release <Feature release>`, all
|
In each :term:`feature release <Feature release>`, all
|
||||||
@ -402,10 +406,10 @@ Bugs
|
|||||||
|
|
||||||
* Is there a proper regression test (the test should fail before the fix
|
* Is there a proper regression test (the test should fail before the fix
|
||||||
is applied)?
|
is applied)?
|
||||||
* If it's a bug that :ref:`qualifies for a backport <supported-versions-policy>`
|
* If it's a bug that :ref:`qualifies for a backport
|
||||||
to the stable version of Django, is there a release note in
|
<supported-versions-policy>` to the stable version of Django, is there a
|
||||||
``docs/releases/A.B.C.txt``? Bug fixes that will be applied only to the main
|
release note in ``docs/releases/A.B.C.txt``? Bug fixes that will be applied
|
||||||
branch don't need a release note.
|
only to the main branch don't need a release note.
|
||||||
|
|
||||||
New Features
|
New Features
|
||||||
------------
|
------------
|
||||||
|
@ -398,9 +398,9 @@ and also excludes several directories not relevant to the results
|
|||||||
Contrib apps
|
Contrib apps
|
||||||
============
|
============
|
||||||
|
|
||||||
Tests for contrib apps can be found in the :source:`tests/` directory, typically
|
Tests for contrib apps can be found in the :source:`tests/` directory,
|
||||||
under ``<app_name>_tests``. For example, tests for ``contrib.auth`` are located
|
typically under ``<app_name>_tests``. For example, tests for ``contrib.auth``
|
||||||
in :source:`tests/auth_tests`.
|
are located in :source:`tests/auth_tests`.
|
||||||
|
|
||||||
.. _troubleshooting-unit-tests:
|
.. _troubleshooting-unit-tests:
|
||||||
|
|
||||||
|
@ -205,8 +205,8 @@ All Python code blocks should be formatted using the :pypi:`blacken-docs`
|
|||||||
auto-formatter. This is automatically run by the :ref:`pre-commit hook
|
auto-formatter. This is automatically run by the :ref:`pre-commit hook
|
||||||
<coding-style-pre-commit>` if configured.
|
<coding-style-pre-commit>` if configured.
|
||||||
|
|
||||||
The check can also be run manually: provided that ``blacken-docs`` is installed,
|
The check can also be run manually: provided that ``blacken-docs`` is
|
||||||
run the following command from the ``docs`` directory:
|
installed, run the following command from the ``docs`` directory:
|
||||||
|
|
||||||
.. console::
|
.. console::
|
||||||
|
|
||||||
@ -245,8 +245,8 @@ Entries that have a status of "broken" need to be fixed. Those that have a
|
|||||||
status of "redirected" may need to be updated to point to the canonical
|
status of "redirected" may need to be updated to point to the canonical
|
||||||
location, e.g. the scheme has changed ``http://`` → ``https://``. In certain
|
location, e.g. the scheme has changed ``http://`` → ``https://``. In certain
|
||||||
cases, we do not want to update a "redirected" link, e.g. a rewrite to always
|
cases, we do not want to update a "redirected" link, e.g. a rewrite to always
|
||||||
point to the latest or stable version of the documentation, e.g. ``/en/stable/`` →
|
point to the latest or stable version of the documentation, e.g.
|
||||||
``/en/3.2/``.
|
``/en/stable/`` → ``/en/3.2/``.
|
||||||
|
|
||||||
Writing style
|
Writing style
|
||||||
=============
|
=============
|
||||||
@ -523,12 +523,12 @@ General improvements or other changes to the APIs that should be emphasized
|
|||||||
should use the "``.. versionchanged:: X.Y``" directive (with the same format
|
should use the "``.. versionchanged:: X.Y``" directive (with the same format
|
||||||
as the ``versionadded`` mentioned above.
|
as the ``versionadded`` mentioned above.
|
||||||
|
|
||||||
These ``versionadded`` and ``versionchanged`` blocks should be "self-contained."
|
These ``versionadded`` and ``versionchanged`` blocks should be
|
||||||
In other words, since we only keep these annotations around for two releases,
|
"self-contained." In other words, since we only keep these annotations around
|
||||||
it's nice to be able to remove the annotation and its contents without having
|
for two releases, it's nice to be able to remove the annotation and its
|
||||||
to reflow, reindent, or edit the surrounding text. For example, instead of
|
contents without having to reflow, reindent, or edit the surrounding text. For
|
||||||
putting the entire description of a new or changed feature in a block, do
|
example, instead of putting the entire description of a new or changed feature
|
||||||
something like this:
|
in a block, do something like this:
|
||||||
|
|
||||||
.. code-block:: rst
|
.. code-block:: rst
|
||||||
|
|
||||||
@ -659,12 +659,12 @@ you'd like to help translate the documentation into another language.
|
|||||||
``django-admin`` man page
|
``django-admin`` man page
|
||||||
=========================
|
=========================
|
||||||
|
|
||||||
Sphinx can generate a manual page for the
|
Sphinx can generate a manual page for the :doc:`django-admin
|
||||||
:doc:`django-admin </ref/django-admin>` command. This is configured in
|
</ref/django-admin>` command. This is configured in ``docs/conf.py``. Unlike
|
||||||
``docs/conf.py``. Unlike other documentation output, this man page should be
|
other documentation output, this man page should be included in the Django
|
||||||
included in the Django repository and the releases as
|
repository and the releases as ``docs/man/django-admin.1``. There isn't a need
|
||||||
``docs/man/django-admin.1``. There isn't a need to update this file when
|
to update this file when updating the documentation, as it's updated once as
|
||||||
updating the documentation, as it's updated once as part of the release process.
|
part of the release process.
|
||||||
|
|
||||||
To generate an updated version of the man page, in the ``docs`` directory, run:
|
To generate an updated version of the man page, in the ``docs`` directory, run:
|
||||||
|
|
||||||
|
@ -748,8 +748,8 @@ details on these changes.
|
|||||||
(replaced by :py:mod:`argparse`).
|
(replaced by :py:mod:`argparse`).
|
||||||
|
|
||||||
* The class ``django.core.management.NoArgsCommand`` will be removed. Use
|
* The class ``django.core.management.NoArgsCommand`` will be removed. Use
|
||||||
:class:`~django.core.management.BaseCommand` instead, which takes no arguments
|
:class:`~django.core.management.BaseCommand` instead, which takes no
|
||||||
by default.
|
arguments by default.
|
||||||
|
|
||||||
* ``django.core.context_processors`` module will be removed.
|
* ``django.core.context_processors`` module will be removed.
|
||||||
|
|
||||||
@ -779,7 +779,8 @@ details on these changes.
|
|||||||
* ``get_all_related_many_to_many_objects()``
|
* ``get_all_related_many_to_many_objects()``
|
||||||
* ``get_all_related_m2m_objects_with_model()``
|
* ``get_all_related_m2m_objects_with_model()``
|
||||||
|
|
||||||
* The ``error_message`` argument of ``django.forms.RegexField`` will be removed.
|
* The ``error_message`` argument of ``django.forms.RegexField`` will be
|
||||||
|
removed.
|
||||||
|
|
||||||
* The ``unordered_list`` filter will no longer support old style lists.
|
* The ``unordered_list`` filter will no longer support old style lists.
|
||||||
|
|
||||||
@ -805,7 +806,8 @@ details on these changes.
|
|||||||
``django.contrib.admin.helpers.InlineAdminForm`` will be removed.
|
``django.contrib.admin.helpers.InlineAdminForm`` will be removed.
|
||||||
|
|
||||||
* The backwards compatibility shim to allow ``FormMixin.get_form()`` to be
|
* The backwards compatibility shim to allow ``FormMixin.get_form()`` to be
|
||||||
defined with no default value for its ``form_class`` argument will be removed.
|
defined with no default value for its ``form_class`` argument will be
|
||||||
|
removed.
|
||||||
|
|
||||||
* The following settings will be removed:
|
* The following settings will be removed:
|
||||||
|
|
||||||
@ -872,14 +874,14 @@ details on these changes.
|
|||||||
* Support for the legacy ``%(<foo>)s`` syntax in ``ModelFormMixin.success_url``
|
* Support for the legacy ``%(<foo>)s`` syntax in ``ModelFormMixin.success_url``
|
||||||
will be removed.
|
will be removed.
|
||||||
|
|
||||||
* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``, ``extent3d()``,
|
* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``,
|
||||||
``make_line()``, and ``unionagg()`` will be removed.
|
``extent3d()``, ``make_line()``, and ``unionagg()`` will be removed.
|
||||||
|
|
||||||
* Ability to specify ``ContentType.name`` when creating a content type instance
|
* Ability to specify ``ContentType.name`` when creating a content type instance
|
||||||
will be removed.
|
will be removed.
|
||||||
|
|
||||||
* Support for the old signature of ``allow_migrate`` will be removed. It changed
|
* Support for the old signature of ``allow_migrate`` will be removed. It
|
||||||
from ``allow_migrate(self, db, model)`` to
|
changed from ``allow_migrate(self, db, model)`` to
|
||||||
``allow_migrate(self, db, app_label, model_name=None, **hints)``.
|
``allow_migrate(self, db, app_label, model_name=None, **hints)``.
|
||||||
|
|
||||||
* Support for the syntax of ``{% cycle %}`` that uses comma-separated arguments
|
* Support for the syntax of ``{% cycle %}`` that uses comma-separated arguments
|
||||||
@ -1002,8 +1004,8 @@ details on these changes.
|
|||||||
* ``django.utils.module_loading.import_by_path`` will be removed in favor of
|
* ``django.utils.module_loading.import_by_path`` will be removed in favor of
|
||||||
``django.utils.module_loading.import_string``.
|
``django.utils.module_loading.import_string``.
|
||||||
|
|
||||||
* ``ssi`` and ``url`` template tags will be removed from the ``future`` template
|
* ``ssi`` and ``url`` template tags will be removed from the ``future``
|
||||||
tag library (used during the 1.3/1.4 deprecation period).
|
template tag library (used during the 1.3/1.4 deprecation period).
|
||||||
|
|
||||||
* ``django.utils.text.javascript_quote`` will be removed.
|
* ``django.utils.text.javascript_quote`` will be removed.
|
||||||
|
|
||||||
@ -1013,9 +1015,9 @@ details on these changes.
|
|||||||
* The ``cache_choices`` option to :class:`~django.forms.ModelChoiceField` and
|
* The ``cache_choices`` option to :class:`~django.forms.ModelChoiceField` and
|
||||||
:class:`~django.forms.ModelMultipleChoiceField` will be removed.
|
:class:`~django.forms.ModelMultipleChoiceField` will be removed.
|
||||||
|
|
||||||
* The default value of the
|
* The default value of the :attr:`RedirectView.permanent
|
||||||
:attr:`RedirectView.permanent <django.views.generic.base.RedirectView.permanent>`
|
<django.views.generic.base.RedirectView.permanent>` attribute will change
|
||||||
attribute will change from ``True`` to ``False``.
|
from ``True`` to ``False``.
|
||||||
|
|
||||||
* ``django.contrib.sitemaps.FlatPageSitemap`` will be removed in favor of
|
* ``django.contrib.sitemaps.FlatPageSitemap`` will be removed in favor of
|
||||||
``django.contrib.flatpages.sitemaps.FlatPageSitemap``.
|
``django.contrib.flatpages.sitemaps.FlatPageSitemap``.
|
||||||
@ -1098,8 +1100,8 @@ details on these changes.
|
|||||||
* The ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting will be removed.
|
* The ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting will be removed.
|
||||||
|
|
||||||
* Usage of the hardcoded *Hold down "Control", or "Command" on a Mac, to select
|
* Usage of the hardcoded *Hold down "Control", or "Command" on a Mac, to select
|
||||||
more than one.* string to override or append to user-provided ``help_text`` in
|
more than one.* string to override or append to user-provided ``help_text``
|
||||||
forms for ManyToMany model fields will not be performed by Django anymore
|
in forms for ManyToMany model fields will not be performed by Django anymore
|
||||||
either at the model or forms layer.
|
either at the model or forms layer.
|
||||||
|
|
||||||
* The ``Model._meta.get_(add|change|delete)_permission`` methods will
|
* The ``Model._meta.get_(add|change|delete)_permission`` methods will
|
||||||
@ -1112,8 +1114,9 @@ details on these changes.
|
|||||||
(``django.contrib.gis.sitemaps.views.index`` and
|
(``django.contrib.gis.sitemaps.views.index`` and
|
||||||
``django.contrib.gis.sitemaps.views.sitemap``).
|
``django.contrib.gis.sitemaps.views.sitemap``).
|
||||||
|
|
||||||
* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter and
|
* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter
|
||||||
``django.utils.html.clean_html`` will be removed following an accelerated deprecation.
|
and ``django.utils.html.clean_html`` will be removed following an accelerated
|
||||||
|
deprecation.
|
||||||
|
|
||||||
.. _deprecation-removed-in-1.7:
|
.. _deprecation-removed-in-1.7:
|
||||||
|
|
||||||
@ -1251,8 +1254,8 @@ details on these changes.
|
|||||||
* Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of
|
* Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of
|
||||||
template filter functions will no longer be supported.
|
template filter functions will no longer be supported.
|
||||||
|
|
||||||
* The attribute ``HttpRequest.raw_post_data`` was renamed to ``HttpRequest.body``
|
* The attribute ``HttpRequest.raw_post_data`` was renamed to
|
||||||
in 1.4. The backward compatibility will be removed --
|
``HttpRequest.body`` in 1.4. The backward compatibility will be removed --
|
||||||
``HttpRequest.raw_post_data`` will no longer work.
|
``HttpRequest.raw_post_data`` will no longer work.
|
||||||
|
|
||||||
* The value for the ``post_url_continue`` parameter in
|
* The value for the ``post_url_continue`` parameter in
|
||||||
@ -1337,10 +1340,10 @@ details on these changes.
|
|||||||
performance issues and will follow a slightly accelerated deprecation
|
performance issues and will follow a slightly accelerated deprecation
|
||||||
timeframe.
|
timeframe.
|
||||||
|
|
||||||
* Translations located under the so-called *project path* will be ignored during
|
* Translations located under the so-called *project path* will be ignored
|
||||||
the translation building process performed at runtime. The
|
during the translation building process performed at runtime. The
|
||||||
:setting:`LOCALE_PATHS` setting can be used for the same task by including the
|
:setting:`LOCALE_PATHS` setting can be used for the same task by including
|
||||||
filesystem path to a ``locale`` directory containing non-app-specific
|
the filesystem path to a ``locale`` directory containing non-app-specific
|
||||||
translations in its value.
|
translations in its value.
|
||||||
|
|
||||||
* The Markup contrib app will no longer support versions of Python-Markdown
|
* The Markup contrib app will no longer support versions of Python-Markdown
|
||||||
|
@ -115,11 +115,11 @@ updates.
|
|||||||
committed until the final release happened.
|
committed until the final release happened.
|
||||||
|
|
||||||
For example, shortly after the release of Django 1.3 the branch
|
For example, shortly after the release of Django 1.3 the branch
|
||||||
``stable/1.3.x`` was created. Official support for that release has expired,
|
``stable/1.3.x`` was created. Official support for that release has
|
||||||
and so it no longer receives direct maintenance from the Django project.
|
expired, and so it no longer receives direct maintenance from the Django
|
||||||
However, that and all other similarly named branches continue to exist, and
|
project. However, that and all other similarly named branches continue to
|
||||||
interested community members have occasionally used them to provide
|
exist, and interested community members have occasionally used them to
|
||||||
unofficial support for old Django releases.
|
provide unofficial support for old Django releases.
|
||||||
|
|
||||||
Tags
|
Tags
|
||||||
====
|
====
|
||||||
|
@ -471,7 +471,8 @@ Building the artifacts
|
|||||||
|
|
||||||
.. admonition:: Optionally use helper scripts
|
.. admonition:: Optionally use helper scripts
|
||||||
|
|
||||||
You can streamline some of the steps below using helper scripts from the Wiki:
|
You can streamline some of the steps below using helper scripts from the
|
||||||
|
Wiki:
|
||||||
|
|
||||||
* `Release script
|
* `Release script
|
||||||
<https://code.djangoproject.com/wiki/ReleaseScript>`_
|
<https://code.djangoproject.com/wiki/ReleaseScript>`_
|
||||||
|
@ -72,9 +72,9 @@ to make the role of Merger sustainable.
|
|||||||
|
|
||||||
The following restrictions apply to the role of Merger:
|
The following restrictions apply to the role of Merger:
|
||||||
|
|
||||||
- A person must not simultaneously serve as a member of the steering council. If
|
- A person must not simultaneously serve as a member of the steering council.
|
||||||
a Merger is elected to the steering council, they shall cease to be a Merger
|
If a Merger is elected to the steering council, they shall cease to be a
|
||||||
immediately upon taking up membership in the steering council.
|
Merger immediately upon taking up membership in the steering council.
|
||||||
- A person may serve in the roles of Releaser and Merger simultaneously.
|
- A person may serve in the roles of Releaser and Merger simultaneously.
|
||||||
|
|
||||||
The selection process, when a vacancy occurs or when the steering council deems
|
The selection process, when a vacancy occurs or when the steering council deems
|
||||||
@ -122,10 +122,10 @@ upload them to the :pypi:`Python Package Index <Django>` and to the
|
|||||||
Membership
|
Membership
|
||||||
----------
|
----------
|
||||||
|
|
||||||
`The steering council`_ selects Releasers_ as necessary to maintain their number
|
`The steering council`_ selects Releasers_ as necessary to maintain their
|
||||||
at a minimum of three, in order to spread the workload and avoid over-burdening
|
number at a minimum of three, in order to spread the workload and avoid
|
||||||
or burning out any individual Releaser. There is no upper limit to the number
|
over-burdening or burning out any individual Releaser. There is no upper limit
|
||||||
of Releasers.
|
to the number of Releasers.
|
||||||
|
|
||||||
It's not a requirement that a Releaser is also a Django Fellow, but the Django
|
It's not a requirement that a Releaser is also a Django Fellow, but the Django
|
||||||
Software Foundation has the power to use funding of Fellow positions as a way
|
Software Foundation has the power to use funding of Fellow positions as a way
|
||||||
@ -223,13 +223,14 @@ who demonstrate:
|
|||||||
years must still demonstrate an understanding of Django's changes and
|
years must still demonstrate an understanding of Django's changes and
|
||||||
direction within those three years.
|
direction within those three years.
|
||||||
|
|
||||||
A new council is elected after each release cycle of Django. The election process
|
A new council is elected after each release cycle of Django. The election
|
||||||
works as follows:
|
process works as follows:
|
||||||
|
|
||||||
#. The steering council directs one of its members to notify the Secretary of the
|
#. The steering council directs one of its members to notify the Secretary of
|
||||||
Django Software Foundation, in writing, of the triggering of the election,
|
the Django Software Foundation, in writing, of the triggering of the
|
||||||
and the condition which triggered it. The Secretary post to the appropriate
|
election, and the condition which triggered it. The Secretary post to the
|
||||||
venue -- the `Django Forum`_ to announce the election and its timeline.
|
appropriate venue -- the `Django Forum`_ to announce the election and its
|
||||||
|
timeline.
|
||||||
#. As soon as the election is announced, the `DSF Board`_ begin a period of
|
#. As soon as the election is announced, the `DSF Board`_ begin a period of
|
||||||
voter registration. All `individual members of the DSF`_ are automatically
|
voter registration. All `individual members of the DSF`_ are automatically
|
||||||
registered and need not explicitly register. All other persons who believe
|
registered and need not explicitly register. All other persons who believe
|
||||||
@ -267,12 +268,12 @@ A member of the steering council may be removed by:
|
|||||||
- Becoming disqualified due to actions taken by the Code of Conduct committee
|
- Becoming disqualified due to actions taken by the Code of Conduct committee
|
||||||
of the Django Software Foundation.
|
of the Django Software Foundation.
|
||||||
- Determining that they did not possess the qualifications of a member of the
|
- Determining that they did not possess the qualifications of a member of the
|
||||||
steering council. This determination must be made jointly by the other members
|
steering council. This determination must be made jointly by the other
|
||||||
of the steering council, and the `DSF Board`_. A valid determination of
|
members of the steering council, and the `DSF Board`_. A valid determination
|
||||||
ineligibility requires that all other members of the steering council and all
|
of ineligibility requires that all other members of the steering council and
|
||||||
members of the DSF Board vote who can vote on the issue (the affected person,
|
all members of the DSF Board vote who can vote on the issue (the affected
|
||||||
if a DSF Board member, must not vote) vote "yes" on a motion that the person
|
person, if a DSF Board member, must not vote) vote "yes" on a motion that the
|
||||||
in question is ineligible.
|
person in question is ineligible.
|
||||||
|
|
||||||
.. _`Django Forum`: https://forum.djangoproject.com/
|
.. _`Django Forum`: https://forum.djangoproject.com/
|
||||||
.. _`Django Git repository`: https://github.com/django/django/
|
.. _`Django Git repository`: https://github.com/django/django/
|
||||||
|
@ -45,8 +45,8 @@ security purposes, please see :doc:`our security policies <security>`.
|
|||||||
bugs and/or security issues.
|
bugs and/or security issues.
|
||||||
|
|
||||||
These releases will be 100% compatible with the associated feature release,
|
These releases will be 100% compatible with the associated feature release,
|
||||||
unless this is impossible for security reasons or to prevent data loss.
|
unless this is impossible for security reasons or to prevent data loss. So
|
||||||
So the answer to "should I upgrade to the latest patch release?" will always
|
the answer to "should I upgrade to the latest patch release?" will always
|
||||||
be "yes."
|
be "yes."
|
||||||
|
|
||||||
Long-term support release
|
Long-term support release
|
||||||
@ -123,8 +123,8 @@ See also the :ref:`deprecating-a-feature` guide.
|
|||||||
Supported versions
|
Supported versions
|
||||||
==================
|
==================
|
||||||
|
|
||||||
At any moment in time, Django's developer team will support a set of releases to
|
At any moment in time, Django's developer team will support a set of releases
|
||||||
varying levels. See `the supported versions section
|
to varying levels. See `the supported versions section
|
||||||
<https://www.djangoproject.com/download/#supported-versions>`_ of the download
|
<https://www.djangoproject.com/download/#supported-versions>`_ of the download
|
||||||
page for the current state of support for each version.
|
page for the current state of support for each version.
|
||||||
|
|
||||||
|
@ -292,7 +292,8 @@ requires a security release:
|
|||||||
* Exploits which fail to follow security best practices, such as failure to
|
* Exploits which fail to follow security best practices, such as failure to
|
||||||
sanitize user input. For other examples, see our :ref:`security
|
sanitize user input. For other examples, see our :ref:`security
|
||||||
documentation <cross-site-scripting>`.
|
documentation <cross-site-scripting>`.
|
||||||
* Exploits in AI generated code that do not adhere to security best practices.
|
* Exploits in AI generated code that do not adhere to security best
|
||||||
|
practices.
|
||||||
|
|
||||||
The security team may conclude that the source of the vulnerability is within
|
The security team may conclude that the source of the vulnerability is within
|
||||||
the Python standard library, in which case the reporter will be asked to report
|
the Python standard library, in which case the reporter will be asked to report
|
||||||
@ -303,8 +304,8 @@ On occasion, a security release may be issued to help resolve a security
|
|||||||
vulnerability within a popular third-party package. These reports should come
|
vulnerability within a popular third-party package. These reports should come
|
||||||
from the package maintainers.
|
from the package maintainers.
|
||||||
|
|
||||||
If you are unsure whether your finding meets these criteria, please still report
|
If you are unsure whether your finding meets these criteria, please still
|
||||||
it :ref:`privately by emailing security@djangoproject.com
|
report it :ref:`privately by emailing security@djangoproject.com
|
||||||
<reporting-security-issues>`. The security team will review your report and
|
<reporting-security-issues>`. The security team will review your report and
|
||||||
recommend the correct course of action.
|
recommend the correct course of action.
|
||||||
|
|
||||||
|
@ -32,9 +32,9 @@ don't, `Dive Into Python`_ is a fantastic (and free) online book for beginning
|
|||||||
Python programmers.
|
Python programmers.
|
||||||
|
|
||||||
Those of you who are unfamiliar with version control systems and Trac will find
|
Those of you who are unfamiliar with version control systems and Trac will find
|
||||||
that this tutorial and its links include just enough information to get started.
|
that this tutorial and its links include just enough information to get
|
||||||
However, you'll probably want to read some more about these different tools if
|
started. However, you'll probably want to read some more about these different
|
||||||
you plan on contributing to Django regularly.
|
tools if you plan on contributing to Django regularly.
|
||||||
|
|
||||||
For the most part though, this tutorial tries to explain as much as possible,
|
For the most part though, this tutorial tries to explain as much as possible,
|
||||||
so that it can be of use to the widest audience.
|
so that it can be of use to the widest audience.
|
||||||
@ -52,9 +52,9 @@ so that it can be of use to the widest audience.
|
|||||||
What does this tutorial cover?
|
What does this tutorial cover?
|
||||||
------------------------------
|
------------------------------
|
||||||
|
|
||||||
We'll be walking you through contributing to Django for the first time.
|
We'll be walking you through contributing to Django for the first time. By the
|
||||||
By the end of this tutorial, you should have a basic understanding of both the
|
end of this tutorial, you should have a basic understanding of both the tools
|
||||||
tools and the processes involved. Specifically, we'll be covering the following:
|
and the processes involved. Specifically, we'll be covering the following:
|
||||||
|
|
||||||
* Installing Git.
|
* Installing Git.
|
||||||
* Downloading a copy of Django's development version.
|
* Downloading a copy of Django's development version.
|
||||||
@ -85,7 +85,8 @@ Code of Conduct
|
|||||||
===============
|
===============
|
||||||
|
|
||||||
As a contributor, you can help us keep the Django community open and inclusive.
|
As a contributor, you can help us keep the Django community open and inclusive.
|
||||||
Please read and follow our `Code of Conduct <https://www.djangoproject.com/conduct/>`_.
|
Please read and follow our `Code of Conduct
|
||||||
|
<https://www.djangoproject.com/conduct/>`_.
|
||||||
|
|
||||||
Installing Git
|
Installing Git
|
||||||
==============
|
==============
|
||||||
@ -123,11 +124,11 @@ Download the Django source code repository using the following command:
|
|||||||
all of Django's commit history, which reduces data transfer from ~250 MB
|
all of Django's commit history, which reduces data transfer from ~250 MB
|
||||||
to ~70 MB.
|
to ~70 MB.
|
||||||
|
|
||||||
Now that you have a local copy of Django, you can install it just like you would
|
Now that you have a local copy of Django, you can install it just like you
|
||||||
install any package using ``pip``. The most convenient way to do so is by using
|
would install any package using ``pip``. The most convenient way to do so is by
|
||||||
a *virtual environment*, which is a feature built into Python that allows you
|
using a *virtual environment*, which is a feature built into Python that allows
|
||||||
to keep a separate directory of installed packages for each of your projects so
|
you to keep a separate directory of installed packages for each of your
|
||||||
that they don't interfere with each other.
|
projects so that they don't interfere with each other.
|
||||||
|
|
||||||
It's a good idea to keep all your virtual environments in one place, for
|
It's a good idea to keep all your virtual environments in one place, for
|
||||||
example in ``.virtualenvs/`` in your home directory.
|
example in ``.virtualenvs/`` in your home directory.
|
||||||
@ -176,20 +177,20 @@ Go ahead and install the previously cloned copy of Django:
|
|||||||
|
|
||||||
$ python -m pip install -e /path/to/your/local/clone/django/
|
$ python -m pip install -e /path/to/your/local/clone/django/
|
||||||
|
|
||||||
The installed version of Django is now pointing at your local copy by installing
|
The installed version of Django is now pointing at your local copy by
|
||||||
in editable mode. You will immediately see any changes you make to it, which is
|
installing in editable mode. You will immediately see any changes you make to
|
||||||
of great help when testing your first contribution.
|
it, which is of great help when testing your first contribution.
|
||||||
|
|
||||||
Running Django's test suite for the first time
|
Running Django's test suite for the first time
|
||||||
==============================================
|
==============================================
|
||||||
|
|
||||||
When contributing to Django it's very important that your code changes don't
|
When contributing to Django it's very important that your code changes don't
|
||||||
introduce bugs into other areas of Django. One way to check that Django still
|
introduce bugs into other areas of Django. One way to check that Django still
|
||||||
works after you make your changes is by running Django's test suite. If all
|
works after you make your changes is by running Django's test suite. If all the
|
||||||
the tests still pass, then you can be reasonably sure that your changes
|
tests still pass, then you can be reasonably sure that your changes work and
|
||||||
work and haven't broken other parts of Django. If you've never run Django's test
|
haven't broken other parts of Django. If you've never run Django's test suite
|
||||||
suite before, it's a good idea to run it once beforehand to get familiar with
|
before, it's a good idea to run it once beforehand to get familiar with its
|
||||||
its output.
|
output.
|
||||||
|
|
||||||
Before running the test suite, enter the Django ``tests/`` directory using the
|
Before running the test suite, enter the Django ``tests/`` directory using the
|
||||||
``cd tests`` command, and install test dependencies by running:
|
``cd tests`` command, and install test dependencies by running:
|
||||||
@ -348,8 +349,8 @@ that's really what happens. ``cd`` to the Django ``tests/`` directory and run:
|
|||||||
|
|
||||||
$ ./runtests.py shortcuts
|
$ ./runtests.py shortcuts
|
||||||
|
|
||||||
If the tests ran correctly, you should see one failure corresponding to the test
|
If the tests ran correctly, you should see one failure corresponding to the
|
||||||
method we added, with this error:
|
test method we added, with this error:
|
||||||
|
|
||||||
.. code-block:: pytb
|
.. code-block:: pytb
|
||||||
|
|
||||||
|
@ -24,8 +24,8 @@ place: read this material to quickly get up and running.
|
|||||||
|
|
||||||
.. seealso::
|
.. seealso::
|
||||||
|
|
||||||
If you're new to Python_, you might want to start by getting an idea of what
|
If you're new to Python_, you might want to start by getting an idea of
|
||||||
the language is like. Django is 100% Python, so if you've got minimal
|
what the language is like. Django is 100% Python, so if you've got minimal
|
||||||
comfort with Python you'll probably get a lot more out of Django.
|
comfort with Python you'll probably get a lot more out of Django.
|
||||||
|
|
||||||
If you're new to programming entirely, you might want to start with this
|
If you're new to programming entirely, you might want to start with this
|
||||||
|
@ -32,9 +32,9 @@ you should see something like:
|
|||||||
Set up a database
|
Set up a database
|
||||||
=================
|
=================
|
||||||
|
|
||||||
This step is only necessary if you'd like to work with a "large" database engine
|
This step is only necessary if you'd like to work with a "large" database
|
||||||
like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult
|
engine like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database,
|
||||||
the :ref:`database installation information <database-installation>`.
|
consult the :ref:`database installation information <database-installation>`.
|
||||||
|
|
||||||
Install Django
|
Install Django
|
||||||
==============
|
==============
|
||||||
|
@ -9,15 +9,15 @@ overview of how to write a database-driven web app with Django.
|
|||||||
The goal of this document is to give you enough technical specifics to
|
The goal of this document is to give you enough technical specifics to
|
||||||
understand how Django works, but this isn't intended to be a tutorial or
|
understand how Django works, but this isn't intended to be a tutorial or
|
||||||
reference -- but we've got both! When you're ready to start a project, you can
|
reference -- but we've got both! When you're ready to start a project, you can
|
||||||
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more
|
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into
|
||||||
detailed documentation </topics/index>`.
|
more detailed documentation </topics/index>`.
|
||||||
|
|
||||||
Design your model
|
Design your model
|
||||||
=================
|
=================
|
||||||
|
|
||||||
Although you can use Django without a database, it comes with an
|
Although you can use Django without a database, it comes with an
|
||||||
`object-relational mapper`_ in which you describe your database layout in Python
|
`object-relational mapper`_ in which you describe your database layout in
|
||||||
code.
|
Python code.
|
||||||
|
|
||||||
.. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping
|
.. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping
|
||||||
|
|
||||||
@ -247,19 +247,19 @@ and renders the template with the retrieved data. Here's an example view for
|
|||||||
context = {"year": year, "article_list": a_list}
|
context = {"year": year, "article_list": a_list}
|
||||||
return render(request, "news/year_archive.html", context)
|
return render(request, "news/year_archive.html", context)
|
||||||
|
|
||||||
This example uses Django's :doc:`template system </topics/templates>`, which has
|
This example uses Django's :doc:`template system </topics/templates>`, which
|
||||||
several powerful features but strives to stay simple enough for non-programmers
|
has several powerful features but strives to stay simple enough for
|
||||||
to use.
|
non-programmers to use.
|
||||||
|
|
||||||
Design your templates
|
Design your templates
|
||||||
=====================
|
=====================
|
||||||
|
|
||||||
The code above loads the ``news/year_archive.html`` template.
|
The code above loads the ``news/year_archive.html`` template.
|
||||||
|
|
||||||
Django has a template search path, which allows you to minimize redundancy among
|
Django has a template search path, which allows you to minimize redundancy
|
||||||
templates. In your Django settings, you specify a list of directories to check
|
among templates. In your Django settings, you specify a list of directories to
|
||||||
for templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template doesn't exist
|
check for templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template
|
||||||
in the first directory, it checks the second, and so on.
|
doesn't exist in the first directory, it checks the second, and so on.
|
||||||
|
|
||||||
Let's say the ``news/year_archive.html`` template was found. Here's what that
|
Let's say the ``news/year_archive.html`` template was found. Here's what that
|
||||||
might look like:
|
might look like:
|
||||||
@ -287,14 +287,14 @@ used only for attribute lookup. They also can do dictionary-key lookup, index
|
|||||||
lookup and function calls.
|
lookup and function calls.
|
||||||
|
|
||||||
Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|"
|
Note ``{{ article.pub_date|date:"F j, Y" }}`` uses a Unix-style "pipe" (the "|"
|
||||||
character). This is called a template filter, and it's a way to filter the value
|
character). This is called a template filter, and it's a way to filter the
|
||||||
of a variable. In this case, the date filter formats a Python datetime object in
|
value of a variable. In this case, the date filter formats a Python datetime
|
||||||
the given format (as found in PHP's date function).
|
object in the given format (as found in PHP's date function).
|
||||||
|
|
||||||
You can chain together as many filters as you'd like. You can write :ref:`custom
|
You can chain together as many filters as you'd like. You can write
|
||||||
template filters <howto-writing-custom-template-filters>`. You can write
|
:ref:`custom template filters <howto-writing-custom-template-filters>`. You can
|
||||||
:doc:`custom template tags </howto/custom-template-tags>`, which run custom
|
write :doc:`custom template tags </howto/custom-template-tags>`, which run
|
||||||
Python code behind the scenes.
|
custom Python code behind the scenes.
|
||||||
|
|
||||||
Finally, Django uses the concept of "template inheritance". That's what the
|
Finally, Django uses the concept of "template inheritance". That's what the
|
||||||
``{% extends "base.html" %}`` does. It means "First load the template called
|
``{% extends "base.html" %}`` does. It means "First load the template called
|
||||||
@ -319,9 +319,9 @@ Here's what the "base.html" template, including the use of :doc:`static files
|
|||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
Simplistically, it defines the look-and-feel of the site (with the site's logo),
|
Simplistically, it defines the look-and-feel of the site (with the site's
|
||||||
and provides "holes" for child templates to fill. This means that a site redesign
|
logo), and provides "holes" for child templates to fill. This means that a site
|
||||||
can be done by changing a single file -- the base template.
|
redesign can be done by changing a single file -- the base template.
|
||||||
|
|
||||||
It also lets you create multiple versions of a site, with different base
|
It also lets you create multiple versions of a site, with different base
|
||||||
templates, while reusing child templates. Django's creators have used this
|
templates, while reusing child templates. Django's creators have used this
|
||||||
|
@ -344,8 +344,8 @@ the world! If this wasn't just an example, you could now:
|
|||||||
* Upload the package on your website.
|
* Upload the package on your website.
|
||||||
|
|
||||||
* Post the package on a public repository, such as `the Python Package Index
|
* Post the package on a public repository, such as `the Python Package Index
|
||||||
(PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
|
(PyPI)`_. There is `a good tutorial
|
||||||
tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
|
<https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
|
||||||
for doing this.
|
for doing this.
|
||||||
|
|
||||||
Installing Python packages with a virtual environment
|
Installing Python packages with a virtual environment
|
||||||
|
@ -39,8 +39,8 @@ Creating a project
|
|||||||
==================
|
==================
|
||||||
|
|
||||||
If this is your first time using Django, you'll have to take care of some
|
If this is your first time using Django, you'll have to take care of some
|
||||||
initial setup. Namely, you'll need to auto-generate some code that establishes a
|
initial setup. Namely, you'll need to auto-generate some code that establishes
|
||||||
Django :term:`project` -- a collection of settings for an instance of Django,
|
a Django :term:`project` -- a collection of settings for an instance of Django,
|
||||||
including database configuration, Django-specific options and
|
including database configuration, Django-specific options and
|
||||||
application-specific settings.
|
application-specific settings.
|
||||||
|
|
||||||
@ -122,8 +122,8 @@ You'll see the following output on the command line:
|
|||||||
|
|
||||||
System check identified no issues (0 silenced).
|
System check identified no issues (0 silenced).
|
||||||
|
|
||||||
You have unapplied migrations; your app may not work properly until they are applied.
|
You have unapplied migrations; your app may not work properly until they are
|
||||||
Run 'python manage.py migrate' to apply them.
|
applied. Run 'python manage.py migrate' to apply them.
|
||||||
|
|
||||||
|today| - 15:50:53
|
|today| - 15:50:53
|
||||||
Django version |version|, using settings 'mysite.settings'
|
Django version |version|, using settings 'mysite.settings'
|
||||||
@ -150,7 +150,8 @@ Now's a good time to note: **don't** use this server in anything resembling a
|
|||||||
production environment. It's intended only for use while developing. (We're in
|
production environment. It's intended only for use while developing. (We're in
|
||||||
the business of making web frameworks, not web servers.)
|
the business of making web frameworks, not web servers.)
|
||||||
|
|
||||||
(To serve the site on a different port, see the :djadmin:`runserver` reference.)
|
(To serve the site on a different port, see the :djadmin:`runserver`
|
||||||
|
reference.)
|
||||||
|
|
||||||
.. admonition:: Automatic reloading of :djadmin:`runserver`
|
.. admonition:: Automatic reloading of :djadmin:`runserver`
|
||||||
|
|
||||||
|
@ -51,7 +51,8 @@ come with Django:
|
|||||||
* :mod:`django.contrib.staticfiles` -- A framework for managing
|
* :mod:`django.contrib.staticfiles` -- A framework for managing
|
||||||
static files.
|
static files.
|
||||||
|
|
||||||
These applications are included by default as a convenience for the common case.
|
These applications are included by default as a convenience for the common
|
||||||
|
case.
|
||||||
|
|
||||||
Some of these applications make use of at least one database table, though,
|
Some of these applications make use of at least one database table, though,
|
||||||
so we need to create the tables in the database before we can use them. To do
|
so we need to create the tables in the database before we can use them. To do
|
||||||
@ -62,13 +63,13 @@ that, run the following command:
|
|||||||
$ python manage.py migrate
|
$ python manage.py migrate
|
||||||
|
|
||||||
The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting
|
The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting
|
||||||
and creates any necessary database tables according to the database settings
|
and creates any necessary database tables according to the database settings in
|
||||||
in your :file:`mysite/settings.py` file and the database migrations shipped
|
your :file:`mysite/settings.py` file and the database migrations shipped with
|
||||||
with the app (we'll cover those later). You'll see a message for each
|
the app (we'll cover those later). You'll see a message for each migration it
|
||||||
migration it applies. If you're interested, run the command-line client for your
|
applies. If you're interested, run the command-line client for your database
|
||||||
database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL),
|
and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), ``.tables``
|
||||||
``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to
|
(SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to display the
|
||||||
display the tables Django created.
|
tables Django created.
|
||||||
|
|
||||||
.. admonition:: For the minimalists
|
.. admonition:: For the minimalists
|
||||||
|
|
||||||
@ -94,8 +95,8 @@ additional metadata.
|
|||||||
Django follows the :ref:`DRY Principle <dry>`. The goal is to define your
|
Django follows the :ref:`DRY Principle <dry>`. The goal is to define your
|
||||||
data model in one place and automatically derive things from it.
|
data model in one place and automatically derive things from it.
|
||||||
|
|
||||||
This includes the migrations - unlike in Ruby On Rails, for example, migrations
|
This includes the migrations - unlike in Ruby On Rails, for example,
|
||||||
are entirely derived from your models file, and are essentially a
|
migrations are entirely derived from your models file, and are essentially a
|
||||||
history that Django can roll through to update your database schema to
|
history that Django can roll through to update your database schema to
|
||||||
match your current models.
|
match your current models.
|
||||||
|
|
||||||
@ -138,12 +139,12 @@ format. You'll use this value in your Python code, and your database will use
|
|||||||
it as the column name.
|
it as the column name.
|
||||||
|
|
||||||
You can use an optional first positional argument to a
|
You can use an optional first positional argument to a
|
||||||
:class:`~django.db.models.Field` to designate a human-readable name. That's used
|
:class:`~django.db.models.Field` to designate a human-readable name. That's
|
||||||
in a couple of introspective parts of Django, and it doubles as documentation.
|
used in a couple of introspective parts of Django, and it doubles as
|
||||||
If this field isn't provided, Django will use the machine-readable name. In this
|
documentation. If this field isn't provided, Django will use the
|
||||||
example, we've only defined a human-readable name for ``Question.pub_date``.
|
machine-readable name. In this example, we've only defined a human-readable
|
||||||
For all other fields in this model, the field's machine-readable name will
|
name for ``Question.pub_date``. For all other fields in this model, the field's
|
||||||
suffice as its human-readable name.
|
machine-readable name will suffice as its human-readable name.
|
||||||
|
|
||||||
Some :class:`~django.db.models.Field` classes have required arguments.
|
Some :class:`~django.db.models.Field` classes have required arguments.
|
||||||
:class:`~django.db.models.CharField`, for example, requires that you give it a
|
:class:`~django.db.models.CharField`, for example, requires that you give it a
|
||||||
@ -166,7 +167,8 @@ That small bit of model code gives Django a lot of information. With it, Django
|
|||||||
is able to:
|
is able to:
|
||||||
|
|
||||||
* Create a database schema (``CREATE TABLE`` statements) for this app.
|
* Create a database schema (``CREATE TABLE`` statements) for this app.
|
||||||
* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects.
|
* Create a Python database-access API for accessing ``Question`` and ``Choice``
|
||||||
|
objects.
|
||||||
|
|
||||||
But first we need to tell our project that the ``polls`` app is installed.
|
But first we need to tell our project that the ``polls`` app is installed.
|
||||||
|
|
||||||
@ -223,8 +225,8 @@ they're designed to be human-editable in case you want to manually tweak how
|
|||||||
Django changes things.
|
Django changes things.
|
||||||
|
|
||||||
There's a command that will run the migrations for you and manage your database
|
There's a command that will run the migrations for you and manage your database
|
||||||
schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a
|
schema automatically - that's called :djadmin:`migrate`, and we'll come to it
|
||||||
moment - but first, let's see what SQL that migration would run. The
|
in a moment - but first, let's see what SQL that migration would run. The
|
||||||
:djadmin:`sqlmigrate` command takes migration names and returns their SQL:
|
:djadmin:`sqlmigrate` command takes migration names and returns their SQL:
|
||||||
|
|
||||||
.. console::
|
.. console::
|
||||||
@ -297,7 +299,8 @@ If you're interested, you can also run
|
|||||||
:djadmin:`python manage.py check <check>`; this checks for any problems in
|
:djadmin:`python manage.py check <check>`; this checks for any problems in
|
||||||
your project without making migrations or touching the database.
|
your project without making migrations or touching the database.
|
||||||
|
|
||||||
Now, run :djadmin:`migrate` again to create those model tables in your database:
|
Now, run :djadmin:`migrate` again to create those model tables in your
|
||||||
|
database:
|
||||||
|
|
||||||
.. console::
|
.. console::
|
||||||
|
|
||||||
@ -534,8 +537,8 @@ Introducing the Django Admin
|
|||||||
|
|
||||||
Django was written in a newsroom environment, with a very clear separation
|
Django was written in a newsroom environment, with a very clear separation
|
||||||
between "content publishers" and the "public" site. Site managers use the
|
between "content publishers" and the "public" site. Site managers use the
|
||||||
system to add news stories, events, sports scores, etc., and that content is
|
system to add news stories, events, sports scores, etc., and that content
|
||||||
displayed on the public site. Django solves the problem of creating a
|
is displayed on the public site. Django solves the problem of creating a
|
||||||
unified interface for site administrators to edit content.
|
unified interface for site administrators to edit content.
|
||||||
|
|
||||||
The admin isn't intended to be used by site visitors. It's for site
|
The admin isn't intended to be used by site visitors. It's for site
|
||||||
@ -597,8 +600,8 @@ given language (if Django has appropriate translations).
|
|||||||
Enter the admin site
|
Enter the admin site
|
||||||
--------------------
|
--------------------
|
||||||
|
|
||||||
Now, try logging in with the superuser account you created in the previous step.
|
Now, try logging in with the superuser account you created in the previous
|
||||||
You should see the Django admin index page:
|
step. You should see the Django admin index page:
|
||||||
|
|
||||||
.. image:: _images/admin02.png
|
.. image:: _images/admin02.png
|
||||||
:alt: Django admin index page
|
:alt: Django admin index page
|
||||||
@ -628,15 +631,15 @@ edit it to look like this:
|
|||||||
Explore the free admin functionality
|
Explore the free admin functionality
|
||||||
------------------------------------
|
------------------------------------
|
||||||
|
|
||||||
Now that we've registered ``Question``, Django knows that it should be displayed on
|
Now that we've registered ``Question``, Django knows that it should be
|
||||||
the admin index page:
|
displayed on the admin index page:
|
||||||
|
|
||||||
.. image:: _images/admin03t.png
|
.. image:: _images/admin03t.png
|
||||||
:alt: Django admin index page, now with polls displayed
|
:alt: Django admin index page, now with polls displayed
|
||||||
|
|
||||||
Click "Questions". Now you're at the "change list" page for questions. This page
|
Click "Questions". Now you're at the "change list" page for questions. This
|
||||||
displays all the questions in the database and lets you choose one to change it.
|
page displays all the questions in the database and lets you choose one to
|
||||||
There's the "What's up?" question we created earlier:
|
change it. There's the "What's up?" question we created earlier:
|
||||||
|
|
||||||
.. image:: _images/admin04t.png
|
.. image:: _images/admin04t.png
|
||||||
:alt: Polls change list page
|
:alt: Polls change list page
|
||||||
|
@ -2,8 +2,8 @@
|
|||||||
Writing your first Django app, part 3
|
Writing your first Django app, part 3
|
||||||
=====================================
|
=====================================
|
||||||
|
|
||||||
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
|
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off.
|
||||||
continuing the web-poll application and will focus on creating the public
|
We're continuing the web-poll application and will focus on creating the public
|
||||||
interface -- "views."
|
interface -- "views."
|
||||||
|
|
||||||
.. admonition:: Where to get help:
|
.. admonition:: Where to get help:
|
||||||
@ -51,8 +51,8 @@ the part of the URL after the domain name).
|
|||||||
|
|
||||||
Now in your time on the web you may have come across such beauties as
|
Now in your time on the web you may have come across such beauties as
|
||||||
``ME2/Sites/dirmod.htm?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B``.
|
``ME2/Sites/dirmod.htm?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B``.
|
||||||
You will be pleased to know that Django allows us much more elegant
|
You will be pleased to know that Django allows us much more elegant *URL
|
||||||
*URL patterns* than that.
|
patterns* than that.
|
||||||
|
|
||||||
A URL pattern is the general form of a URL - for example:
|
A URL pattern is the general form of a URL - for example:
|
||||||
``/newsarchive/<year>/<month>/``.
|
``/newsarchive/<year>/<month>/``.
|
||||||
@ -135,8 +135,8 @@ Write views that actually do something
|
|||||||
|
|
||||||
Each view is responsible for doing one of two things: returning an
|
Each view is responsible for doing one of two things: returning an
|
||||||
:class:`~django.http.HttpResponse` object containing the content for the
|
:class:`~django.http.HttpResponse` object containing the content for the
|
||||||
requested page, or raising an exception such as :exc:`~django.http.Http404`. The
|
requested page, or raising an exception such as :exc:`~django.http.Http404`.
|
||||||
rest is up to you.
|
The rest is up to you.
|
||||||
|
|
||||||
Your view can read records from a database, or not. It can use a template
|
Your view can read records from a database, or not. It can use a template
|
||||||
system such as Django's -- or a third-party Python template system -- or not.
|
system such as Django's -- or a third-party Python template system -- or not.
|
||||||
@ -167,9 +167,9 @@ commas, according to publication date:
|
|||||||
# Leave the rest of the views (detail, results, vote) unchanged
|
# Leave the rest of the views (detail, results, vote) unchanged
|
||||||
|
|
||||||
There's a problem here, though: the page's design is hardcoded in the view. If
|
There's a problem here, though: the page's design is hardcoded in the view. If
|
||||||
you want to change the way the page looks, you'll have to edit this Python code.
|
you want to change the way the page looks, you'll have to edit this Python
|
||||||
So let's use Django's template system to separate the design from Python by
|
code. So let's use Django's template system to separate the design from Python
|
||||||
creating a template that the view can use.
|
by creating a template that the view can use.
|
||||||
|
|
||||||
First, create a directory called ``templates`` in your ``polls`` directory.
|
First, create a directory called ``templates`` in your ``polls`` directory.
|
||||||
Django will look for templates in there.
|
Django will look for templates in there.
|
||||||
@ -268,8 +268,8 @@ rewritten:
|
|||||||
|
|
||||||
Note that once we've done this in all these views, we no longer need to import
|
Note that once we've done this in all these views, we no longer need to import
|
||||||
:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
|
:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
|
||||||
want to keep ``HttpResponse`` if you still have the stub methods for ``detail``,
|
want to keep ``HttpResponse`` if you still have the stub methods for
|
||||||
``results``, and ``vote``).
|
``detail``, ``results``, and ``vote``).
|
||||||
|
|
||||||
The :func:`~django.shortcuts.render` function takes the request object as its
|
The :func:`~django.shortcuts.render` function takes the request object as its
|
||||||
first argument, a template name as its second argument and a dictionary as its
|
first argument, a template name as its second argument and a dictionary as its
|
||||||
@ -279,8 +279,8 @@ object of the given template rendered with the given context.
|
|||||||
Raising a 404 error
|
Raising a 404 error
|
||||||
===================
|
===================
|
||||||
|
|
||||||
Now, let's tackle the question detail view -- the page that displays the question text
|
Now, let's tackle the question detail view -- the page that displays the
|
||||||
for a given poll. Here's the view:
|
question text for a given poll. Here's the view:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
:caption: ``polls/views.py``
|
:caption: ``polls/views.py``
|
||||||
@ -361,8 +361,8 @@ Use the template system
|
|||||||
=======================
|
=======================
|
||||||
|
|
||||||
Back to the ``detail()`` view for our poll application. Given the context
|
Back to the ``detail()`` view for our poll application. Given the context
|
||||||
variable ``question``, here's what the ``polls/detail.html`` template might look
|
variable ``question``, here's what the ``polls/detail.html`` template might
|
||||||
like:
|
look like:
|
||||||
|
|
||||||
.. code-block:: html+django
|
.. code-block:: html+django
|
||||||
:caption: ``polls/templates/polls/detail.html``
|
:caption: ``polls/templates/polls/detail.html``
|
||||||
@ -375,15 +375,15 @@ like:
|
|||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
The template system uses dot-lookup syntax to access variable attributes. In
|
The template system uses dot-lookup syntax to access variable attributes. In
|
||||||
the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
|
the example of ``{{ question.question_text }}``, first Django does a dictionary
|
||||||
on the object ``question``. Failing that, it tries an attribute lookup -- which
|
lookup on the object ``question``. Failing that, it tries an attribute lookup
|
||||||
works, in this case. If attribute lookup had failed, it would've tried a
|
-- which works, in this case. If attribute lookup had failed, it would've tried
|
||||||
list-index lookup.
|
a list-index lookup.
|
||||||
|
|
||||||
Method-calling happens in the :ttag:`{% for %}<for>` loop:
|
Method-calling happens in the :ttag:`{% for %}<for>` loop:
|
||||||
``question.choice_set.all`` is interpreted as the Python code
|
``question.choice_set.all`` is interpreted as the Python code
|
||||||
``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
|
``question.choice_set.all()``, which returns an iterable of ``Choice`` objects
|
||||||
suitable for use in the :ttag:`{% for %}<for>` tag.
|
and is suitable for use in the :ttag:`{% for %}<for>` tag.
|
||||||
|
|
||||||
See the :doc:`template guide </topics/templates>` for more about templates.
|
See the :doc:`template guide </topics/templates>` for more about templates.
|
||||||
|
|
||||||
|
@ -2,8 +2,8 @@
|
|||||||
Writing your first Django app, part 4
|
Writing your first Django app, part 4
|
||||||
=====================================
|
=====================================
|
||||||
|
|
||||||
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're
|
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off.
|
||||||
continuing the web-poll application and will focus on form processing and
|
We're continuing the web-poll application and will focus on form processing and
|
||||||
cutting down our code.
|
cutting down our code.
|
||||||
|
|
||||||
.. admonition:: Where to get help:
|
.. admonition:: Where to get help:
|
||||||
@ -42,8 +42,8 @@ A quick rundown:
|
|||||||
POST data ``choice=#`` where # is the ID of the selected choice. This is the
|
POST data ``choice=#`` where # is the ID of the selected choice. This is the
|
||||||
basic concept of HTML forms.
|
basic concept of HTML forms.
|
||||||
|
|
||||||
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we
|
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and
|
||||||
set ``method="post"``. Using ``method="post"`` (as opposed to
|
we set ``method="post"``. Using ``method="post"`` (as opposed to
|
||||||
``method="get"``) is very important, because the act of submitting this
|
``method="get"``) is very important, because the act of submitting this
|
||||||
form will alter data server-side. Whenever you create a form that alters
|
form will alter data server-side. Whenever you create a form that alters
|
||||||
data server-side, use ``method="post"``. This tip isn't specific to
|
data server-side, use ``method="post"``. This tip isn't specific to
|
||||||
@ -158,8 +158,8 @@ As mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an
|
|||||||
:class:`~django.http.HttpRequest` objects, see the :doc:`request and
|
:class:`~django.http.HttpRequest` objects, see the :doc:`request and
|
||||||
response documentation </ref/request-response>`.
|
response documentation </ref/request-response>`.
|
||||||
|
|
||||||
After somebody votes in a question, the ``vote()`` view redirects to the results
|
After somebody votes in a question, the ``vote()`` view redirects to the
|
||||||
page for the question. Let's write that view:
|
results page for the question. Let's write that view:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
:caption: ``polls/views.py``
|
:caption: ``polls/views.py``
|
||||||
@ -190,8 +190,8 @@ Now, create a ``polls/results.html`` template:
|
|||||||
|
|
||||||
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
|
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
|
||||||
|
|
||||||
Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
|
Now, go to ``/polls/1/`` in your browser and vote in the question. You should
|
||||||
results page that gets updated each time you vote. If you submit the form
|
see a results page that gets updated each time you vote. If you submit the form
|
||||||
without having chosen a choice, you should see the error message.
|
without having chosen a choice, you should see the error message.
|
||||||
|
|
||||||
Use generic views: Less code is better
|
Use generic views: Less code is better
|
||||||
@ -206,12 +206,12 @@ the database according to a parameter passed in the URL, loading a template and
|
|||||||
returning the rendered template. Because this is so common, Django provides a
|
returning the rendered template. Because this is so common, Django provides a
|
||||||
shortcut, called the "generic views" system.
|
shortcut, called the "generic views" system.
|
||||||
|
|
||||||
Generic views abstract common patterns to the point where you don't even need to
|
Generic views abstract common patterns to the point where you don't even need
|
||||||
write Python code to write an app. For example, the
|
to write Python code to write an app. For example, the
|
||||||
:class:`~django.views.generic.list.ListView` and
|
:class:`~django.views.generic.list.ListView` and
|
||||||
:class:`~django.views.generic.detail.DetailView` generic views
|
:class:`~django.views.generic.detail.DetailView` generic views abstract the
|
||||||
abstract the concepts of "display a list of objects" and
|
concepts of "display a list of objects" and "display a detail page for a
|
||||||
"display a detail page for a particular type of object" respectively.
|
particular type of object" respectively.
|
||||||
|
|
||||||
Let's convert our poll app to use the generic views system, so we can delete a
|
Let's convert our poll app to use the generic views system, so we can delete a
|
||||||
bunch of our own code. We'll have to take a few steps to make the conversion.
|
bunch of our own code. We'll have to take a few steps to make the conversion.
|
||||||
|
@ -122,7 +122,8 @@ tests earlier, but it's never too late to get started.
|
|||||||
Sometimes it's difficult to figure out where to get started with writing tests.
|
Sometimes it's difficult to figure out where to get started with writing tests.
|
||||||
If you have written several thousand lines of Python, choosing something to
|
If you have written several thousand lines of Python, choosing something to
|
||||||
test might not be easy. In such a case, it's fruitful to write your first test
|
test might not be easy. In such a case, it's fruitful to write your first test
|
||||||
the next time you make a change, either when you add a new feature or fix a bug.
|
the next time you make a change, either when you add a new feature or fix a
|
||||||
|
bug.
|
||||||
|
|
||||||
So let's do that right away.
|
So let's do that right away.
|
||||||
|
|
||||||
@ -135,9 +136,10 @@ We identify a bug
|
|||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
Fortunately, there's a little bug in the ``polls`` application for us to fix
|
Fortunately, there's a little bug in the ``polls`` application for us to fix
|
||||||
right away: the ``Question.was_published_recently()`` method returns ``True`` if
|
right away: the ``Question.was_published_recently()`` method returns ``True``
|
||||||
the ``Question`` was published within the last day (which is correct) but also if
|
if the ``Question`` was published within the last day (which is correct) but
|
||||||
the ``Question``’s ``pub_date`` field is in the future (which certainly isn't).
|
also if the ``Question``’s ``pub_date`` field is in the future (which certainly
|
||||||
|
isn't).
|
||||||
|
|
||||||
Confirm the bug by using the :djadmin:`shell` to check the method on a question
|
Confirm the bug by using the :djadmin:`shell` to check the method on a question
|
||||||
whose date lies in the future:
|
whose date lies in the future:
|
||||||
@ -191,9 +193,9 @@ Put the following in the ``tests.py`` file in the ``polls`` application:
|
|||||||
future_question = Question(pub_date=time)
|
future_question = Question(pub_date=time)
|
||||||
self.assertIs(future_question.was_published_recently(), False)
|
self.assertIs(future_question.was_published_recently(), False)
|
||||||
|
|
||||||
Here we have created a :class:`django.test.TestCase` subclass with a method that
|
Here we have created a :class:`django.test.TestCase` subclass with a method
|
||||||
creates a ``Question`` instance with a ``pub_date`` in the future. We then check
|
that creates a ``Question`` instance with a ``pub_date`` in the future. We then
|
||||||
the output of ``was_published_recently()`` - which *ought* to be False.
|
check the output of ``was_published_recently()`` - which *ought* to be False.
|
||||||
|
|
||||||
Running tests
|
Running tests
|
||||||
-------------
|
-------------
|
||||||
@ -242,8 +244,8 @@ What happened is this:
|
|||||||
|
|
||||||
* it looked for test methods - ones whose names begin with ``test``
|
* it looked for test methods - ones whose names begin with ``test``
|
||||||
|
|
||||||
* in ``test_was_published_recently_with_future_question`` it created a ``Question``
|
* in ``test_was_published_recently_with_future_question`` it created a
|
||||||
instance whose ``pub_date`` field is 30 days in the future
|
``Question`` instance whose ``pub_date`` field is 30 days in the future
|
||||||
|
|
||||||
* ... and using the ``assertIs()`` method, it discovered that its
|
* ... and using the ``assertIs()`` method, it discovered that its
|
||||||
``was_published_recently()`` returns ``True``, though we wanted it to return
|
``was_published_recently()`` returns ``True``, though we wanted it to return
|
||||||
@ -255,10 +257,10 @@ occurred.
|
|||||||
Fixing the bug
|
Fixing the bug
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
We already know what the problem is: ``Question.was_published_recently()`` should
|
We already know what the problem is: ``Question.was_published_recently()``
|
||||||
return ``False`` if its ``pub_date`` is in the future. Amend the method in
|
should return ``False`` if its ``pub_date`` is in the future. Amend the method
|
||||||
``models.py``, so that it will only return ``True`` if the date is also in the
|
in ``models.py``, so that it will only return ``True`` if the date is also in
|
||||||
past:
|
the past:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
:caption: ``polls/models.py``
|
:caption: ``polls/models.py``
|
||||||
@ -292,8 +294,8 @@ More comprehensive tests
|
|||||||
------------------------
|
------------------------
|
||||||
|
|
||||||
While we're here, we can further pin down the ``was_published_recently()``
|
While we're here, we can further pin down the ``was_published_recently()``
|
||||||
method; in fact, it would be positively embarrassing if in fixing one bug we had
|
method; in fact, it would be positively embarrassing if in fixing one bug we
|
||||||
introduced another.
|
had introduced another.
|
||||||
|
|
||||||
Add two more test methods to the same class, to test the behavior of the method
|
Add two more test methods to the same class, to test the behavior of the method
|
||||||
more comprehensively:
|
more comprehensively:
|
||||||
@ -320,8 +322,9 @@ more comprehensively:
|
|||||||
recent_question = Question(pub_date=time)
|
recent_question = Question(pub_date=time)
|
||||||
self.assertIs(recent_question.was_published_recently(), True)
|
self.assertIs(recent_question.was_published_recently(), True)
|
||||||
|
|
||||||
And now we have three tests that confirm that ``Question.was_published_recently()``
|
And now we have three tests that confirm that
|
||||||
returns sensible values for past, recent, and future questions.
|
``Question.was_published_recently()`` returns sensible values for past, recent,
|
||||||
|
and future questions.
|
||||||
|
|
||||||
Again, ``polls`` is a minimal application, but however complex it grows in the
|
Again, ``polls`` is a minimal application, but however complex it grows in the
|
||||||
future and whatever other code it interacts with, we now have some guarantee
|
future and whatever other code it interacts with, we now have some guarantee
|
||||||
@ -644,19 +647,19 @@ code is suffering from test bloat, which brings us to:
|
|||||||
When testing, more is better
|
When testing, more is better
|
||||||
============================
|
============================
|
||||||
|
|
||||||
It might seem that our tests are growing out of control. At this rate there will
|
It might seem that our tests are growing out of control. At this rate there
|
||||||
soon be more code in our tests than in our application, and the repetition
|
will soon be more code in our tests than in our application, and the repetition
|
||||||
is unaesthetic, compared to the elegant conciseness of the rest of our code.
|
is unaesthetic, compared to the elegant conciseness of the rest of our code.
|
||||||
|
|
||||||
**It doesn't matter**. Let them grow. For the most part, you can write a test
|
**It doesn't matter**. Let them grow. For the most part, you can write a test
|
||||||
once and then forget about it. It will continue performing its useful function
|
once and then forget about it. It will continue performing its useful function
|
||||||
as you continue to develop your program.
|
as you continue to develop your program.
|
||||||
|
|
||||||
Sometimes tests will need to be updated. Suppose that we amend our views so that
|
Sometimes tests will need to be updated. Suppose that we amend our views so
|
||||||
only ``Question`` entries with associated ``Choice`` instances are published.
|
that only ``Question`` entries with associated ``Choice`` instances are
|
||||||
In that case, many of our existing tests will fail - *telling us exactly which
|
published. In that case, many of our existing tests will fail - *telling us
|
||||||
tests need to be amended to bring them up to date*, so to that extent tests
|
exactly which tests need to be amended to bring them up to date*, so to that
|
||||||
help look after themselves.
|
extent tests help look after themselves.
|
||||||
|
|
||||||
At worst, as you continue developing, you might find that you have some tests
|
At worst, as you continue developing, you might find that you have some tests
|
||||||
that are now redundant. Even that's not a problem; in testing redundancy is
|
that are now redundant. Even that's not a problem; in testing redundancy is
|
||||||
|
@ -2,10 +2,10 @@
|
|||||||
Writing your first Django app, part 7
|
Writing your first Django app, part 7
|
||||||
=====================================
|
=====================================
|
||||||
|
|
||||||
This tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off. We're
|
This tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off.
|
||||||
continuing the web-poll application and will focus on customizing Django's
|
We're continuing the web-poll application and will focus on customizing
|
||||||
automatically-generated admin site that we first explored in :doc:`Tutorial 2
|
Django's automatically-generated admin site that we first explored in
|
||||||
</intro/tutorial02>`.
|
:doc:`Tutorial 2 </intro/tutorial02>`.
|
||||||
|
|
||||||
.. admonition:: Where to get help:
|
.. admonition:: Where to get help:
|
||||||
|
|
||||||
@ -71,8 +71,8 @@ up into fieldsets:
|
|||||||
admin.site.register(Question, QuestionAdmin)
|
admin.site.register(Question, QuestionAdmin)
|
||||||
|
|
||||||
The first element of each tuple in
|
The first element of each tuple in
|
||||||
:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset.
|
:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the
|
||||||
Here's what our form looks like now:
|
fieldset. Here's what our form looks like now:
|
||||||
|
|
||||||
.. image:: _images/admin08t.png
|
.. image:: _images/admin08t.png
|
||||||
:alt: Form has fieldsets now
|
:alt: Form has fieldsets now
|
||||||
@ -104,10 +104,10 @@ looks like this:
|
|||||||
.. image:: _images/admin09.png
|
.. image:: _images/admin09.png
|
||||||
:alt: Choice admin page
|
:alt: Choice admin page
|
||||||
|
|
||||||
In that form, the "Question" field is a select box containing every question in the
|
In that form, the "Question" field is a select box containing every question in
|
||||||
database. Django knows that a :class:`~django.db.models.ForeignKey` should be
|
the database. Django knows that a :class:`~django.db.models.ForeignKey` should
|
||||||
represented in the admin as a ``<select>`` box. In our case, only one question
|
be represented in the admin as a ``<select>`` box. In our case, only one
|
||||||
exists at this point.
|
question exists at this point.
|
||||||
|
|
||||||
Also note the "Add another question" link next to "Question." Every object with
|
Also note the "Add another question" link next to "Question." Every object with
|
||||||
a ``ForeignKey`` relationship to another gets this for free. When you click
|
a ``ForeignKey`` relationship to another gets this for free. When you click
|
||||||
@ -116,12 +116,12 @@ If you add a question in that window and click "Save", Django will save the
|
|||||||
question to the database and dynamically add it as the selected choice on the
|
question to the database and dynamically add it as the selected choice on the
|
||||||
"Add choice" form you're looking at.
|
"Add choice" form you're looking at.
|
||||||
|
|
||||||
But, really, this is an inefficient way of adding ``Choice`` objects to the system.
|
But, really, this is an inefficient way of adding ``Choice`` objects to the
|
||||||
It'd be better if you could add a bunch of Choices directly when you create the
|
system. It'd be better if you could add a bunch of Choices directly when you
|
||||||
``Question`` object. Let's make that happen.
|
create the ``Question`` object. Let's make that happen.
|
||||||
|
|
||||||
Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question``
|
Remove the ``register()`` call for the ``Choice`` model. Then, edit the
|
||||||
registration code to read:
|
``Question`` registration code to read:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
:caption: ``polls/admin.py``
|
:caption: ``polls/admin.py``
|
||||||
@ -146,8 +146,8 @@ registration code to read:
|
|||||||
|
|
||||||
admin.site.register(Question, QuestionAdmin)
|
admin.site.register(Question, QuestionAdmin)
|
||||||
|
|
||||||
This tells Django: "``Choice`` objects are edited on the ``Question`` admin page. By
|
This tells Django: "``Choice`` objects are edited on the ``Question`` admin
|
||||||
default, provide enough fields for 3 choices."
|
page. By default, provide enough fields for 3 choices."
|
||||||
|
|
||||||
Load the "Add question" page to see how that looks:
|
Load the "Add question" page to see how that looks:
|
||||||
|
|
||||||
@ -167,8 +167,8 @@ image shows an added slot:
|
|||||||
:alt: Additional slot added dynamically
|
:alt: Additional slot added dynamically
|
||||||
|
|
||||||
One small problem, though. It takes a lot of screen space to display all the
|
One small problem, though. It takes a lot of screen space to display all the
|
||||||
fields for entering related ``Choice`` objects. For that reason, Django offers a
|
fields for entering related ``Choice`` objects. For that reason, Django offers
|
||||||
tabular way of displaying inline related objects. To use it, change the
|
a tabular way of displaying inline related objects. To use it, change the
|
||||||
``ChoiceInline`` declaration to read:
|
``ChoiceInline`` declaration to read:
|
||||||
|
|
||||||
.. code-block:: python
|
.. code-block:: python
|
||||||
@ -278,10 +278,10 @@ This is shaping up well. Let's add some search capability::
|
|||||||
search_fields = ["question_text"]
|
search_fields = ["question_text"]
|
||||||
|
|
||||||
That adds a search box at the top of the change list. When somebody enters
|
That adds a search box at the top of the change list. When somebody enters
|
||||||
search terms, Django will search the ``question_text`` field. You can use as many
|
search terms, Django will search the ``question_text`` field. You can use as
|
||||||
fields as you'd like -- although because it uses a ``LIKE`` query behind the
|
many fields as you'd like -- although because it uses a ``LIKE`` query behind
|
||||||
scenes, limiting the number of search fields to a reasonable number will make
|
the scenes, limiting the number of search fields to a reasonable number will
|
||||||
it easier for your database to do the search.
|
make it easier for your database to do the search.
|
||||||
|
|
||||||
Now's also a good time to note that change lists give you free pagination. The
|
Now's also a good time to note that change lists give you free pagination. The
|
||||||
default is to display 100 items per page. :attr:`Change list pagination
|
default is to display 100 items per page. :attr:`Change list pagination
|
||||||
@ -413,9 +413,9 @@ Customize the admin index page
|
|||||||
On a similar note, you might want to customize the look and feel of the Django
|
On a similar note, you might want to customize the look and feel of the Django
|
||||||
admin index page.
|
admin index page.
|
||||||
|
|
||||||
By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
|
By default, it displays all the apps in :setting:`INSTALLED_APPS` that have
|
||||||
registered with the admin application, in alphabetical order. You may want to
|
been registered with the admin application, in alphabetical order. You may want
|
||||||
make significant changes to the layout. After all, the index is probably the
|
to make significant changes to the layout. After all, the index is probably the
|
||||||
most important page of the admin, and it should be easy to use.
|
most important page of the admin, and it should be easy to use.
|
||||||
|
|
||||||
The template to customize is ``admin/index.html``. (Do the same as with
|
The template to customize is ``admin/index.html``. (Do the same as with
|
||||||
|
@ -2,11 +2,11 @@
|
|||||||
Writing your first Django app, part 8
|
Writing your first Django app, part 8
|
||||||
=====================================
|
=====================================
|
||||||
|
|
||||||
This tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>` left off. We've
|
This tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>` left off.
|
||||||
built our web-poll application and will now look at third-party packages. One of
|
We've built our web-poll application and will now look at third-party packages.
|
||||||
Django's strengths is the rich ecosystem of third-party packages. They're
|
One of Django's strengths is the rich ecosystem of third-party packages.
|
||||||
community developed packages that can be used to quickly improve the feature set
|
They're community developed packages that can be used to quickly improve the
|
||||||
of an application.
|
feature set of an application.
|
||||||
|
|
||||||
This tutorial will show how to add :pypi:`Django Debug Toolbar
|
This tutorial will show how to add :pypi:`Django Debug Toolbar
|
||||||
<django-debug-toolbar>`, a commonly used third-party package. The Django Debug
|
<django-debug-toolbar>`, a commonly used third-party package. The Django Debug
|
||||||
@ -68,7 +68,8 @@ resolve the issue yourself, there are options available to you.
|
|||||||
<https://django-debug-toolbar.readthedocs.io/en/latest/tips.html>`_ that
|
<https://django-debug-toolbar.readthedocs.io/en/latest/tips.html>`_ that
|
||||||
outlines troubleshooting options.
|
outlines troubleshooting options.
|
||||||
#. Search for similar issues on the package's issue tracker. Django Debug
|
#. Search for similar issues on the package's issue tracker. Django Debug
|
||||||
Toolbar’s is `on GitHub <https://github.com/django-commons/django-debug-toolbar/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc>`_.
|
Toolbar’s is `on GitHub
|
||||||
|
<https://github.com/django-commons/django-debug-toolbar/issues>`_.
|
||||||
#. Consult the `Django Forum <https://forum.djangoproject.com/>`_.
|
#. Consult the `Django Forum <https://forum.djangoproject.com/>`_.
|
||||||
#. Join the `Django Discord server <https://chat.djangoproject.com>`_.
|
#. Join the `Django Discord server <https://chat.djangoproject.com>`_.
|
||||||
|
|
||||||
|
@ -10,8 +10,8 @@ with this intro (in fact, if you've read every single word, you've read about
|
|||||||
So what's next?
|
So what's next?
|
||||||
|
|
||||||
Well, we've always been big fans of learning by doing. At this point you should
|
Well, we've always been big fans of learning by doing. At this point you should
|
||||||
know enough to start a project of your own and start fooling around. As you need
|
know enough to start a project of your own and start fooling around. As you
|
||||||
to learn new tricks, come back to the documentation. There's also a bigger
|
need to learn new tricks, come back to the documentation. There's also a bigger
|
||||||
`Django ecosystem`_ out there for you to explore that the community has
|
`Django ecosystem`_ out there for you to explore that the community has
|
||||||
created.
|
created.
|
||||||
|
|
||||||
@ -100,8 +100,8 @@ reasons:
|
|||||||
* To add documentation for new features as new features get added, or as
|
* To add documentation for new features as new features get added, or as
|
||||||
Django APIs or behaviors change.
|
Django APIs or behaviors change.
|
||||||
|
|
||||||
Django's documentation is kept in the same source control system as its code. It
|
Django's documentation is kept in the same source control system as its code.
|
||||||
lives in the :source:`docs` directory of our Git repository. Each document
|
It lives in the :source:`docs` directory of our Git repository. Each document
|
||||||
online is a separate text file in the repository.
|
online is a separate text file in the repository.
|
||||||
|
|
||||||
Where to get it
|
Where to get it
|
||||||
@ -115,15 +115,16 @@ On the web
|
|||||||
|
|
||||||
The most recent version of the Django documentation lives at
|
The most recent version of the Django documentation lives at
|
||||||
https://docs.djangoproject.com/en/dev/. These HTML pages are generated
|
https://docs.djangoproject.com/en/dev/. These HTML pages are generated
|
||||||
automatically from the text files in source control. That means they reflect the
|
automatically from the text files in source control. That means they reflect
|
||||||
"latest and greatest" in Django -- they include the very latest corrections and
|
the "latest and greatest" in Django -- they include the very latest corrections
|
||||||
additions, and they discuss the latest Django features, which may only be
|
and additions, and they discuss the latest Django features, which may only be
|
||||||
available to users of the Django development version. (See
|
available to users of the Django development version. (See
|
||||||
:ref:`differences-between-doc-versions` below.)
|
:ref:`differences-between-doc-versions` below.)
|
||||||
|
|
||||||
We encourage you to help improve the docs by submitting changes, corrections and
|
We encourage you to help improve the docs by submitting changes, corrections
|
||||||
suggestions in the `ticket system`_. The Django developers actively monitor the
|
and suggestions in the `ticket system`_. The Django developers actively monitor
|
||||||
ticket system and use your feedback to improve the documentation for everybody.
|
the ticket system and use your feedback to improve the documentation for
|
||||||
|
everybody.
|
||||||
|
|
||||||
Note, however, that tickets should explicitly relate to the documentation,
|
Note, however, that tickets should explicitly relate to the documentation,
|
||||||
rather than asking broad tech-support questions. If you need help with your
|
rather than asking broad tech-support questions. If you need help with your
|
||||||
|
@ -145,7 +145,7 @@ if __name__ == "__main__":
|
|||||||
"--disable",
|
"--disable",
|
||||||
"line-too-long", # Disable sphinx-lint version
|
"line-too-long", # Disable sphinx-lint version
|
||||||
"--max-line-length",
|
"--max-line-length",
|
||||||
"80",
|
"79",
|
||||||
*params,
|
*params,
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
@ -34,9 +34,9 @@ stack are independent of another wherever possible.
|
|||||||
Less code
|
Less code
|
||||||
---------
|
---------
|
||||||
|
|
||||||
Django apps should use as little code as possible; they should lack boilerplate.
|
Django apps should use as little code as possible; they should lack
|
||||||
Django should take full advantage of Python's dynamic capabilities, such as
|
boilerplate. Django should take full advantage of Python's dynamic
|
||||||
introspection.
|
capabilities, such as introspection.
|
||||||
|
|
||||||
.. _quick-development:
|
.. _quick-development:
|
||||||
|
|
||||||
|
@ -3,10 +3,10 @@ Third-party distributions of Django
|
|||||||
===================================
|
===================================
|
||||||
|
|
||||||
Many third-party distributors are now providing versions of Django integrated
|
Many third-party distributors are now providing versions of Django integrated
|
||||||
with their package-management systems. These can make installation and upgrading
|
with their package-management systems. These can make installation and
|
||||||
much easier for users of Django since the integration includes the ability to
|
upgrading much easier for users of Django since the integration includes the
|
||||||
automatically install dependencies (like database adapters) that Django
|
ability to automatically install dependencies (like database adapters) that
|
||||||
requires.
|
Django requires.
|
||||||
|
|
||||||
Typically, these packages are based on the latest stable release of Django, so
|
Typically, these packages are based on the latest stable release of Django, so
|
||||||
if you want to use the development version of Django you'll need to follow the
|
if you want to use the development version of Django you'll need to follow the
|
||||||
@ -21,15 +21,14 @@ a list of `Third Party Distributions`_ to help you out.
|
|||||||
|
|
||||||
.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions
|
.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions
|
||||||
|
|
||||||
|
|
||||||
For distributors
|
For distributors
|
||||||
================
|
================
|
||||||
|
|
||||||
If you'd like to package Django for distribution, we'd be happy to help out!
|
If you'd like to package Django for distribution, we'd be happy to help out!
|
||||||
Please introduce yourself on the `Django Forum`_.
|
Please introduce yourself on the `Django Forum`_.
|
||||||
|
|
||||||
We also encourage all distributors to subscribe to the |django-announce| mailing
|
We also encourage all distributors to subscribe to the |django-announce|
|
||||||
list, which is a (very) low-traffic list for announcing new releases of Django
|
mailing list, which is a (very) low-traffic list for announcing new releases of
|
||||||
and important bugfixes.
|
Django and important bugfixes.
|
||||||
|
|
||||||
.. _Django Forum: https://forum.djangoproject.com/
|
.. _Django Forum: https://forum.djangoproject.com/
|
||||||
|
@ -2,8 +2,8 @@
|
|||||||
Meta-documentation and miscellany
|
Meta-documentation and miscellany
|
||||||
=================================
|
=================================
|
||||||
|
|
||||||
Documentation that we can't find a more organized place for. Like that drawer in
|
Documentation that we can't find a more organized place for. Like that drawer
|
||||||
your kitchen with the scissors, batteries, duct tape, and other junk.
|
in your kitchen with the scissors, batteries, duct tape, and other junk.
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 2
|
:maxdepth: 2
|
||||||
|
@ -321,12 +321,12 @@ Methods
|
|||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
In the usual initialization process, the ``ready`` method is only called
|
In the usual initialization process, the ``ready`` method is only
|
||||||
once by Django. But in some corner cases, particularly in tests which
|
called once by Django. But in some corner cases, particularly in tests
|
||||||
are fiddling with installed applications, ``ready`` might be called more
|
which are fiddling with installed applications, ``ready`` might be
|
||||||
than once. In that case, either write idempotent methods, or put a flag
|
called more than once. In that case, either write idempotent methods,
|
||||||
on your ``AppConfig`` classes to prevent rerunning code which should
|
or put a flag on your ``AppConfig`` classes to prevent rerunning code
|
||||||
be executed exactly one time.
|
which should be executed exactly one time.
|
||||||
|
|
||||||
.. _namespace package:
|
.. _namespace package:
|
||||||
|
|
||||||
|
@ -189,11 +189,13 @@ Model fields
|
|||||||
* **fields.E121**: ``max_length`` must be a positive integer.
|
* **fields.E121**: ``max_length`` must be a positive integer.
|
||||||
* **fields.W122**: ``max_length`` is ignored when used with
|
* **fields.W122**: ``max_length`` is ignored when used with
|
||||||
``<integer field type>``.
|
``<integer field type>``.
|
||||||
* **fields.E130**: ``DecimalField``\s must define a ``decimal_places`` attribute.
|
* **fields.E130**: ``DecimalField``\s must define a ``decimal_places``
|
||||||
|
attribute.
|
||||||
* **fields.E131**: ``decimal_places`` must be a non-negative integer.
|
* **fields.E131**: ``decimal_places`` must be a non-negative integer.
|
||||||
* **fields.E132**: ``DecimalField``\s must define a ``max_digits`` attribute.
|
* **fields.E132**: ``DecimalField``\s must define a ``max_digits`` attribute.
|
||||||
* **fields.E133**: ``max_digits`` must be a positive integer.
|
* **fields.E133**: ``max_digits`` must be a positive integer.
|
||||||
* **fields.E134**: ``max_digits`` must be greater or equal to ``decimal_places``.
|
* **fields.E134**: ``max_digits`` must be greater or equal to
|
||||||
|
``decimal_places``.
|
||||||
* **fields.E140**: ``FilePathField``\s must have either ``allow_files`` or
|
* **fields.E140**: ``FilePathField``\s must have either ``allow_files`` or
|
||||||
``allow_folders`` set to True.
|
``allow_folders`` set to True.
|
||||||
* **fields.E150**: ``GenericIPAddressField``\s cannot have ``blank=True`` if
|
* **fields.E150**: ``GenericIPAddressField``\s cannot have ``blank=True`` if
|
||||||
@ -324,7 +326,8 @@ Related fields
|
|||||||
``<model>``.
|
``<model>``.
|
||||||
* **fields.E338**: The intermediary model ``<through model>`` has no field
|
* **fields.E338**: The intermediary model ``<through model>`` has no field
|
||||||
``<field name>``.
|
``<field name>``.
|
||||||
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to ``<model>``.
|
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to
|
||||||
|
``<model>``.
|
||||||
* **fields.E340**: The field's intermediary table ``<table name>`` clashes with
|
* **fields.E340**: The field's intermediary table ``<table name>`` clashes with
|
||||||
the table name of ``<model>``/``<model>.<field name>``.
|
the table name of ``<model>``/``<model>.<field name>``.
|
||||||
* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.
|
* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.
|
||||||
@ -382,7 +385,8 @@ Models
|
|||||||
* **models.E019**: Autogenerated column name too long for M2M field
|
* **models.E019**: Autogenerated column name too long for M2M field
|
||||||
``<M2M field>``. Maximum length is ``<maximum length>`` for database
|
``<M2M field>``. Maximum length is ``<maximum length>`` for database
|
||||||
``<alias>``.
|
``<alias>``.
|
||||||
* **models.E020**: The ``<model>.check()`` class method is currently overridden.
|
* **models.E020**: The ``<model>.check()`` class method is currently
|
||||||
|
overridden.
|
||||||
* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used
|
* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used
|
||||||
together.
|
together.
|
||||||
* **models.E022**: ``<function>`` contains a lazy reference to
|
* **models.E022**: ``<function>`` contains a lazy reference to
|
||||||
@ -442,7 +446,8 @@ Models
|
|||||||
Management Commands
|
Management Commands
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
The following checks verify custom management commands are correctly configured:
|
The following checks verify custom management commands are correctly
|
||||||
|
configured:
|
||||||
|
|
||||||
* **commands.E001**: The ``migrate`` and ``makemigrations`` commands must have
|
* **commands.E001**: The ``migrate`` and ``makemigrations`` commands must have
|
||||||
the same ``autodetector``.
|
the same ``autodetector``.
|
||||||
@ -489,12 +494,13 @@ The following checks are run if you use the :option:`check --deploy` option:
|
|||||||
* **security.W005**: You have not set the
|
* **security.W005**: You have not set the
|
||||||
:setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this,
|
:setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this,
|
||||||
your site is potentially vulnerable to attack via an insecure connection to a
|
your site is potentially vulnerable to attack via an insecure connection to a
|
||||||
subdomain. Only set this to ``True`` if you are certain that all subdomains of
|
subdomain. Only set this to ``True`` if you are certain that all subdomains
|
||||||
your domain should be served exclusively via SSL.
|
of your domain should be served exclusively via SSL.
|
||||||
* **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not
|
* **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not
|
||||||
set to ``True``, so your pages will not be served with an
|
set to ``True``, so your pages will not be served with an
|
||||||
``'X-Content-Type-Options: nosniff'`` header. You should consider enabling
|
``'X-Content-Type-Options: nosniff'`` header. You should consider enabling
|
||||||
this header to prevent the browser from identifying content types incorrectly.
|
this header to prevent the browser from identifying content types
|
||||||
|
incorrectly.
|
||||||
* **security.W007**: Your ``SECURE_BROWSER_XSS_FILTER`` setting is not
|
* **security.W007**: Your ``SECURE_BROWSER_XSS_FILTER`` setting is not
|
||||||
set to ``True``, so your pages will not be served with an
|
set to ``True``, so your pages will not be served with an
|
||||||
``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling
|
``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling
|
||||||
@ -504,7 +510,8 @@ The following checks are run if you use the :option:`check --deploy` option:
|
|||||||
* **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to
|
* **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to
|
||||||
``True``. Unless your site should be available over both SSL and non-SSL
|
``True``. Unless your site should be available over both SSL and non-SSL
|
||||||
connections, you may want to either set this setting to ``True`` or configure
|
connections, you may want to either set this setting to ``True`` or configure
|
||||||
a load balancer or reverse-proxy server to redirect all connections to HTTPS.
|
a load balancer or reverse-proxy server to redirect all connections to
|
||||||
|
HTTPS.
|
||||||
* **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters,
|
* **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters,
|
||||||
less than 5 unique characters, or it's prefixed with ``'django-insecure-'``
|
less than 5 unique characters, or it's prefixed with ``'django-insecure-'``
|
||||||
indicating that it was generated automatically by Django. Please generate a
|
indicating that it was generated automatically by Django. Please generate a
|
||||||
@ -521,18 +528,19 @@ The following checks are run if you use the :option:`check --deploy` option:
|
|||||||
to ``True``. Using a secure-only session cookie makes it more difficult for
|
to ``True``. Using a secure-only session cookie makes it more difficult for
|
||||||
network traffic sniffers to hijack user sessions.
|
network traffic sniffers to hijack user sessions.
|
||||||
* **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``.
|
* **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``.
|
||||||
Using a secure-only session cookie makes it more difficult for network traffic
|
Using a secure-only session cookie makes it more difficult for network
|
||||||
sniffers to hijack user sessions.
|
traffic sniffers to hijack user sessions.
|
||||||
* **security.W013**: You have :mod:`django.contrib.sessions` in your
|
* **security.W013**: You have :mod:`django.contrib.sessions` in your
|
||||||
:setting:`INSTALLED_APPS`, but you have not set
|
:setting:`INSTALLED_APPS`, but you have not set
|
||||||
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
|
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
|
||||||
cookie makes it more difficult for cross-site scripting attacks to hijack user
|
cookie makes it more difficult for cross-site scripting attacks to hijack
|
||||||
sessions.
|
user sessions.
|
||||||
* **security.W014**: You have
|
* **security.W014**: You have
|
||||||
:class:`django.contrib.sessions.middleware.SessionMiddleware` in your
|
:class:`django.contrib.sessions.middleware.SessionMiddleware` in your
|
||||||
:setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY`
|
:setting:`MIDDLEWARE`, but you have not set
|
||||||
to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for
|
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
|
||||||
cross-site scripting attacks to hijack user sessions.
|
cookie makes it more difficult for cross-site scripting attacks to hijack
|
||||||
|
user sessions.
|
||||||
* **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``.
|
* **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``.
|
||||||
Using an ``HttpOnly`` session cookie makes it more difficult for cross-site
|
Using an ``HttpOnly`` session cookie makes it more difficult for cross-site
|
||||||
scripting attacks to hijack user sessions.
|
scripting attacks to hijack user sessions.
|
||||||
@ -585,8 +593,8 @@ Signals
|
|||||||
-------
|
-------
|
||||||
|
|
||||||
* **signals.E001**: ``<handler>`` was connected to the ``<signal>`` signal with
|
* **signals.E001**: ``<handler>`` was connected to the ``<signal>`` signal with
|
||||||
a lazy reference to the sender ``<app label>.<model>``, but app ``<app label>``
|
a lazy reference to the sender ``<app label>.<model>``, but app
|
||||||
isn't installed or doesn't provide model ``<model>``.
|
``<app label>`` isn't installed or doesn't provide model ``<model>``.
|
||||||
|
|
||||||
Templates
|
Templates
|
||||||
---------
|
---------
|
||||||
@ -871,8 +879,8 @@ The following checks are performed on the default
|
|||||||
unique.
|
unique.
|
||||||
* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin
|
* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin
|
||||||
permission for model ``<model>``.
|
permission for model ``<model>``.
|
||||||
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for model
|
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for
|
||||||
``<model>``.
|
model ``<model>``.
|
||||||
* **auth.E007**: The :attr:`verbose_name
|
* **auth.E007**: The :attr:`verbose_name
|
||||||
<django.db.models.Options.verbose_name>` of model ``<model>`` must be at most
|
<django.db.models.Options.verbose_name>` of model ``<model>`` must be at most
|
||||||
244 characters for its builtin permission names
|
244 characters for its builtin permission names
|
||||||
|
@ -10,8 +10,8 @@ views.
|
|||||||
|
|
||||||
Many of Django's built-in class-based views inherit from other class-based
|
Many of Django's built-in class-based views inherit from other class-based
|
||||||
views or various mixins. Because this inheritance chain is very important, the
|
views or various mixins. Because this inheritance chain is very important, the
|
||||||
ancestor classes are documented under the section title of **Ancestors (MRO)**.
|
ancestor classes are documented under the section title of **Ancestors
|
||||||
MRO is an acronym for Method Resolution Order.
|
(MRO)**. MRO is an acronym for Method Resolution Order.
|
||||||
|
|
||||||
``View``
|
``View``
|
||||||
========
|
========
|
||||||
@ -103,9 +103,9 @@ MRO is an acronym for Method Resolution Order.
|
|||||||
delegate to a method that matches the HTTP method; a ``GET`` will be
|
delegate to a method that matches the HTTP method; a ``GET`` will be
|
||||||
delegated to ``get()``, a ``POST`` to ``post()``, and so on.
|
delegated to ``get()``, a ``POST`` to ``post()``, and so on.
|
||||||
|
|
||||||
By default, a ``HEAD`` request will be delegated to ``get()``.
|
By default, a ``HEAD`` request will be delegated to ``get()``. If you
|
||||||
If you need to handle ``HEAD`` requests in a different way than ``GET``,
|
need to handle ``HEAD`` requests in a different way than ``GET``, you
|
||||||
you can override the ``head()`` method. See
|
can override the ``head()`` method. See
|
||||||
:ref:`supporting-other-http-methods` for an example.
|
:ref:`supporting-other-http-methods` for an example.
|
||||||
|
|
||||||
.. method:: http_method_not_allowed(request, *args, **kwargs)
|
.. method:: http_method_not_allowed(request, *args, **kwargs)
|
||||||
|
@ -222,9 +222,9 @@ views for displaying drilldown pages for date-based data.
|
|||||||
context will be:
|
context will be:
|
||||||
|
|
||||||
* ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`
|
* ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`
|
||||||
object containing all days that have objects available in the given month,
|
object containing all days that have objects available in the given
|
||||||
according to ``queryset``, represented as :class:`datetime.datetime`
|
month, according to ``queryset``, represented as
|
||||||
objects, in ascending order.
|
:class:`datetime.datetime` objects, in ascending order.
|
||||||
|
|
||||||
* ``month``: A :class:`~datetime.date` object
|
* ``month``: A :class:`~datetime.date` object
|
||||||
representing the given month.
|
representing the given month.
|
||||||
|
@ -78,8 +78,9 @@ Multiple object mixins
|
|||||||
|
|
||||||
.. attribute:: ordering
|
.. attribute:: ordering
|
||||||
|
|
||||||
A string or list of strings specifying the ordering to apply to the ``queryset``.
|
A string or list of strings specifying the ordering to apply to the
|
||||||
Valid values are the same as those for :meth:`~django.db.models.query.QuerySet.order_by`.
|
``queryset``. Valid values are the same as those for
|
||||||
|
:meth:`~django.db.models.query.QuerySet.order_by`.
|
||||||
|
|
||||||
.. attribute:: paginate_by
|
.. attribute:: paginate_by
|
||||||
|
|
||||||
@ -106,10 +107,10 @@ Multiple object mixins
|
|||||||
.. attribute:: paginator_class
|
.. attribute:: paginator_class
|
||||||
|
|
||||||
The paginator class to be used for pagination. By default,
|
The paginator class to be used for pagination. By default,
|
||||||
:class:`django.core.paginator.Paginator` is used. If the custom paginator
|
:class:`django.core.paginator.Paginator` is used. If the custom
|
||||||
class doesn't have the same constructor interface as
|
paginator class doesn't have the same constructor interface as
|
||||||
:class:`django.core.paginator.Paginator`, you will also need to
|
:class:`django.core.paginator.Paginator`, you will also need to provide
|
||||||
provide an implementation for :meth:`get_paginator`.
|
an implementation for :meth:`get_paginator`.
|
||||||
|
|
||||||
.. attribute:: context_object_name
|
.. attribute:: context_object_name
|
||||||
|
|
||||||
@ -122,8 +123,8 @@ Multiple object mixins
|
|||||||
|
|
||||||
.. method:: get_ordering()
|
.. method:: get_ordering()
|
||||||
|
|
||||||
Returns a string (or iterable of strings) that defines the ordering that
|
Returns a string (or iterable of strings) that defines the ordering
|
||||||
will be applied to the ``queryset``.
|
that will be applied to the ``queryset``.
|
||||||
|
|
||||||
Returns :attr:`ordering` by default.
|
Returns :attr:`ordering` by default.
|
||||||
|
|
||||||
@ -132,10 +133,10 @@ Multiple object mixins
|
|||||||
Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
|
Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
|
||||||
``is_paginated``).
|
``is_paginated``).
|
||||||
|
|
||||||
Constructed by paginating ``queryset`` into pages of size ``page_size``.
|
Constructed by paginating ``queryset`` into pages of size
|
||||||
If the request contains a ``page`` argument, either as a captured URL
|
``page_size``. If the request contains a ``page`` argument, either as a
|
||||||
argument or as a GET argument, ``object_list`` will correspond to the
|
captured URL argument or as a GET argument, ``object_list`` will
|
||||||
objects from that page.
|
correspond to the objects from that page.
|
||||||
|
|
||||||
.. method:: get_paginate_by(queryset)
|
.. method:: get_paginate_by(queryset)
|
||||||
|
|
||||||
|
@ -102,9 +102,10 @@ Single object mixins
|
|||||||
|
|
||||||
Returns context data for displaying the object.
|
Returns context data for displaying the object.
|
||||||
|
|
||||||
The base implementation of this method requires that the ``self.object``
|
The base implementation of this method requires that the
|
||||||
attribute be set by the view (even if ``None``). Be sure to do this if
|
``self.object`` attribute be set by the view (even if ``None``). Be
|
||||||
you are using this mixin without one of the built-in views that does so.
|
sure to do this if you are using this mixin without one of the built-in
|
||||||
|
views that does so.
|
||||||
|
|
||||||
It returns a dictionary with these contents:
|
It returns a dictionary with these contents:
|
||||||
|
|
||||||
|
@ -2,7 +2,8 @@
|
|||||||
Class-based views mixins
|
Class-based views mixins
|
||||||
========================
|
========================
|
||||||
|
|
||||||
Class-based views API reference. For introductory material, see :doc:`/topics/class-based-views/mixins`.
|
Class-based views API reference. For introductory material, see
|
||||||
|
:doc:`/topics/class-based-views/mixins`.
|
||||||
|
|
||||||
.. toctree::
|
.. toctree::
|
||||||
:maxdepth: 1
|
:maxdepth: 1
|
||||||
|
@ -15,13 +15,14 @@ have loaded in a hidden frame or iframe.
|
|||||||
An example of clickjacking
|
An example of clickjacking
|
||||||
==========================
|
==========================
|
||||||
|
|
||||||
Suppose an online store has a page where a logged-in user can click "Buy Now" to
|
Suppose an online store has a page where a logged-in user can click "Buy Now"
|
||||||
purchase an item. A user has chosen to stay logged into the store all the time
|
to purchase an item. A user has chosen to stay logged into the store all the
|
||||||
for convenience. An attacker site might create an "I Like Ponies" button on one
|
time for convenience. An attacker site might create an "I Like Ponies" button
|
||||||
of their own pages, and load the store's page in a transparent iframe such that
|
on one of their own pages, and load the store's page in a transparent iframe
|
||||||
the "Buy Now" button is invisibly overlaid on the "I Like Ponies" button. If the
|
such that the "Buy Now" button is invisibly overlaid on the "I Like Ponies"
|
||||||
user visits the attacker's site, clicking "I Like Ponies" will cause an
|
button. If the user visits the attacker's site, clicking "I Like Ponies" will
|
||||||
inadvertent click on the "Buy Now" button and an unknowing purchase of the item.
|
cause an inadvertent click on the "Buy Now" button and an unknowing purchase of
|
||||||
|
the item.
|
||||||
|
|
||||||
.. _clickjacking-prevention:
|
.. _clickjacking-prevention:
|
||||||
|
|
||||||
@ -93,8 +94,8 @@ that tells the middleware not to set the header::
|
|||||||
Setting ``X-Frame-Options`` per view
|
Setting ``X-Frame-Options`` per view
|
||||||
------------------------------------
|
------------------------------------
|
||||||
|
|
||||||
To set the ``X-Frame-Options`` header on a per view basis, Django provides these
|
To set the ``X-Frame-Options`` header on a per view basis, Django provides
|
||||||
decorators::
|
these decorators::
|
||||||
|
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from django.views.decorators.clickjacking import xframe_options_deny
|
from django.views.decorators.clickjacking import xframe_options_deny
|
||||||
|
@ -189,8 +189,8 @@ You can do it like this::
|
|||||||
|
|
||||||
Notice first that we've moved ``make_published`` into a method and renamed the
|
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
|
``modeladmin`` parameter to ``self``, and second that we've now put the string
|
||||||
``'make_published'`` in ``actions`` instead of a direct function reference. This
|
``'make_published'`` in ``actions`` instead of a direct function reference.
|
||||||
tells the :class:`ModelAdmin` to look up the action as a method.
|
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
|
Defining actions as methods gives the action more idiomatic access to the
|
||||||
:class:`ModelAdmin` itself, allowing the action to call any of the methods
|
: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)
|
.. method:: AdminSite.add_action(action, name=None)
|
||||||
|
|
||||||
Some actions are best if they're made available to *any* object in the admin
|
Some actions are best if they're made available to *any* object in the
|
||||||
site -- the export action defined above would be a good candidate. You can
|
admin site -- the export action defined above would be a good candidate.
|
||||||
make an action globally available using :meth:`AdminSite.add_action`. For
|
You can make an action globally available using
|
||||||
example::
|
:meth:`AdminSite.add_action`. For example::
|
||||||
|
|
||||||
from django.contrib import admin
|
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
|
This makes the ``export_selected_objects`` action globally available as an
|
||||||
action named "export_selected_objects". You can explicitly give the action
|
action named "export_selected_objects". You can explicitly give the action
|
||||||
a name -- good if you later want to programmatically :ref:`remove the action
|
a name -- good if you later want to programmatically :ref:`remove the
|
||||||
<disabling-admin-actions>` -- by passing a second argument to
|
action <disabling-admin-actions>` -- by passing a second argument to
|
||||||
:meth:`AdminSite.add_action`::
|
:meth:`AdminSite.add_action`::
|
||||||
|
|
||||||
admin.site.add_action(export_selected_objects, "export_selected")
|
admin.site.add_action(export_selected_objects, "export_selected")
|
||||||
@ -317,11 +317,11 @@ Disabling a site-wide action
|
|||||||
|
|
||||||
.. method:: AdminSite.disable_action(name)
|
.. method:: AdminSite.disable_action(name)
|
||||||
|
|
||||||
If you need to disable a :ref:`site-wide action <adminsite-actions>` you can
|
If you need to disable a :ref:`site-wide action <adminsite-actions>` you
|
||||||
call :meth:`AdminSite.disable_action`.
|
can call :meth:`AdminSite.disable_action`.
|
||||||
|
|
||||||
For example, you can use this method to remove the built-in "delete selected
|
For example, you can use this method to remove the built-in "delete
|
||||||
objects" action::
|
selected objects" action::
|
||||||
|
|
||||||
admin.site.disable_action("delete_selected")
|
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
|
Finally, you can conditionally enable or disable actions on a per-request
|
||||||
(and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
|
(and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
|
||||||
|
|
||||||
This returns a dictionary of actions allowed. The keys are action names, and
|
This returns a dictionary of actions allowed. The keys are action names,
|
||||||
the values are ``(function, name, short_description)`` tuples.
|
and the values are ``(function, name, short_description)`` tuples.
|
||||||
|
|
||||||
For example, if you only want users whose names begin with 'J' to be able
|
For example, if you only want users whose names begin with 'J' to be able
|
||||||
to delete objects in bulk::
|
to delete objects in bulk::
|
||||||
|
@ -127,8 +127,8 @@ The ``register`` decorator
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
It's given one or more model classes to register with the ``ModelAdmin``.
|
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
|
If you're using a custom :class:`AdminSite`, pass it using the ``site``
|
||||||
argument::
|
keyword argument::
|
||||||
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from .models import Author, Editor, Reader
|
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.
|
application. Such modules are expected to register models with the admin.
|
||||||
|
|
||||||
Typically you won't need to call this function directly as
|
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
|
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
|
``ModelAdmin`` subclasses into your code and register them to the custom
|
||||||
@ -204,13 +205,13 @@ subclass::
|
|||||||
.. attribute:: ModelAdmin.actions_on_bottom
|
.. attribute:: ModelAdmin.actions_on_bottom
|
||||||
|
|
||||||
Controls where on the page the actions bar appears. By default, the admin
|
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;
|
changelist displays actions at the top of the page (``actions_on_top =
|
||||||
actions_on_bottom = False``).
|
True; actions_on_bottom = False``).
|
||||||
|
|
||||||
.. attribute:: ModelAdmin.actions_selection_counter
|
.. attribute:: ModelAdmin.actions_selection_counter
|
||||||
|
|
||||||
Controls whether a selection counter is displayed next to the action dropdown.
|
Controls whether a selection counter is displayed next to the action
|
||||||
By default, the admin changelist will display it
|
dropdown. By default, the admin changelist will display it
|
||||||
(``actions_selection_counter = True``).
|
(``actions_selection_counter = True``).
|
||||||
|
|
||||||
.. attribute:: ModelAdmin.date_hierarchy
|
.. attribute:: ModelAdmin.date_hierarchy
|
||||||
@ -313,7 +314,8 @@ subclass::
|
|||||||
values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
|
values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
|
||||||
read-only.
|
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
|
The ``fields`` option accepts the same types of values as
|
||||||
:attr:`~ModelAdmin.list_display`, except that callables and ``__`` lookups
|
: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`.
|
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
|
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
|
tuple. In this example, the ``url`` and ``title`` fields will display on
|
||||||
same line and the ``content`` field will be displayed below them on its
|
the same line and the ``content`` field will be displayed below them on its
|
||||||
own line::
|
own line::
|
||||||
|
|
||||||
class FlatPageAdmin(admin.ModelAdmin):
|
class FlatPageAdmin(admin.ModelAdmin):
|
||||||
@ -334,11 +336,11 @@ subclass::
|
|||||||
dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
|
dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
|
||||||
as described in the next section.
|
as described in the next section.
|
||||||
|
|
||||||
If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
|
If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are
|
||||||
Django will default to displaying each field that isn't an ``AutoField`` and
|
present, Django will default to displaying each field that isn't an
|
||||||
has ``editable=True``, in a single fieldset, in the same order as the fields
|
``AutoField`` and has ``editable=True``, in a single fieldset, in the same
|
||||||
are defined in the model, followed by any fields defined in
|
order as the fields are defined in the model, followed by any fields
|
||||||
:attr:`~ModelAdmin.readonly_fields`.
|
defined in :attr:`~ModelAdmin.readonly_fields`.
|
||||||
|
|
||||||
.. attribute:: ModelAdmin.fieldsets
|
.. attribute:: ModelAdmin.fieldsets
|
||||||
|
|
||||||
@ -380,10 +382,10 @@ subclass::
|
|||||||
|
|
||||||
.. image:: _images/fieldsets.png
|
.. image:: _images/fieldsets.png
|
||||||
|
|
||||||
If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
|
If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are
|
||||||
Django will default to displaying each field that isn't an ``AutoField`` and
|
present, Django will default to displaying each field that isn't an
|
||||||
has ``editable=True``, in a single fieldset, in the same order as the fields
|
``AutoField`` and has ``editable=True``, in a single fieldset, in the same
|
||||||
are defined in the model.
|
order as the fields are defined in the model.
|
||||||
|
|
||||||
The ``field_options`` dictionary can have the following keys:
|
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``
|
since the admin has its own way of defining fields, the ``Meta.fields``
|
||||||
attribute will be ignored.
|
attribute will be ignored.
|
||||||
|
|
||||||
If the ``ModelForm`` is only going to be used for the admin, the easiest
|
If the ``ModelForm`` is only going to be used for the admin, the
|
||||||
solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
|
easiest solution is to omit the ``Meta.model`` attribute, since
|
||||||
will provide the correct model to use. Alternatively, you can set
|
``ModelAdmin`` will provide the correct model to use. Alternatively,
|
||||||
``fields = []`` in the ``Meta`` class to satisfy the validation on the
|
you can set ``fields = []`` in the ``Meta`` class to satisfy the
|
||||||
``ModelForm``.
|
validation on the ``ModelForm``.
|
||||||
|
|
||||||
.. admonition:: ``ModelAdmin.exclude`` takes precedence
|
.. admonition:: ``ModelAdmin.exclude`` takes precedence
|
||||||
|
|
||||||
@ -922,9 +924,9 @@ subclass::
|
|||||||
.. attribute:: ModelAdmin.list_max_show_all
|
.. attribute:: ModelAdmin.list_max_show_all
|
||||||
|
|
||||||
Set ``list_max_show_all`` to control how many items can appear on a "Show
|
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
|
all" admin change list page. The admin will display a "Show all" link on
|
||||||
change list only if the total result count is less than or equal to this
|
the change list only if the total result count is less than or equal to
|
||||||
setting. By default, this is set to ``200``.
|
this setting. By default, this is set to ``200``.
|
||||||
|
|
||||||
.. attribute:: ModelAdmin.list_per_page
|
.. attribute:: ModelAdmin.list_per_page
|
||||||
|
|
||||||
@ -1080,8 +1082,8 @@ subclass::
|
|||||||
You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
|
You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
|
||||||
``django.contrib.admin`` module.
|
``django.contrib.admin`` module.
|
||||||
|
|
||||||
Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
|
Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or
|
||||||
``choices`` set.
|
has ``choices`` set.
|
||||||
|
|
||||||
.. attribute:: ModelAdmin.autocomplete_fields
|
.. attribute:: ModelAdmin.autocomplete_fields
|
||||||
|
|
||||||
@ -1270,8 +1272,8 @@ subclass::
|
|||||||
WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
|
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
|
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`
|
lookup by appending it the field. For example, you could use
|
||||||
by setting ``search_fields`` to ``['first_name__exact']``.
|
:lookup:`exact` by setting ``search_fields`` to ``['first_name__exact']``.
|
||||||
|
|
||||||
Some (older) shortcuts for specifying a field lookup are also available.
|
Some (older) shortcuts for specifying a field lookup are also available.
|
||||||
You can prefix a field in ``search_fields`` with the following characters
|
You can prefix a field in ``search_fields`` with the following characters
|
||||||
@ -1298,9 +1300,9 @@ subclass::
|
|||||||
.. attribute:: ModelAdmin.show_full_result_count
|
.. attribute:: ModelAdmin.show_full_result_count
|
||||||
|
|
||||||
Set ``show_full_result_count`` to control whether the full count of objects
|
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)``).
|
should be displayed on a filtered admin page (e.g. ``99 results (103
|
||||||
If this option is set to ``False``, a text like ``99 results (Show all)``
|
total)``). If this option is set to ``False``, a text like ``99 results
|
||||||
is displayed instead.
|
(Show all)`` is displayed instead.
|
||||||
|
|
||||||
The default of ``show_full_result_count=True`` generates a query to perform
|
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
|
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
|
.. attribute:: ModelAdmin.view_on_site
|
||||||
|
|
||||||
Set ``view_on_site`` to control whether or not to display the "View on site" link.
|
Set ``view_on_site`` to control whether or not to display the "View on
|
||||||
This link should bring you to a URL where you can display the saved object.
|
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
|
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`
|
default), the object's :meth:`~django.db.models.Model.get_absolute_url`
|
||||||
method will be used to generate the url.
|
method will be used to generate the url.
|
||||||
|
|
||||||
If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
|
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
|
but you don't want the "View on site" button to appear, you only need to
|
||||||
``view_on_site`` to ``False``::
|
set ``view_on_site`` to ``False``::
|
||||||
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
|
||||||
@ -1473,9 +1476,9 @@ default templates used by the :class:`ModelAdmin` views:
|
|||||||
readonly.append("age") # Edits the class attribute.
|
readonly.append("age") # Edits the class attribute.
|
||||||
return readonly
|
return readonly
|
||||||
|
|
||||||
This results in ``readonly_fields`` becoming
|
This results in ``readonly_fields`` becoming ``["name", "age", "age",
|
||||||
``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added
|
...]``, even for a superuser, as ``"age"`` is added each time non-superuser
|
||||||
each time non-superuser visits the page.
|
visits the page.
|
||||||
|
|
||||||
.. method:: ModelAdmin.get_ordering(request)
|
.. 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
|
The ``get_search_results`` method modifies the list of objects displayed
|
||||||
into those that match the provided search term. It accepts the request, a
|
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.
|
queryset that applies the current filters, and the user-provided search
|
||||||
It returns a tuple containing a queryset modified to implement the search, and
|
term. It returns a tuple containing a queryset modified to implement the
|
||||||
a boolean indicating if the results may contain duplicates.
|
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
|
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
|
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 =
|
This implementation is more efficient than ``search_fields =
|
||||||
('name', '=age')`` which results in a string comparison for the numeric
|
('name', '=age')`` which results in a string comparison for the numeric
|
||||||
field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')``
|
field, for example
|
||||||
on PostgreSQL.
|
``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')`` on PostgreSQL.
|
||||||
|
|
||||||
.. _Solr: https://solr.apache.org
|
.. _Solr: https://solr.apache.org
|
||||||
.. _Haystack: https://haystacksearch.org
|
.. _Haystack: https://haystacksearch.org
|
||||||
@ -1544,8 +1548,8 @@ default templates used by the :class:`ModelAdmin` views:
|
|||||||
|
|
||||||
.. method:: ModelAdmin.get_autocomplete_fields(request)
|
.. method:: ModelAdmin.get_autocomplete_fields(request)
|
||||||
|
|
||||||
The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is
|
The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and
|
||||||
expected to return a ``list`` or ``tuple`` of field names that will be
|
is expected to return a ``list`` or ``tuple`` of field names that will be
|
||||||
displayed with an autocomplete widget as described above in the
|
displayed with an autocomplete widget as described above in the
|
||||||
:attr:`ModelAdmin.autocomplete_fields` section.
|
: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
|
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
|
``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`
|
a ``dictionary``, as described above in the
|
||||||
section.
|
:attr:`ModelAdmin.prepopulated_fields` section.
|
||||||
|
|
||||||
.. method:: ModelAdmin.get_list_display(request)
|
.. 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)
|
.. method:: ModelAdmin.get_list_display_links(request, list_display)
|
||||||
|
|
||||||
The ``get_list_display_links`` method is given the ``HttpRequest`` and
|
The ``get_list_display_links`` method is given the ``HttpRequest`` and the
|
||||||
the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
|
``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`. It
|
||||||
It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
|
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
|
names on the changelist that will be linked to the change view, as
|
||||||
in the :attr:`ModelAdmin.list_display_links` section.
|
described in the :attr:`ModelAdmin.list_display_links` section.
|
||||||
|
|
||||||
.. method:: ModelAdmin.get_exclude(request, obj=None)
|
.. 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``
|
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
|
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
|
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)
|
.. method:: ModelAdmin.get_list_filter(request)
|
||||||
|
|
||||||
@ -1611,8 +1616,8 @@ default templates used by the :class:`ModelAdmin` views:
|
|||||||
|
|
||||||
.. method:: ModelAdmin.get_search_fields(request)
|
.. method:: ModelAdmin.get_search_fields(request)
|
||||||
|
|
||||||
The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
|
The ``get_search_fields`` method is given the ``HttpRequest`` and is
|
||||||
to return the same kind of sequence type as for the
|
expected to return the same kind of sequence type as for the
|
||||||
:attr:`~ModelAdmin.search_fields` attribute.
|
:attr:`~ModelAdmin.search_fields` attribute.
|
||||||
|
|
||||||
.. method:: ModelAdmin.get_sortable_by(request)
|
.. 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
|
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
|
``obj`` being edited (or ``None`` on an add form) and is expected to return
|
||||||
a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
|
a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
|
||||||
objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
|
objects, as described below in the
|
||||||
section. For example, the following would return inlines without the default
|
:class:`~django.contrib.admin.InlineModelAdmin` section. For example, the
|
||||||
filtering based on add, change, delete, and view permissions::
|
following would return inlines without the default filtering based on add,
|
||||||
|
change, delete, and view permissions::
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
inlines = [MyInline]
|
inlines = [MyInline]
|
||||||
@ -1862,8 +1868,8 @@ default templates used by the :class:`ModelAdmin` views:
|
|||||||
``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
|
``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
|
||||||
``ModelAdmin`` ignores this value, overriding it with the
|
``ModelAdmin`` ignores this value, overriding it with the
|
||||||
:attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
|
:attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
|
||||||
omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
|
omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide
|
||||||
correct model to use.
|
the correct model to use.
|
||||||
|
|
||||||
.. method:: ModelAdmin.get_changelist_formset(request, **kwargs)
|
.. 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
|
can be manipulated by the user, they must be sanitized to prevent
|
||||||
unauthorized data exposure.
|
unauthorized data exposure.
|
||||||
|
|
||||||
The ``lookup_allowed()`` method is given a lookup path from the query string
|
The ``lookup_allowed()`` method is given a lookup path from the query
|
||||||
(e.g. ``'user__email'``), the corresponding value
|
string (e.g. ``'user__email'``), the corresponding value (e.g.
|
||||||
(e.g. ``'user@example.com'``), and the request, and returns a boolean
|
``'user@example.com'``), and the request, and returns a boolean indicating
|
||||||
indicating whether filtering the changelist's ``QuerySet`` using the
|
whether filtering the changelist's ``QuerySet`` using the parameters is
|
||||||
parameters is permitted. If ``lookup_allowed()`` returns ``False``,
|
permitted. If ``lookup_allowed()`` returns ``False``,
|
||||||
``DisallowedModelAdminLookup``
|
``DisallowedModelAdminLookup`` (subclass of
|
||||||
(subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
|
:exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
|
||||||
|
|
||||||
By default, ``lookup_allowed()`` allows access to a model's local fields,
|
By default, ``lookup_allowed()`` allows access to a model's local fields,
|
||||||
field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from
|
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)
|
.. method:: ModelAdmin.has_view_permission(request, obj=None)
|
||||||
|
|
||||||
Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.
|
Should return ``True`` if viewing ``obj`` is permitted, ``False``
|
||||||
If obj is ``None``, should return ``True`` or ``False`` to indicate whether
|
otherwise. If obj is ``None``, should return ``True`` or ``False`` to
|
||||||
viewing of objects of this type is permitted in general (e.g., ``False``
|
indicate whether viewing of objects of this type is permitted in general
|
||||||
will be interpreted as meaning that the current user is not permitted to
|
(e.g., ``False`` will be interpreted as meaning that the current user is
|
||||||
view any object of this type).
|
not permitted to view any object of this type).
|
||||||
|
|
||||||
The default implementation returns ``True`` if the user has either the
|
The default implementation returns ``True`` if the user has either the
|
||||||
"change" or "view" permission.
|
"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
|
:attr:`~django.db.models.Options.verbose_name_plural` to the number of
|
||||||
objects that will be deleted.
|
objects that will be deleted.
|
||||||
|
|
||||||
``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s
|
``perms_needed`` is a set of
|
||||||
of the models that the user doesn't have permission to delete.
|
: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
|
``protected`` is a list of strings representing of all the protected
|
||||||
related objects that can't be deleted. The list is displayed in the
|
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
|
``Product``, add/change views you can use
|
||||||
:class:`~django.contrib.contenttypes.admin.GenericTabularInline`
|
:class:`~django.contrib.contenttypes.admin.GenericTabularInline`
|
||||||
or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both
|
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
|
provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular
|
||||||
and stacked visual layouts for the forms representing the inline objects,
|
and stacked visual layouts for the forms representing the inline objects,
|
||||||
respectively, just like their non-generic counterparts. They behave just like
|
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.
|
going to run your app on a case-sensitive filesystem.
|
||||||
|
|
||||||
To override an admin template for a specific app, copy and edit the template
|
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
|
from the :source:`django/contrib/admin/templates/admin` directory, and save it
|
||||||
of the directories you just created.
|
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
|
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
|
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`.
|
:source:`django/contrib/admin/static/admin/css/base.css`.
|
||||||
|
|
||||||
Dark mode variables, respecting the `prefers-color-scheme`_ media query, are
|
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
|
defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This
|
||||||
linked to the document in ``{% block dark-mode-vars %}``.
|
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
|
.. _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
|
.. 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
|
.. 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_title``: :attr:`AdminSite.site_title`
|
||||||
* ``site_url``: :attr:`AdminSite.site_url`
|
* ``site_url``: :attr:`AdminSite.site_url`
|
||||||
* ``has_permission``: :meth:`AdminSite.has_permission`
|
* ``has_permission``: :meth:`AdminSite.has_permission`
|
||||||
* ``available_apps``: a list of applications from the :doc:`application registry
|
* ``available_apps``: a list of applications from the :doc:`application
|
||||||
</ref/applications/>` available for the current user. Each entry in the
|
registry </ref/applications/>` available for the current user. Each entry
|
||||||
list is a dict representing an application with the following keys:
|
in the list is a dict representing an application with the following
|
||||||
|
keys:
|
||||||
|
|
||||||
* ``app_label``: the application label
|
* ``app_label``: the application label
|
||||||
* ``app_url``: the URL of the application index in the admin
|
* ``app_url``: the URL of the application index in the admin
|
||||||
* ``has_module_perms``: a boolean indicating if displaying and accessing of
|
* ``has_module_perms``: a boolean indicating if displaying and accessing
|
||||||
the module's index page is permitted for the current user
|
of the module's index page is permitted for the current user
|
||||||
* ``models``: a list of the models available in the application
|
* ``models``: a list of the models available in the application
|
||||||
|
|
||||||
Each model is a dict with the following keys:
|
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)
|
.. method:: AdminSite.get_model_admin(model)
|
||||||
|
|
||||||
Returns an admin class for the given model class. Raises
|
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)
|
.. 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
|
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
|
example, the message contains a list of the edited fields. The Django admin
|
||||||
site formats this content as a JSON structure, so that
|
site formats this content as a JSON structure, so that
|
||||||
:meth:`get_change_message` can recompose a message translated in the current
|
:meth:`get_change_message` can recompose a message translated in the
|
||||||
user language. Custom code might set this as a plain string though. You are
|
current user language. Custom code might set this as a plain string though.
|
||||||
advised to use the :meth:`get_change_message` method to retrieve this value
|
You are advised to use the :meth:`get_change_message` method to retrieve
|
||||||
instead of accessing it directly.
|
this value instead of accessing it directly.
|
||||||
|
|
||||||
``LogEntry`` methods
|
``LogEntry`` methods
|
||||||
--------------------
|
--------------------
|
||||||
|
@ -61,7 +61,8 @@ Fields
|
|||||||
|
|
||||||
.. attribute:: user_permissions
|
.. 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
|
.. attribute:: is_staff
|
||||||
|
|
||||||
@ -79,8 +80,8 @@ Fields
|
|||||||
flag but the default backend
|
flag but the default backend
|
||||||
(:class:`~django.contrib.auth.backends.ModelBackend`) and the
|
(:class:`~django.contrib.auth.backends.ModelBackend`) and the
|
||||||
:class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can
|
:class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can
|
||||||
use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`
|
use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend` or
|
||||||
or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
|
:class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`
|
||||||
if you want to allow inactive users to login. In this case, you'll also
|
if you want to allow inactive users to login. In this case, you'll also
|
||||||
want to customize the
|
want to customize the
|
||||||
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
|
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
|
||||||
@ -124,9 +125,9 @@ Attributes
|
|||||||
.. attribute:: is_anonymous
|
.. attribute:: is_anonymous
|
||||||
|
|
||||||
Read-only attribute which is always ``False``. This is a way of
|
Read-only attribute which is always ``False``. This is a way of
|
||||||
differentiating :class:`~models.User` and :class:`~models.AnonymousUser`
|
differentiating :class:`~models.User` and
|
||||||
objects. Generally, you should prefer using
|
:class:`~models.AnonymousUser` objects. Generally, you should prefer
|
||||||
:attr:`~django.contrib.auth.models.User.is_authenticated` to this
|
using :attr:`~django.contrib.auth.models.User.is_authenticated` to this
|
||||||
attribute.
|
attribute.
|
||||||
|
|
||||||
Methods
|
Methods
|
||||||
@ -246,8 +247,8 @@ Methods
|
|||||||
|
|
||||||
Returns ``True`` if the user has the specified permission, where perm
|
Returns ``True`` if the user has the specified permission, where perm
|
||||||
is in the format ``"<app label>.<permission codename>"``. (see
|
is in the format ``"<app label>.<permission codename>"``. (see
|
||||||
documentation on :ref:`permissions <topic-authorization>`). If the user is
|
documentation on :ref:`permissions <topic-authorization>`). If the user
|
||||||
inactive, this method will always return ``False``. For an active
|
is inactive, this method will always return ``False``. For an active
|
||||||
superuser, this method will always return ``True``.
|
superuser, this method will always return ``True``.
|
||||||
|
|
||||||
If ``obj`` is passed in, this method won't check for a permission for
|
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
|
allow setting arbitrary fields on a :ref:`custom user model
|
||||||
<auth-custom-user>`.
|
<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
|
.. 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.
|
The name of the module used for authentication.
|
||||||
|
|
||||||
``credentials``
|
``credentials``
|
||||||
A dictionary of keyword arguments containing the user credentials that were
|
A dictionary of keyword arguments containing the user credentials that
|
||||||
passed to :func:`~django.contrib.auth.authenticate` or your own custom
|
were passed to :func:`~django.contrib.auth.authenticate` or your own
|
||||||
authentication backend. Credentials matching a set of 'sensitive' patterns,
|
custom authentication backend. Credentials matching a set of
|
||||||
(including password) will not be sent in the clear as part of the signal.
|
'sensitive' patterns (including password) will not be sent in the clear
|
||||||
|
as part of the signal.
|
||||||
|
|
||||||
``request``
|
``request``
|
||||||
The :class:`~django.http.HttpRequest` object, if one was provided to
|
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.User` and
|
||||||
:class:`~django.contrib.auth.models.PermissionsMixin`.
|
:class:`~django.contrib.auth.models.PermissionsMixin`.
|
||||||
|
|
||||||
:meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`,
|
:meth:`has_perm`, :meth:`get_all_permissions`,
|
||||||
and :meth:`get_group_permissions` allow an object to be passed as a
|
:meth:`get_user_permissions`, and :meth:`get_group_permissions` allow an
|
||||||
parameter for object-specific permissions, but this backend does not
|
object to be passed as a parameter for object-specific permissions, but
|
||||||
implement them other than returning an empty set of permissions if
|
this backend does not implement them other than returning an empty set of
|
||||||
``obj is not None``.
|
permissions if ``obj is not None``.
|
||||||
|
|
||||||
:meth:`with_perm` also allows an object to be passed as a parameter, but
|
: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``.
|
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()``
|
*Asynchronous version*: ``aget_all_permissions()``
|
||||||
|
|
||||||
Returns the set of permission strings the ``user_obj`` has, including both
|
Returns the set of permission strings the ``user_obj`` has, including
|
||||||
user permissions and group permissions. Returns an empty set if
|
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.AbstractBaseUser.is_anonymous` or
|
||||||
:attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.
|
: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
|
.. class:: AllowAllUsersModelBackend
|
||||||
|
|
||||||
Same as :class:`ModelBackend` except that it doesn't reject inactive users
|
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
|
When using this backend, you'll likely want to customize the
|
||||||
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
|
:class:`~django.contrib.auth.forms.AuthenticationForm` used by the
|
||||||
|
@ -188,8 +188,8 @@ The ``ContentTypeManager``
|
|||||||
|
|
||||||
.. method:: get_for_id(id)
|
.. method:: get_for_id(id)
|
||||||
|
|
||||||
Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.
|
Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by
|
||||||
Since this method uses the same shared cache as
|
ID. Since this method uses the same shared cache as
|
||||||
:meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
|
:meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
|
||||||
it's preferred to use this method over the usual
|
it's preferred to use this method over the usual
|
||||||
``ContentType.objects.get(pk=id)``
|
``ContentType.objects.get(pk=id)``
|
||||||
@ -338,10 +338,11 @@ model:
|
|||||||
.. admonition:: Serializing references to ``ContentType`` objects
|
.. admonition:: Serializing references to ``ContentType`` objects
|
||||||
|
|
||||||
If you're serializing data (for example, when generating
|
If you're serializing data (for example, when generating
|
||||||
:class:`~django.test.TransactionTestCase.fixtures`) from a model that implements
|
:class:`~django.test.TransactionTestCase.fixtures`) from a model that
|
||||||
generic relations, you should probably be using a natural key to uniquely
|
implements generic relations, you should probably be using a natural key to
|
||||||
identify related :class:`~django.contrib.contenttypes.models.ContentType`
|
uniquely identify related
|
||||||
objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
|
:class:`~django.contrib.contenttypes.models.ContentType` objects. See
|
||||||
|
:ref:`natural keys<topics-serialization-natural-keys>` and
|
||||||
:option:`dumpdata --natural-foreign` for more information.
|
:option:`dumpdata --natural-foreign` for more information.
|
||||||
|
|
||||||
This will enable an API similar to the one used for a normal
|
This will enable an API similar to the one used for a normal
|
||||||
|
@ -3,7 +3,8 @@ The flatpages app
|
|||||||
=================
|
=================
|
||||||
|
|
||||||
.. module:: django.contrib.flatpages
|
.. 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"
|
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
|
HTML content in a database and handles the management for you via Django's
|
||||||
|
@ -68,7 +68,8 @@ of using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.
|
|||||||
|
|
||||||
.. django-admin-option:: --no-imports
|
.. 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
|
.. django-admin-option:: --null NULL
|
||||||
|
|
||||||
|
@ -45,7 +45,8 @@ model):
|
|||||||
>>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
|
>>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
|
||||||
>>> z.save()
|
>>> 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
|
.. code-block:: pycon
|
||||||
|
|
||||||
@ -72,8 +73,8 @@ transform procedure:
|
|||||||
... ) # printing the last SQL statement executed (requires DEBUG=True)
|
... ) # printing the last SQL statement executed (requires DEBUG=True)
|
||||||
INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
|
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
|
Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object,
|
||||||
(Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
|
WKT (Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in
|
||||||
hexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the
|
hexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the
|
||||||
input is not a ``GEOSGeometry`` object, the geometry field will attempt to
|
input is not a ``GEOSGeometry`` object, the geometry field will attempt to
|
||||||
create a ``GEOSGeometry`` instance from the input.
|
create a ``GEOSGeometry`` instance from the input.
|
||||||
@ -169,10 +170,10 @@ For example:
|
|||||||
>>> qs = Zipcode.objects.filter(poly__contains=pnt)
|
>>> qs = Zipcode.objects.filter(poly__contains=pnt)
|
||||||
>>> qs = Elevation.objects.filter(poly__contains=rst)
|
>>> qs = Elevation.objects.filter(poly__contains=rst)
|
||||||
|
|
||||||
In this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`
|
In this case, ``poly`` is the geographic field,
|
||||||
is the spatial lookup type, ``pnt`` is the parameter (which may be a
|
:lookup:`contains <gis-contains>` is the spatial lookup type, ``pnt`` is the
|
||||||
:class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of
|
parameter (which may be a :class:`~django.contrib.gis.geos.GEOSGeometry` object
|
||||||
GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
|
or a string of GeoJSON , WKT, or HEXEWKB), and ``rst`` is a
|
||||||
:class:`~django.contrib.gis.gdal.GDALRaster` object.
|
:class:`~django.contrib.gis.gdal.GDALRaster` object.
|
||||||
|
|
||||||
.. _spatial-lookup-raster:
|
.. _spatial-lookup-raster:
|
||||||
@ -181,9 +182,9 @@ Raster Lookups
|
|||||||
--------------
|
--------------
|
||||||
|
|
||||||
The raster lookup syntax is similar to the syntax for geometries. The only
|
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
|
difference is that a band index can be specified as additional input. If no
|
||||||
index is specified, the first band is used by default (index ``0``). In that
|
band index is specified, the first band is used by default (index ``0``). In
|
||||||
case the syntax is identical to the syntax for geometry lookups.
|
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
|
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
|
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
|
: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.
|
``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
|
While all spatial lookups can be used with raster objects on both sides, not
|
||||||
underlying operators natively accept raster input. For cases where the operator
|
all underlying operators natively accept raster input. For cases where the
|
||||||
expects geometry input, the raster is automatically converted to a geometry.
|
operator expects geometry input, the raster is automatically converted to a
|
||||||
It's important to keep this in mind when interpreting the lookup results.
|
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
|
The type of raster support is listed for all lookups in the :ref:`compatibility
|
||||||
table <spatial-lookup-compatibility>`. Lookups involving rasters are currently
|
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:
|
Distance lookups take a tuple parameter comprising:
|
||||||
|
|
||||||
#. A geometry or raster to base calculations from; and
|
#. 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,
|
If a :class:`~django.contrib.gis.measure.Distance` object is used,
|
||||||
it may be expressed in any units (the SQL generated will use units
|
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::
|
.. note::
|
||||||
|
|
||||||
In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
|
In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types
|
||||||
geographic distance queries are performed with. [#fndistsphere15]_ However,
|
geographic distance queries are performed with. [#fndistsphere15]_
|
||||||
these queries may take a long time, as great-circle distances must be
|
However, these queries may take a long time, as great-circle distances must
|
||||||
calculated on the fly for *every* row in the query. This is because the
|
be calculated on the fly for *every* row in the query. This is because the
|
||||||
spatial index on traditional geometry fields cannot be used.
|
spatial index on traditional geometry fields cannot be used.
|
||||||
|
|
||||||
For much better performance on WGS84 distance queries, consider using
|
For much better performance on WGS84 distance queries, consider using
|
||||||
:ref:`geography columns <geography-type>` in your database instead because
|
:ref:`geography columns <geography-type>` in your database instead because
|
||||||
they are able to use their spatial index in distance queries.
|
they are able to use their spatial index in distance queries.
|
||||||
You can tell GeoDjango to use a geography column by setting ``geography=True``
|
You can tell GeoDjango to use a geography column by setting
|
||||||
in your field definition.
|
``geography=True`` in your field definition.
|
||||||
|
|
||||||
For example, let's say we have a ``SouthTexasCity`` model (from the
|
For example, let's say we have a ``SouthTexasCity`` model (from the
|
||||||
:source:`GeoDjango distance tests <tests/gis_tests/distapp/models.py>` ) on a
|
:source:`GeoDjango distance tests <tests/gis_tests/distapp/models.py>` ) on a
|
||||||
|
@ -5,10 +5,10 @@ Geographic Feeds
|
|||||||
.. module:: django.contrib.gis.feeds
|
.. module:: django.contrib.gis.feeds
|
||||||
:synopsis: GeoDjango's framework for generating spatial feeds.
|
:synopsis: GeoDjango's framework for generating spatial feeds.
|
||||||
|
|
||||||
GeoDjango has its own :class:`Feed` subclass that may embed location information
|
GeoDjango has its own :class:`Feed` subclass that may embed location
|
||||||
in RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or
|
information in RSS/Atom feeds formatted according to either the `Simple
|
||||||
`W3C Geo`_ standards. Because GeoDjango's syndication API is a superset of
|
GeoRSS`__ or `W3C Geo`_ standards. Because GeoDjango's syndication API is a
|
||||||
Django's, please consult :doc:`Django's syndication documentation
|
superset of Django's, please consult :doc:`Django's syndication documentation
|
||||||
</ref/contrib/syndication>` for details on general usage.
|
</ref/contrib/syndication>` for details on general usage.
|
||||||
|
|
||||||
.. _W3C Geo: https://www.w3.org/2003/01/geo/
|
.. _W3C Geo: https://www.w3.org/2003/01/geo/
|
||||||
|
@ -5,8 +5,8 @@ GeoDjango Forms API
|
|||||||
.. module:: django.contrib.gis.forms
|
.. module:: django.contrib.gis.forms
|
||||||
:synopsis: GeoDjango forms API.
|
:synopsis: GeoDjango forms API.
|
||||||
|
|
||||||
GeoDjango provides some specialized form fields and widgets in order to visually
|
GeoDjango provides some specialized form fields and widgets in order to
|
||||||
display and edit geolocalized data on a map. By default, they use
|
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`_-powered maps, with a base WMS layer provided by `NASA`_.
|
||||||
|
|
||||||
.. _OpenLayers: https://openlayers.org/
|
.. _OpenLayers: https://openlayers.org/
|
||||||
|
@ -29,7 +29,7 @@ Measurements
|
|||||||
.. class:: Area(expression, **extra)
|
.. class:: Area(expression, **extra)
|
||||||
|
|
||||||
*Availability*: MariaDB, `MySQL
|
*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
|
Oracle, `PostGIS <https://postgis.net/docs/ST_Area.html>`__, SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns the area of the
|
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
|
`PostGIS <https://postgis.net/docs/ST_Distance.html>`__, Oracle, SpatiaLite
|
||||||
|
|
||||||
Accepts two geographic fields or expressions and returns the distance between
|
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
|
them, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a
|
||||||
float value is returned when the coordinates are geodetic.
|
raw float value is returned when the coordinates are geodetic.
|
||||||
|
|
||||||
On backends that support distance calculation on geodetic coordinates, the
|
On backends that support distance calculation on geodetic coordinates, the
|
||||||
proper backend function is automatically chosen depending on the SRID value of
|
proper backend function is automatically chosen depending on the SRID value of
|
||||||
@ -81,18 +81,19 @@ queryset is calculated:
|
|||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
Because the ``distance`` attribute is a
|
Because the ``distance`` attribute is a
|
||||||
:class:`~django.contrib.gis.measure.Distance` object, you can easily express
|
:class:`~django.contrib.gis.measure.Distance` object, you can easily
|
||||||
the value in the units of your choice. For example, ``city.distance.mi`` is
|
express the value in the units of your choice. For example,
|
||||||
the distance value in miles and ``city.distance.km`` is the distance value
|
``city.distance.mi`` is the distance value in miles and
|
||||||
in kilometers. See :doc:`measure` for usage details and the list of
|
``city.distance.km`` is the distance value in kilometers. See
|
||||||
:ref:`supported_units`.
|
:doc:`measure` for usage details and the list of :ref:`supported_units`.
|
||||||
|
|
||||||
``GeometryDistance``
|
``GeometryDistance``
|
||||||
--------------------
|
--------------------
|
||||||
|
|
||||||
.. class:: GeometryDistance(expr1, expr2, **extra)
|
.. 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
|
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,
|
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>`__,
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_Perimeter.html>`__,
|
||||||
Oracle, SpatiaLite
|
Oracle, SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns the perimeter of the
|
Accepts a single geographic field or expression and returns the perimeter of
|
||||||
geometry field as a :class:`~django.contrib.gis.measure.Distance` object.
|
the geometry field as a :class:`~django.contrib.gis.measure.Distance` object.
|
||||||
|
|
||||||
Relationships
|
Relationships
|
||||||
=============
|
=============
|
||||||
@ -150,8 +151,9 @@ south = ``π``; west = ``3π/2``.
|
|||||||
|
|
||||||
.. class:: BoundingCircle(expression, num_seg=48, **extra)
|
.. class:: BoundingCircle(expression, num_seg=48, **extra)
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__,
|
*Availability*: `PostGIS
|
||||||
`Oracle <https://docs.oracle.com/en/database/oracle/oracle-database/21/spatl/
|
<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>`_,
|
SDO_GEOM-reference.html#GUID-82A61626-BB64-4793-B53D-A0DBEC91831A>`_,
|
||||||
SpatiaLite 5.1+
|
SpatiaLite 5.1+
|
||||||
|
|
||||||
@ -205,8 +207,8 @@ representing the bounding box of the geometry.
|
|||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_LineLocatePoint.html>`__,
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_LineLocatePoint.html>`__,
|
||||||
SpatiaLite
|
SpatiaLite
|
||||||
|
|
||||||
Returns a float between 0 and 1 representing the location of the closest point on
|
Returns a float between 0 and 1 representing the location of the closest point
|
||||||
``linestring`` to the given ``point``, as a fraction of the 2D line length.
|
on ``linestring`` to the given ``point``, as a fraction of the 2D line length.
|
||||||
|
|
||||||
``PointOnSurface``
|
``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>`__,
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_PointOnSurface.html>`__,
|
||||||
MariaDB, Oracle, SpatiaLite
|
MariaDB, Oracle, SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns a ``Point`` geometry
|
Accepts a single geographic field or expression and returns a ``Point``
|
||||||
guaranteed to lie on the surface of the field; otherwise returns ``None``.
|
geometry guaranteed to lie on the surface of the field; otherwise returns
|
||||||
|
``None``.
|
||||||
|
|
||||||
Operations
|
Operations
|
||||||
==========
|
==========
|
||||||
@ -334,7 +337,8 @@ parameter.
|
|||||||
|
|
||||||
.. class:: Scale(expression, x, y, z=0.0, **extra)
|
.. 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
|
Accepts a single geographic field or expression and returns a geometry with
|
||||||
scaled coordinates by multiplying them with the ``x``, ``y``, and optionally
|
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>`__,
|
*Availability*: Oracle, `PostGIS <https://postgis.net/docs/ST_AsGML.html>`__,
|
||||||
SpatiaLite
|
SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns a `Geographic Markup
|
Accepts a single geographic field or expression and returns a `Geographic
|
||||||
Language (GML)`__ representation of the geometry.
|
Markup Language (GML)`__ representation of the geometry.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
@ -498,7 +502,8 @@ __ https://en.wikipedia.org/wiki/Geography_Markup_Language
|
|||||||
|
|
||||||
.. class:: AsKML(expression, precision=8, **extra)
|
.. 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
|
Accepts a single geographic field or expression and returns a `Keyhole Markup
|
||||||
Language (KML)`__ representation of the geometry.
|
Language (KML)`__ representation of the geometry.
|
||||||
@ -527,7 +532,8 @@ __ https://developers.google.com/kml/documentation/
|
|||||||
|
|
||||||
.. class:: AsSVG(expression, relative=False, precision=8, **extra)
|
.. 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
|
Accepts a single geographic field or expression and returns a `Scalable Vector
|
||||||
Graphics (SVG)`__ representation of the geometry.
|
Graphics (SVG)`__ representation of the geometry.
|
||||||
@ -668,8 +674,8 @@ Accepts a single geographic field or expression and returns the memory size
|
|||||||
SpatiaLite
|
SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns the number of
|
Accepts a single geographic field or expression and returns the number of
|
||||||
geometries if the geometry field is a collection (e.g., a ``GEOMETRYCOLLECTION``
|
geometries if the geometry field is a collection (e.g., a
|
||||||
or ``MULTI*`` field). Returns 1 for single geometries.
|
``GEOMETRYCOLLECTION`` or ``MULTI*`` field). Returns 1 for single geometries.
|
||||||
|
|
||||||
On MySQL, returns ``None`` 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>`__,
|
<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
|
`PostGIS <https://postgis.net/docs/ST_NPoints.html>`__, Oracle, SpatiaLite
|
||||||
|
|
||||||
Accepts a single geographic field or expression and returns the number of points
|
Accepts a single geographic field or expression and returns the number of
|
||||||
in a geometry.
|
points in a geometry.
|
||||||
|
|
||||||
On MySQL, returns ``None`` for any non-``LINESTRING`` geometry.
|
On MySQL, returns ``None`` for any non-``LINESTRING`` geometry.
|
||||||
|
@ -299,11 +299,11 @@ __ https://gdal.org/drivers/vector/
|
|||||||
``Feature`` wraps an OGR feature. You never create a ``Feature`` object
|
``Feature`` wraps an OGR feature. You never create a ``Feature`` object
|
||||||
directly. Instead, you retrieve them from a :class:`Layer` object. Each
|
directly. Instead, you retrieve them from a :class:`Layer` object. Each
|
||||||
feature consists of a geometry and a set of fields containing additional
|
feature consists of a geometry and a set of fields containing additional
|
||||||
properties. The geometry of a field is accessible via its ``geom`` property,
|
properties. The geometry of a field is accessible via its ``geom``
|
||||||
which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a
|
property, which returns an :class:`OGRGeometry` object. A ``Feature``
|
||||||
standard Python container for its fields, which it returns as :class:`Field`
|
behaves like a standard Python container for its fields, which it returns
|
||||||
objects: you can access a field directly by its index or name, or you can
|
as :class:`Field` objects: you can access a field directly by its index or
|
||||||
iterate over a feature's fields, e.g. in a ``for`` loop.
|
name, or you can iterate over a feature's fields, e.g. in a ``for`` loop.
|
||||||
|
|
||||||
.. attribute:: geom
|
.. attribute:: geom
|
||||||
|
|
||||||
@ -537,9 +537,9 @@ coordinate transformation:
|
|||||||
.. method:: __getitem__()
|
.. method:: __getitem__()
|
||||||
|
|
||||||
Returns the point at the specified index for a :class:`LineString`, the
|
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
|
interior ring at the specified index for a :class:`Polygon`, or the
|
||||||
at the specified index in a :class:`GeometryCollection`. Not applicable to
|
geometry at the specified index in a :class:`GeometryCollection`. Not
|
||||||
other geometry types.
|
applicable to other geometry types.
|
||||||
|
|
||||||
.. attribute:: dimension
|
.. attribute:: dimension
|
||||||
|
|
||||||
@ -1273,28 +1273,28 @@ Raster Data Objects
|
|||||||
----------------
|
----------------
|
||||||
|
|
||||||
:class:`GDALRaster` is a wrapper for the GDAL raster source object that
|
:class:`GDALRaster` is a wrapper for the GDAL raster source object that
|
||||||
supports reading data from a variety of GDAL-supported geospatial file
|
supports reading data from a variety of GDAL-supported geospatial file formats
|
||||||
formats and data sources using a consistent interface. Each
|
and data sources using a consistent interface. Each data source is represented
|
||||||
data source is represented by a :class:`GDALRaster` object which contains
|
by a :class:`GDALRaster` object which contains one or more layers of data named
|
||||||
one or more layers of data named bands. Each band, represented by a
|
bands. Each band, represented by a :class:`GDALBand` object, contains
|
||||||
:class:`GDALBand` object, contains georeferenced image data. For example, an RGB
|
georeferenced image data. For example, an RGB image is represented as three
|
||||||
image is represented as three bands: one for red, one for green, and one for
|
bands: one for red, one for green, and one for blue.
|
||||||
blue.
|
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
For raster data there is no difference between a raster instance and its
|
For raster data there is no difference between a raster instance and its
|
||||||
data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
|
data source. Unlike for the Geometry objects, :class:`GDALRaster` objects
|
||||||
always a data source. Temporary rasters can be instantiated in memory
|
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
|
using the corresponding driver, but they will be of the same class as
|
||||||
raster sources.
|
file-based raster sources.
|
||||||
|
|
||||||
.. class:: GDALRaster(ds_input, write=False)
|
.. class:: GDALRaster(ds_input, write=False)
|
||||||
|
|
||||||
The constructor for ``GDALRaster`` accepts two parameters. The first
|
The constructor for ``GDALRaster`` accepts two parameters. The first
|
||||||
parameter defines the raster source, and the second parameter defines if a
|
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
|
raster should be opened in write mode. For newly-created rasters, the
|
||||||
parameter is ignored and the new raster is always created in write mode.
|
second parameter is ignored and the new raster is always created in write
|
||||||
|
mode.
|
||||||
|
|
||||||
The first parameter can take three forms: a string or
|
The first parameter can take three forms: a string or
|
||||||
:class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
|
:class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
|
||||||
@ -1358,8 +1358,8 @@ blue.
|
|||||||
|
|
||||||
.. attribute:: name
|
.. attribute:: name
|
||||||
|
|
||||||
The name of the source which is equivalent to the input file path or the name
|
The name of the source which is equivalent to the input file path or
|
||||||
provided upon instantiation.
|
the name provided upon instantiation.
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
|
|
||||||
@ -1368,11 +1368,12 @@ blue.
|
|||||||
|
|
||||||
.. attribute:: driver
|
.. attribute:: driver
|
||||||
|
|
||||||
The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
|
The name of the GDAL driver used to handle the input file. For
|
||||||
from a file, the driver type is detected automatically. The creation of rasters from
|
``GDALRaster``\s created from a file, the driver type is detected
|
||||||
scratch is an in-memory raster by default (``'MEM'``), but can be
|
automatically. The creation of rasters from scratch is an in-memory
|
||||||
altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
|
raster by default (``'MEM'``), but can be altered as needed. For
|
||||||
For a list of file types, see also the `GDAL Raster Formats`__ list.
|
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/
|
__ https://gdal.org/drivers/raster/
|
||||||
|
|
||||||
@ -1572,10 +1573,11 @@ blue.
|
|||||||
for file-based rasters the warp function will create a new raster on
|
for file-based rasters the warp function will create a new raster on
|
||||||
disk.
|
disk.
|
||||||
|
|
||||||
The only parameter that is set differently from the source raster is the
|
The only parameter that is set differently from the source raster is
|
||||||
name. The default value of the raster name is the name of the source
|
the name. The default value of the raster name is the name of the
|
||||||
raster appended with ``'_copy' + source_driver_name``. For file-based
|
source raster appended with ``'_copy' + source_driver_name``. For
|
||||||
rasters it is recommended to provide the file path of the target raster.
|
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
|
The resampling algorithm used for warping can be specified with the
|
||||||
``resampling`` argument. The default is ``NearestNeighbor``, and the
|
``resampling`` argument. The default is ``NearestNeighbor``, and the
|
||||||
@ -1714,7 +1716,8 @@ blue.
|
|||||||
|
|
||||||
.. attribute:: pixel_count
|
.. 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)
|
.. method:: statistics(refresh=False, approximate=False)
|
||||||
|
|
||||||
@ -1764,8 +1767,8 @@ blue.
|
|||||||
.. attribute:: nodata_value
|
.. attribute:: nodata_value
|
||||||
|
|
||||||
The "no data" value for a band is generally a special marker value used
|
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
|
to mark pixels that are not valid data. Such pixels should generally
|
||||||
be displayed, nor contribute to analysis operations.
|
not be displayed, nor contribute to analysis operations.
|
||||||
|
|
||||||
To delete an existing "no data" value, set this property to ``None``.
|
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.
|
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
|
If ``as_string`` is ``True``, the data type is returned as a string
|
||||||
with the following possible values:
|
with the following possible values: ``GCI_Undefined``,
|
||||||
``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
|
``GCI_GrayIndex``, ``GCI_PaletteIndex``, ``GCI_RedBand``,
|
||||||
``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
|
``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
|
||||||
``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
|
``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
|
||||||
``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
|
``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
|
||||||
``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
|
``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
|
||||||
``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
|
``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
|
||||||
because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
|
because both correspond to the integer 16, but only
|
||||||
is returned as a string.
|
``GCI_YCbCr_CrBand`` is returned as a string.
|
||||||
|
|
||||||
.. method:: data(data=None, offset=None, size=None, shape=None)
|
.. method:: data(data=None, offset=None, size=None, shape=None)
|
||||||
|
|
||||||
The accessor to the pixel values of the ``GDALBand``. Returns the complete
|
The accessor to the pixel values of the ``GDALBand``. Returns the
|
||||||
data array if no parameters are provided. A subset of the pixel array can
|
complete data array if no parameters are provided. A subset of the
|
||||||
be requested by specifying an offset and block size as tuples.
|
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
|
If NumPy is available, the data is returned as NumPy array. For
|
||||||
reasons, it is highly recommended to use NumPy.
|
performance reasons, it is highly recommended to use NumPy.
|
||||||
|
|
||||||
Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
|
Data is written to the ``GDALBand`` if the ``data`` parameter is
|
||||||
The input can be of one of the following types - packed string, buffer, list,
|
provided. The input can be of one of the following types - packed
|
||||||
array, and NumPy array. The number of items in the input should normally
|
string, buffer, list, array, and NumPy array. The number of items in
|
||||||
correspond to the total number of pixels in the band, or to the number
|
the input should normally correspond to the total number of pixels in
|
||||||
of pixels for a specific block of pixel values if the ``offset`` and
|
the band, or to the number of pixels for a specific block of pixel
|
||||||
``size`` parameters are provided.
|
values if the ``offset`` and ``size`` parameters are provided.
|
||||||
|
|
||||||
If the number of items in the input is different from the target pixel
|
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
|
block, the ``shape`` parameter must be specified. The shape is a tuple
|
||||||
@ -1927,8 +1931,8 @@ Key Default Usage
|
|||||||
.. object:: datatype
|
.. object:: datatype
|
||||||
|
|
||||||
Integer representing the data type for all the bands. Defaults to ``6``
|
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.
|
(Float32). All bands of a new raster are required to have the same
|
||||||
The value mapping is:
|
datatype. The value mapping is:
|
||||||
|
|
||||||
===== =============== ===================================
|
===== =============== ===================================
|
||||||
Value GDAL Pixel Type Description
|
Value GDAL Pixel Type Description
|
||||||
|
@ -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
|
<https://postgis.net/docs/RT_ST_Polygon.html>`_ function. See also the
|
||||||
:ref:`introduction to raster lookups <spatial-lookup-raster>`.
|
: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
|
- Native raster support ``N``: the operator accepts rasters natively on both
|
||||||
sides of the lookup, and raster input can be mixed with geometry inputs.
|
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``
|
``bbcontains``
|
||||||
--------------
|
--------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contain.html>`__,
|
*Availability*: `PostGIS
|
||||||
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
|
<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
|
Tests if the geometry or raster field's bounding box completely contains the
|
||||||
lookup geometry's bounding box.
|
lookup geometry's bounding box.
|
||||||
@ -113,8 +115,9 @@ SpatiaLite ``MbrOverlaps(poly, geom)``
|
|||||||
``contained``
|
``contained``
|
||||||
-------------
|
-------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contained.html>`__,
|
*Availability*: `PostGIS
|
||||||
MariaDB, MySQL, SpatiaLite, PGRaster (Native)
|
<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
|
Tests if the geometry field's bounding box is completely contained by the
|
||||||
lookup geometry's bounding box.
|
lookup geometry's bounding box.
|
||||||
@ -161,8 +164,8 @@ SpatiaLite ``Contains(poly, geom)``
|
|||||||
``contains_properly``
|
``contains_properly``
|
||||||
---------------------
|
---------------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_ContainsProperly.html>`__,
|
*Availability*: `PostGIS
|
||||||
PGRaster (Bilateral)
|
<https://postgis.net/docs/ST_ContainsProperly.html>`__, PGRaster (Bilateral)
|
||||||
|
|
||||||
Returns true if the lookup geometry intersects the interior of the
|
Returns true if the lookup geometry intersects the interior of the
|
||||||
geometry field, but not the boundary (or exterior).
|
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>`__,
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_Relate.html>`__,
|
||||||
MariaDB, Oracle, SpatiaLite, PGRaster (Conversion)
|
MariaDB, Oracle, SpatiaLite, PGRaster (Conversion)
|
||||||
|
|
||||||
Tests if the geometry field is spatially related to the lookup geometry by
|
Tests if the geometry field is spatially related to the lookup geometry by the
|
||||||
the values given in the given pattern. This lookup requires a tuple parameter,
|
values given in the given pattern. This lookup requires a tuple parameter,
|
||||||
``(geom, pattern)``; the form of ``pattern`` will depend on the spatial backend:
|
``(geom, pattern)``; the form of ``pattern`` will depend on the spatial
|
||||||
|
backend:
|
||||||
|
|
||||||
MariaDB, PostGIS, and SpatiaLite
|
MariaDB, PostGIS, and SpatiaLite
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
@ -612,11 +616,11 @@ PostGIS equivalent:
|
|||||||
``overlaps_left``
|
``overlaps_left``
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overleft.html>`__,
|
*Availability*: `PostGIS
|
||||||
PGRaster (Bilateral)
|
<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
|
Tests if the geometry field's bounding box overlaps or is to the left of the
|
||||||
geometry's bounding box.
|
lookup geometry's bounding box.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
@ -634,11 +638,11 @@ PostGIS equivalent:
|
|||||||
``overlaps_right``
|
``overlaps_right``
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overright.html>`__,
|
*Availability*: `PostGIS
|
||||||
PGRaster (Bilateral)
|
<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
|
Tests if the geometry field's bounding box overlaps or is to the right of the
|
||||||
geometry's bounding box.
|
lookup geometry's bounding box.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
@ -655,8 +659,8 @@ PostGIS equivalent:
|
|||||||
``overlaps_above``
|
``overlaps_above``
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overabove.html>`__,
|
*Availability*: `PostGIS
|
||||||
PGRaster (Conversion)
|
<https://postgis.net/docs/ST_Geometry_Overabove.html>`__, PGRaster (Conversion)
|
||||||
|
|
||||||
Tests if the geometry field's bounding box overlaps or is above the lookup
|
Tests if the geometry field's bounding box overlaps or is above the lookup
|
||||||
geometry's bounding box.
|
geometry's bounding box.
|
||||||
@ -676,8 +680,8 @@ PostGIS equivalent:
|
|||||||
``overlaps_below``
|
``overlaps_below``
|
||||||
------------------
|
------------------
|
||||||
|
|
||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overbelow.html>`__,
|
*Availability*: `PostGIS
|
||||||
PGRaster (Conversion)
|
<https://postgis.net/docs/ST_Geometry_Overbelow.html>`__, PGRaster (Conversion)
|
||||||
|
|
||||||
Tests if the geometry field's bounding box overlaps or is below the lookup
|
Tests if the geometry field's bounding box overlaps or is below the lookup
|
||||||
geometry's bounding box.
|
geometry's bounding box.
|
||||||
@ -918,11 +922,11 @@ Example:
|
|||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_Collect.html>`__,
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_Collect.html>`__,
|
||||||
MariaDB, MySQL, SpatiaLite
|
MariaDB, MySQL, SpatiaLite
|
||||||
|
|
||||||
Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry
|
Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the
|
||||||
column. This is analogous to a simplified version of the :class:`Union`
|
geometry column. This is analogous to a simplified version of the
|
||||||
aggregate, except it can be several orders of magnitude faster than performing
|
:class:`Union` aggregate, except it can be several orders of magnitude faster
|
||||||
a union because it rolls up geometries into a collection or multi object, not
|
than performing a union because it rolls up geometries into a collection or
|
||||||
caring about dissolving boundaries.
|
multi object, not caring about dissolving boundaries.
|
||||||
|
|
||||||
.. versionchanged:: 6.0
|
.. versionchanged:: 6.0
|
||||||
|
|
||||||
@ -955,8 +959,8 @@ Example:
|
|||||||
*Availability*: `PostGIS <https://postgis.net/docs/ST_3DExtent.html>`__
|
*Availability*: `PostGIS <https://postgis.net/docs/ST_3DExtent.html>`__
|
||||||
|
|
||||||
Returns the 3D extent of all ``geo_field`` in the ``QuerySet`` as a 6-tuple,
|
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,
|
comprising the lower left coordinate and upper right coordinate (each with x,
|
||||||
and z coordinates).
|
y, and z coordinates).
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
|
@ -101,10 +101,10 @@ Finally, there is the :func:`fromfile` factory method which returns a
|
|||||||
|
|
||||||
You find many ``TypeError`` or ``AttributeError`` exceptions filling your
|
You find many ``TypeError`` or ``AttributeError`` exceptions filling your
|
||||||
web server's log files. This generally means that you are creating GEOS
|
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
|
objects at the top level of some of your Python modules. Then, due to a
|
||||||
condition in the garbage collector, your module is garbage collected before
|
race condition in the garbage collector, your module is garbage collected
|
||||||
the GEOS object. To prevent this, create :class:`GEOSGeometry` objects
|
before the GEOS object. To prevent this, create :class:`GEOSGeometry`
|
||||||
inside the local scope of your functions/methods.
|
objects inside the local scope of your functions/methods.
|
||||||
|
|
||||||
Geometries are Pythonic
|
Geometries are Pythonic
|
||||||
-----------------------
|
-----------------------
|
||||||
@ -439,8 +439,8 @@ return a boolean.
|
|||||||
|
|
||||||
.. method:: GEOSGeometry.contains(other)
|
.. method:: GEOSGeometry.contains(other)
|
||||||
|
|
||||||
Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>` returns
|
Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>`
|
||||||
``True``.
|
returns ``True``.
|
||||||
|
|
||||||
.. method:: GEOSGeometry.covers(other)
|
.. method:: GEOSGeometry.covers(other)
|
||||||
|
|
||||||
@ -456,8 +456,8 @@ return a boolean.
|
|||||||
|
|
||||||
This predicate is similar to :meth:`GEOSGeometry.contains`, but is more
|
This predicate is similar to :meth:`GEOSGeometry.contains`, but is more
|
||||||
inclusive (i.e. returns ``True`` for more cases). In particular, unlike
|
inclusive (i.e. returns ``True`` for more cases). In particular, unlike
|
||||||
:meth:`~GEOSGeometry.contains` it does not distinguish between points in the
|
:meth:`~GEOSGeometry.contains` it does not distinguish between points in
|
||||||
boundary and in the interior of geometries. For most situations,
|
the boundary and in the interior of geometries. For most situations,
|
||||||
``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an
|
``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an
|
||||||
added benefit, ``covers()`` is more amenable to optimization and hence
|
added benefit, ``covers()`` is more amenable to optimization and hence
|
||||||
should outperform :meth:`~GEOSGeometry.contains`.
|
should outperform :meth:`~GEOSGeometry.contains`.
|
||||||
@ -507,9 +507,9 @@ return a boolean.
|
|||||||
|
|
||||||
.. method:: GEOSGeometry.relate_pattern(other, pattern)
|
.. method:: GEOSGeometry.relate_pattern(other, pattern)
|
||||||
|
|
||||||
Returns ``True`` if the elements in the DE-9IM intersection matrix
|
Returns ``True`` if the elements in the DE-9IM intersection matrix for this
|
||||||
for this geometry and the other matches the given ``pattern`` --
|
geometry and the other matches the given ``pattern`` -- a string of nine
|
||||||
a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
|
characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
|
||||||
|
|
||||||
.. method:: GEOSGeometry.touches(other)
|
.. method:: GEOSGeometry.touches(other)
|
||||||
|
|
||||||
@ -548,9 +548,9 @@ Topological Methods
|
|||||||
.. method:: GEOSGeometry.interpolate_normalized(distance)
|
.. method:: GEOSGeometry.interpolate_normalized(distance)
|
||||||
|
|
||||||
Given a distance (float), returns the point (or closest point) within the
|
Given a distance (float), returns the point (or closest point) within the
|
||||||
geometry (:class:`LineString` or :class:`MultiLineString`) at that distance.
|
geometry (:class:`LineString` or :class:`MultiLineString`) at that
|
||||||
The normalized version takes the distance as a float between 0 (origin) and
|
distance. The normalized version takes the distance as a float between 0
|
||||||
1 (endpoint).
|
(origin) and 1 (endpoint).
|
||||||
|
|
||||||
Reverse of :meth:`GEOSGeometry.project`.
|
Reverse of :meth:`GEOSGeometry.project`.
|
||||||
|
|
||||||
@ -583,10 +583,10 @@ Topological Methods
|
|||||||
|
|
||||||
By default, this function does not preserve topology. For example,
|
By default, this function does not preserve topology. For example,
|
||||||
:class:`Polygon` objects can be split, be collapsed into lines, or
|
:class:`Polygon` objects can be split, be collapsed into lines, or
|
||||||
disappear. :class:`Polygon` holes can be created or disappear, and lines may
|
disappear. :class:`Polygon` holes can be created or disappear, and lines
|
||||||
cross. By specifying ``preserve_topology=True``, the result will have the
|
may cross. By specifying ``preserve_topology=True``, the result will have
|
||||||
same dimension and number of components as the input; this is significantly
|
the same dimension and number of components as the input; this is
|
||||||
slower, however.
|
significantly slower, however.
|
||||||
|
|
||||||
.. method:: GEOSGeometry.sym_difference(other)
|
.. method:: GEOSGeometry.sym_difference(other)
|
||||||
|
|
||||||
@ -633,13 +633,13 @@ Topological Properties
|
|||||||
|
|
||||||
The result obeys the following contract:
|
The result obeys the following contract:
|
||||||
|
|
||||||
* Unioning a set of :class:`LineString`\s has the effect of fully noding and
|
* Unioning a set of :class:`LineString`\s has the effect of fully noding
|
||||||
dissolving the linework.
|
and dissolving the linework.
|
||||||
|
|
||||||
* Unioning a set of :class:`Polygon`\s will always return a :class:`Polygon`
|
* Unioning a set of :class:`Polygon`\s will always return a
|
||||||
or :class:`MultiPolygon` geometry (unlike :meth:`GEOSGeometry.union`,
|
:class:`Polygon` or :class:`MultiPolygon` geometry (unlike
|
||||||
which may return geometries of lower dimension if a topology collapse
|
:meth:`GEOSGeometry.union`, which may return geometries of lower
|
||||||
occurs).
|
dimension if a topology collapse occurs).
|
||||||
|
|
||||||
Other Properties & Methods
|
Other Properties & Methods
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
@ -655,7 +655,8 @@ Other Properties & Methods
|
|||||||
|
|
||||||
.. method:: GEOSGeometry.clone()
|
.. 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)
|
.. method:: GEOSGeometry.distance(geom)
|
||||||
|
|
||||||
@ -678,8 +679,8 @@ Other Properties & Methods
|
|||||||
|
|
||||||
Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
|
Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
|
||||||
``PreparedGeometry`` objects are optimized for the contains, intersects,
|
``PreparedGeometry`` objects are optimized for the contains, intersects,
|
||||||
covers, crosses, disjoint, overlaps, touches and within operations. Refer to
|
covers, crosses, disjoint, overlaps, touches and within operations. Refer
|
||||||
the :ref:`prepared-geometries` documentation for more information.
|
to the :ref:`prepared-geometries` documentation for more information.
|
||||||
|
|
||||||
.. attribute:: GEOSGeometry.srs
|
.. attribute:: GEOSGeometry.srs
|
||||||
|
|
||||||
@ -810,8 +811,8 @@ Other Properties & Methods
|
|||||||
|
|
||||||
``Polygon`` objects may be instantiated by passing in parameters that
|
``Polygon`` objects may be instantiated by passing in parameters that
|
||||||
represent the rings of the polygon. The parameters must either be
|
represent the rings of the polygon. The parameters must either be
|
||||||
:class:`LinearRing` instances, or a sequence that may be used to construct a
|
:class:`LinearRing` instances, or a sequence that may be used to construct
|
||||||
:class:`LinearRing`:
|
a :class:`LinearRing`:
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
|
|
||||||
@ -973,7 +974,8 @@ Geometry Factories
|
|||||||
|
|
||||||
:param file_h: input file that contains spatial data
|
:param file_h: input file that contains spatial data
|
||||||
:type file_h: a Python ``file`` object or a string path to the file
|
: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:
|
Example:
|
||||||
|
|
||||||
@ -988,7 +990,8 @@ Geometry Factories
|
|||||||
:type string: str
|
:type string: str
|
||||||
:param srid: spatial reference identifier
|
:param srid: spatial reference identifier
|
||||||
:type srid: int
|
: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
|
``fromstr(string, srid)`` is equivalent to
|
||||||
:class:`GEOSGeometry(string, srid) <GEOSGeometry>`.
|
: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)
|
.. class:: WKTWriter(dim=2, trim=False, precision=None)
|
||||||
|
|
||||||
This class allows outputting the WKT representation of a geometry. See the
|
This class allows outputting the WKT representation of a geometry. See the
|
||||||
:attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes for
|
:attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes
|
||||||
details about the constructor arguments.
|
for details about the constructor arguments.
|
||||||
|
|
||||||
.. method:: WKTWriter.write(geom)
|
.. method:: WKTWriter.write(geom)
|
||||||
|
|
||||||
|
@ -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.
|
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
|
The most common solution is to properly configure your :ref:`libsettings` *or*
|
||||||
:ref:`geoslibrarypath` in your settings.
|
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:
|
.. _geoslibrarypath:
|
||||||
|
|
||||||
@ -169,7 +170,8 @@ GEOS C library. For example:
|
|||||||
The setting must be the *full* path to the **C** shared library; in
|
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``.
|
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:
|
.. _proj4:
|
||||||
|
|
||||||
@ -192,8 +194,8 @@ PROJ < 7.x) [#]_:
|
|||||||
|
|
||||||
$ wget https://download.osgeo.org/proj/proj-data-X.Y.tar.gz
|
$ 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
|
Next, untar the source code archive, and extract the datum shifting files in
|
||||||
``data`` subdirectory. This must be done *prior* to configuration:
|
the ``data`` subdirectory. This must be done *prior* to configuration:
|
||||||
|
|
||||||
.. code-block:: shell
|
.. code-block:: shell
|
||||||
|
|
||||||
|
@ -19,11 +19,12 @@ instructions are available for:
|
|||||||
|
|
||||||
.. admonition:: Use the Source
|
.. admonition:: Use the Source
|
||||||
|
|
||||||
Because GeoDjango takes advantage of the latest in the open source geospatial
|
Because GeoDjango takes advantage of the latest in the open source
|
||||||
software technology, recent versions of the libraries are necessary.
|
geospatial software technology, recent versions of the libraries are
|
||||||
If binary packages aren't available for your platform, installation from
|
necessary. If binary packages aren't available for your platform,
|
||||||
source may be required. When compiling the libraries from source, please
|
installation from source may be required. When compiling the libraries from
|
||||||
follow the directions closely, especially if you're a beginner.
|
source, please follow the directions closely, especially if you're a
|
||||||
|
beginner.
|
||||||
|
|
||||||
Requirements
|
Requirements
|
||||||
============
|
============
|
||||||
@ -99,7 +100,8 @@ Add ``django.contrib.gis`` to :setting:`INSTALLED_APPS`
|
|||||||
Like other Django contrib applications, you will *only* need to add
|
Like other Django contrib applications, you will *only* need to add
|
||||||
:mod:`django.contrib.gis` to :setting:`INSTALLED_APPS` in your settings.
|
: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
|
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
|
Troubleshooting
|
||||||
===============
|
===============
|
||||||
@ -145,10 +147,11 @@ could place the following in their bash profile:
|
|||||||
Setting system library path
|
Setting system library path
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include
|
On GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which
|
||||||
additional paths from files in another directory, such as ``/etc/ld.so.conf.d``.
|
may include additional paths from files in another directory, such as
|
||||||
As the root user, add the custom library path (like ``/usr/local/lib``) on a
|
``/etc/ld.so.conf.d``. As the root user, add the custom library path (like
|
||||||
new line in ``ld.so.conf``. This is *one* example of how to do so:
|
``/usr/local/lib``) on a new line in ``ld.so.conf``. This is *one* example of
|
||||||
|
how to do so:
|
||||||
|
|
||||||
.. code-block:: shell
|
.. 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
|
called ``objdump`` (part of the ``binutils`` package) to verify a shared
|
||||||
library on GNU/Linux systems. Thus, if ``binutils`` is not installed on your
|
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
|
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
|
The ``binutils`` package may be installed on Debian and Ubuntu systems using
|
||||||
following command:
|
the following command:
|
||||||
|
|
||||||
.. code-block:: shell
|
.. code-block:: shell
|
||||||
|
|
||||||
@ -279,9 +283,10 @@ __ https://brew.sh/
|
|||||||
Fink
|
Fink
|
||||||
^^^^
|
^^^^
|
||||||
|
|
||||||
`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users
|
`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for
|
||||||
of the `Fink`__ package system. `Different packages are available`__ (starting
|
users of the `Fink`__ package system. `Different packages are available`__
|
||||||
with ``django-gis``), depending on which version of Python you want to use.
|
(starting with ``django-gis``), depending on which version of Python you want
|
||||||
|
to use.
|
||||||
|
|
||||||
__ https://schwehr.blogspot.com/
|
__ https://schwehr.blogspot.com/
|
||||||
__ https://www.finkproject.org/
|
__ https://www.finkproject.org/
|
||||||
|
@ -39,8 +39,8 @@ command line interface and enter the following query:
|
|||||||
|
|
||||||
sqlite> CREATE VIRTUAL TABLE testrtree USING rtree(id,minX,maxX,minY,maxY);
|
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,
|
If you obtain an error, you will have to recompile SQLite from source.
|
||||||
skip this section.
|
Otherwise, skip this section.
|
||||||
|
|
||||||
To install from sources, download the latest amalgamation source archive from
|
To install from sources, download the latest amalgamation source archive from
|
||||||
the `SQLite download page`__, and extract:
|
the `SQLite download page`__, and extract:
|
||||||
@ -51,8 +51,9 @@ the `SQLite download page`__, and extract:
|
|||||||
$ unzip sqlite-amalgamation-XXX0000.zip
|
$ unzip sqlite-amalgamation-XXX0000.zip
|
||||||
$ cd sqlite-amalgamation-XXX0000
|
$ cd sqlite-amalgamation-XXX0000
|
||||||
|
|
||||||
Next, run the ``configure`` script -- however the ``CFLAGS`` environment variable
|
Next, run the ``configure`` script -- however the ``CFLAGS`` environment
|
||||||
needs to be customized so that SQLite knows to build the R*Tree module:
|
variable needs to be customized so that SQLite knows to build the R*Tree
|
||||||
|
module:
|
||||||
|
|
||||||
.. code-block:: shell
|
.. code-block:: shell
|
||||||
|
|
||||||
|
@ -21,12 +21,12 @@ then inserting into a GeoDjango model.
|
|||||||
|
|
||||||
.. warning ::
|
.. warning ::
|
||||||
|
|
||||||
GIS data sources, like shapefiles, may be very large. If you find
|
GIS data sources, like shapefiles, may be very large. If you find that
|
||||||
that :class:`LayerMapping` is using too much memory, set
|
:class:`LayerMapping` is using too much memory, set :setting:`DEBUG` to
|
||||||
:setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG`
|
``False`` in your settings. When :setting:`DEBUG` is set to ``True``,
|
||||||
is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>`
|
Django :ref:`automatically logs <faq-see-raw-sql-queries>` *every* SQL
|
||||||
*every* SQL query -- and when SQL statements contain geometries, this may
|
query -- and when SQL statements contain geometries, this may consume more
|
||||||
consume more memory than is typical.
|
memory than is typical.
|
||||||
|
|
||||||
Example
|
Example
|
||||||
=======
|
=======
|
||||||
@ -52,7 +52,8 @@ Example
|
|||||||
PRIMEM["Greenwich",0],
|
PRIMEM["Greenwich",0],
|
||||||
UNIT["Degree",0.017453292519943295]]
|
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
|
from django.contrib.gis.db import models
|
||||||
|
|
||||||
|
@ -206,6 +206,7 @@ Measurement API
|
|||||||
Alias for :class:`Area` class.
|
Alias for :class:`Area` class.
|
||||||
|
|
||||||
.. rubric:: Footnotes
|
.. rubric:: Footnotes
|
||||||
.. [#] `Robert Coup <https://koordinates.com/>`_ is the initial author of the measure objects,
|
.. [#] `Robert Coup <https://koordinates.com/>`_ is the initial author of the
|
||||||
and was inspired by Brian Beck's work in `geopy <https://github.com/geopy/geopy/>`_
|
measure objects, and was inspired by Brian Beck's work in `geopy
|
||||||
and Geoff Biggs' PhD work on dimensioned units for robotics.
|
<https://github.com/geopy/geopy/>`_ and Geoff Biggs' PhD work on
|
||||||
|
dimensioned units for robotics.
|
||||||
|
@ -108,9 +108,9 @@ All are optional.
|
|||||||
|
|
||||||
.. attribute:: BaseSpatialField.srid
|
.. attribute:: BaseSpatialField.srid
|
||||||
|
|
||||||
Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry field to
|
Sets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry
|
||||||
the given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees
|
field to the given value. Defaults to 4326 (also known as `WGS84`__, units are
|
||||||
of longitude and latitude).
|
in degrees of longitude and latitude).
|
||||||
|
|
||||||
__ https://en.wikipedia.org/wiki/WGS84
|
__ 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
|
Choosing an appropriate SRID for your model is an important decision that the
|
||||||
developer should consider carefully. The SRID is an integer specifier that
|
developer should consider carefully. The SRID is an integer specifier that
|
||||||
corresponds to the projection system that will be used to interpret the data
|
corresponds to the projection system that will be used to interpret the data in
|
||||||
in the spatial database. [#fnsrid]_ Projection systems give the context to the
|
the spatial database. [#fnsrid]_ Projection systems give the context to the
|
||||||
coordinates that specify a location. Although the details of `geodesy`__ are
|
coordinates that specify a location. Although the details of `geodesy`__ are
|
||||||
beyond the scope of this documentation, the general problem is that the earth
|
beyond the scope of this documentation, the general problem is that the earth
|
||||||
is spherical and representations of the earth (e.g., paper maps, web maps)
|
is spherical and representations of the earth (e.g., paper maps, web maps) are
|
||||||
are not.
|
not.
|
||||||
|
|
||||||
Most people are familiar with using latitude and longitude to reference a
|
Most people are familiar with using latitude and longitude to reference a
|
||||||
location on the earth's surface. However, latitude and longitude are angles,
|
location on the earth's surface. However, latitude and longitude are angles,
|
||||||
@ -263,7 +263,7 @@ geography column to a geometry type in the query::
|
|||||||
|
|
||||||
For more information, the PostGIS documentation contains a helpful section on
|
For more information, the PostGIS documentation contains a helpful section on
|
||||||
determining `when to use geography data type over geometry data type
|
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
|
.. rubric:: Footnotes
|
||||||
.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.
|
.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.ogc.org/standard/sfs/>`_.
|
||||||
|
@ -13,8 +13,8 @@ __ https://geojson.org/
|
|||||||
The ``geojson`` serializer is not meant for round-tripping data, as it has no
|
The ``geojson`` serializer is not meant for round-tripping data, as it has no
|
||||||
deserializer equivalent. For example, you cannot use :djadmin:`loaddata` to
|
deserializer equivalent. For example, you cannot use :djadmin:`loaddata` to
|
||||||
reload the output produced by this serializer. If you plan to reload the
|
reload the output produced by this serializer. If you plan to reload the
|
||||||
outputted data, use the plain :ref:`json serializer <serialization-formats-json>`
|
outputted data, use the plain :ref:`json serializer
|
||||||
instead.
|
<serialization-formats-json>` instead.
|
||||||
|
|
||||||
In addition to the options of the ``json`` serializer, the ``geojson``
|
In addition to the options of the ``json`` serializer, the ``geojson``
|
||||||
serializer accepts the following additional option when it is called by
|
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
|
* ``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
|
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
|
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``
|
* ``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.
|
key of the GeoJSON feature. By default, the primary key of objects is used.
|
||||||
|
@ -15,7 +15,8 @@ Settings
|
|||||||
|
|
||||||
.. note::
|
.. 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
|
.. setting:: POSTGIS_VERSION
|
||||||
|
|
||||||
|
@ -6,8 +6,8 @@ Introduction
|
|||||||
============
|
============
|
||||||
|
|
||||||
GeoDjango is an included contrib module for Django that turns it into a
|
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
|
world-class geographic web framework. GeoDjango strives to make it as simple as
|
||||||
as possible to create geographic web applications, like location-based services.
|
possible to create geographic web applications, like location-based services.
|
||||||
Its features include:
|
Its features include:
|
||||||
|
|
||||||
* Django model fields for `OGC`_ geometries and raster data.
|
* 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 --
|
There are many different ways to import data into a spatial database --
|
||||||
besides the tools included within GeoDjango, you may also use the following:
|
besides the tools included within GeoDjango, you may also use the following:
|
||||||
|
|
||||||
* `ogr2ogr`_: A command-line utility included with GDAL that
|
* `ogr2ogr`_: A command-line utility included with GDAL that can import many
|
||||||
can import many vector data formats into PostGIS, MySQL, and Oracle databases.
|
vector data formats into PostGIS, MySQL, and Oracle databases.
|
||||||
* `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into
|
* `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into
|
||||||
PostGIS.
|
PostGIS.
|
||||||
|
|
||||||
@ -375,12 +375,12 @@ You can see the layer's geometry type and how many features it contains:
|
|||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
Unfortunately, the shapefile data format does not allow for greater
|
Unfortunately, the shapefile data format does not allow for greater
|
||||||
specificity with regards to geometry types. This shapefile, like
|
specificity with regards to geometry types. This shapefile, like many
|
||||||
many others, actually includes ``MultiPolygon`` geometries, not Polygons.
|
others, actually includes ``MultiPolygon`` geometries, not Polygons. It's
|
||||||
It's important to use a more general field type in models: a
|
important to use a more general field type in models: a GeoDjango
|
||||||
GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
|
``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
|
||||||
``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This
|
``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This is
|
||||||
is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
|
why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
|
||||||
|
|
||||||
The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference
|
The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference
|
||||||
system associated with it. If it does, the ``srs`` attribute will return a
|
system associated with it. If it does, the ``srs`` attribute will return a
|
||||||
@ -412,18 +412,22 @@ units of degrees.
|
|||||||
In addition, shapefiles also support attribute fields that may contain
|
In addition, shapefiles also support attribute fields that may contain
|
||||||
additional data. Here are the fields on the World Borders layer:
|
additional data. Here are the fields on the World Borders layer:
|
||||||
|
|
||||||
|
.. code-block:: pycon
|
||||||
|
|
||||||
>>> print(lyr.fields)
|
>>> print(lyr.fields)
|
||||||
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
|
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
|
||||||
|
|
||||||
The following code will let you examine the OGR types (e.g. integer or
|
The following code will let you examine the OGR types (e.g. integer or
|
||||||
string) associated with each of the fields:
|
string) associated with each of the fields:
|
||||||
|
|
||||||
|
.. code-block:: pycon
|
||||||
|
|
||||||
>>> [fld.__name__ for fld in lyr.field_types]
|
>>> [fld.__name__ for fld in lyr.field_types]
|
||||||
['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger64', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']
|
['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
|
You can iterate over each feature in the layer and extract information from
|
||||||
the feature's geometry (accessed via the ``geom`` attribute) as well as the
|
both the feature's geometry (accessed via the ``geom`` attribute) as well as
|
||||||
feature's attribute fields (whose **values** are accessed via ``get()``
|
the feature's attribute fields (whose **values** are accessed via ``get()``
|
||||||
method):
|
method):
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
@ -769,7 +773,8 @@ application with the following code::
|
|||||||
|
|
||||||
admin.site.register(WorldBorder, admin.ModelAdmin)
|
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.contrib import admin
|
||||||
from django.urls import include, path
|
from django.urls import include, path
|
||||||
|
@ -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
|
<tut-batteries-included>`. It ships with a variety of extra, optional tools
|
||||||
that solve common web development problems.
|
that solve common web development problems.
|
||||||
|
|
||||||
This code lives in :source:`django/contrib` in the Django distribution. This document
|
This code lives in :source:`django/contrib` in the Django distribution. This
|
||||||
gives a rundown of the packages in ``contrib``, along with any dependencies
|
document gives a rundown of the packages in ``contrib``, along with any
|
||||||
those packages have.
|
dependencies those packages have.
|
||||||
|
|
||||||
.. admonition:: Including ``contrib`` packages in ``INSTALLED_APPS``
|
.. admonition:: Including ``contrib`` packages in ``INSTALLED_APPS``
|
||||||
|
|
||||||
|
@ -104,19 +104,19 @@ templates.
|
|||||||
The built-in levels, which can be imported from ``django.contrib.messages``
|
The built-in levels, which can be imported from ``django.contrib.messages``
|
||||||
directly, are:
|
directly, are:
|
||||||
|
|
||||||
=========== ========
|
=========== =========================================================================================
|
||||||
Constant Purpose
|
Constant Purpose
|
||||||
=========== ========
|
=========== =========================================================================================
|
||||||
``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
|
``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
|
||||||
``INFO`` Informational messages for the user
|
``INFO`` Informational messages for the user
|
||||||
``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
|
``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
|
||||||
``WARNING`` A failure did not occur but may be imminent
|
``WARNING`` A failure did not occur but may be imminent
|
||||||
``ERROR`` An action was **not** successful or some other failure occurred
|
``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
|
The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded
|
||||||
(or it can be `changed per request`_). Attempts to add messages of a level less
|
level (or it can be `changed per request`_). Attempts to add messages of a
|
||||||
than this will be ignored.
|
level less than this will be ignored.
|
||||||
|
|
||||||
.. _`changed per request`: `Changing the minimum recorded level per-request`_
|
.. _`changed per request`: `Changing the minimum recorded level per-request`_
|
||||||
|
|
||||||
|
@ -11,8 +11,8 @@ Indexing these fields
|
|||||||
=====================
|
=====================
|
||||||
|
|
||||||
:class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a
|
: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.
|
B-tree index, which isn't particularly helpful when querying complex data
|
||||||
Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
|
types. Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
|
||||||
:class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though
|
:class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though
|
||||||
the index choice is dependent on the queries that you're using. Generally, GiST
|
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
|
may be a good choice for the :ref:`range fields <range-fields>` and
|
||||||
@ -450,8 +450,8 @@ operator ``?|``. For example:
|
|||||||
``has_keys``
|
``has_keys``
|
||||||
~~~~~~~~~~~~
|
~~~~~~~~~~~~
|
||||||
|
|
||||||
Returns objects where all of the given keys are in the data. Uses the SQL operator
|
Returns objects where all of the given keys are in the data. Uses the SQL
|
||||||
``?&``. For example:
|
operator ``?&``. For example:
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
|
|
||||||
@ -741,8 +741,8 @@ passed range.
|
|||||||
``not_gt``
|
``not_gt``
|
||||||
^^^^^^^^^^
|
^^^^^^^^^^
|
||||||
|
|
||||||
The returned ranges do not contain any points greater than the passed range, that
|
The returned ranges do not contain any points greater than the passed range,
|
||||||
is the upper bound of the returned range is at most the upper bound of the
|
that is the upper bound of the returned range is at most the upper bound of the
|
||||||
passed range.
|
passed range.
|
||||||
|
|
||||||
>>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
|
>>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
|
||||||
|
@ -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
|
``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS` and activate
|
||||||
the `unaccent extension on PostgreSQL`_. The
|
the `unaccent extension on PostgreSQL`_. The
|
||||||
:class:`~django.contrib.postgres.operations.UnaccentExtension` migration
|
: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
|
.. _unaccent extension on PostgreSQL: https://www.postgresql.org/docs/current/unaccent.html
|
||||||
|
|
||||||
@ -105,7 +106,7 @@ The ``unaccent`` lookup can be used on
|
|||||||
|
|
||||||
.. warning::
|
.. warning::
|
||||||
|
|
||||||
``unaccent`` lookups should perform fine in most use cases. However, queries
|
``unaccent`` lookups should perform fine in most use cases. However,
|
||||||
using this filter will generally perform full table scans, which can be slow
|
queries using this filter will generally perform full table scans, which
|
||||||
on large tables. In those cases, using dedicated full text indexing tools
|
can be slow on large tables. In those cases, using dedicated full text
|
||||||
might be appropriate.
|
indexing tools might be appropriate.
|
||||||
|
@ -295,8 +295,7 @@ the search vector you wish to use. For example::
|
|||||||
name="search_vector_idx",
|
name="search_vector_idx",
|
||||||
)
|
)
|
||||||
|
|
||||||
The PostgreSQL documentation has details on
|
The PostgreSQL docs has details on `creating indexes for full text search
|
||||||
`creating indexes for full text search
|
|
||||||
<https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.
|
<https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.
|
||||||
|
|
||||||
``SearchVectorField``
|
``SearchVectorField``
|
||||||
|
@ -16,7 +16,8 @@ To install the redirects app, follow these steps:
|
|||||||
|
|
||||||
#. Ensure that the ``django.contrib.sites`` framework
|
#. Ensure that the ``django.contrib.sites`` framework
|
||||||
:ref:`is installed <enabling-the-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'``
|
#. Add ``'django.contrib.redirects.middleware.RedirectFallbackMiddleware'``
|
||||||
to your :setting:`MIDDLEWARE` setting.
|
to your :setting:`MIDDLEWARE` setting.
|
||||||
#. Run the command :djadmin:`manage.py migrate <migrate>`.
|
#. Run the command :djadmin:`manage.py migrate <migrate>`.
|
||||||
@ -24,8 +25,8 @@ To install the redirects app, follow these steps:
|
|||||||
How it works
|
How it works
|
||||||
============
|
============
|
||||||
|
|
||||||
``manage.py migrate`` creates a ``django_redirect`` table in your database. This
|
``manage.py migrate`` creates a ``django_redirect`` table in your database.
|
||||||
is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
|
This is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
|
||||||
|
|
||||||
The :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
|
The :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
|
||||||
does all of the work. Each time any Django application raises a 404
|
does all of the work. Each time any Django application raises a 404
|
||||||
@ -71,10 +72,11 @@ Via the Python API
|
|||||||
|
|
||||||
.. class:: models.Redirect
|
.. class:: models.Redirect
|
||||||
|
|
||||||
Redirects are represented by a standard :doc:`Django model </topics/db/models>`,
|
Redirects are represented by a standard
|
||||||
which lives in :source:`django/contrib/redirects/models.py`. You can access
|
:doc:`Django model </topics/db/models>`, which lives in
|
||||||
redirect objects via the :doc:`Django database API </topics/db/queries>`.
|
:source:`django/contrib/redirects/models.py`. You can access redirect
|
||||||
For example:
|
objects via the :doc:`Django database API </topics/db/queries>`. For
|
||||||
|
example:
|
||||||
|
|
||||||
.. code-block:: pycon
|
.. code-block:: pycon
|
||||||
|
|
||||||
|
@ -61,12 +61,13 @@ To activate sitemap generation on your Django site, add this line to your
|
|||||||
name="django.contrib.sitemaps.views.sitemap",
|
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
|
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
|
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
|
below. For instance, if :file:`sitemap.xml` lives in your root directory, it
|
||||||
reference any URL in your site. However, if your sitemap lives at
|
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/sitemap.xml`, it may only reference URLs that begin with
|
||||||
:file:`/content/`.
|
: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
|
references individual sitemap files, one per each section defined in your
|
||||||
``sitemaps`` dictionary. The only differences in usage are:
|
``sitemaps`` dictionary. The only differences in usage are:
|
||||||
|
|
||||||
* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
|
* You use two views in your URLconf:
|
||||||
and :func:`django.contrib.sitemaps.views.sitemap`.
|
:func:`django.contrib.sitemaps.views.index` and
|
||||||
|
:func:`django.contrib.sitemaps.views.sitemap`.
|
||||||
* The :func:`django.contrib.sitemaps.views.sitemap` view should take a
|
* The :func:`django.contrib.sitemaps.views.sitemap` view should take a
|
||||||
``section`` keyword argument.
|
``section`` keyword argument.
|
||||||
|
|
||||||
|
@ -160,7 +160,8 @@ it is not.
|
|||||||
If you don't have access to the request object, you can use the
|
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`
|
``get_current()`` method of the :class:`~django.contrib.sites.models.Site`
|
||||||
model's manager. You should then ensure that your settings file does contain
|
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
|
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
|
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
|
``Site.objects.get_current()`` could result in a database query. But Django is
|
||||||
little cleverer than that: on the first request, the current site is cached, and
|
a little cleverer than that: on the first request, the current site is cached,
|
||||||
any subsequent call returns the cached data instead of hitting the database.
|
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
|
If for any reason you want to force a database query, you can tell Django to
|
||||||
clear the cache using ``Site.objects.clear_cache()``::
|
clear the cache using ``Site.objects.clear_cache()``::
|
||||||
@ -344,8 +346,9 @@ your model explicitly. For example::
|
|||||||
on_site = CurrentSiteManager()
|
on_site = CurrentSiteManager()
|
||||||
|
|
||||||
With this model, ``Photo.objects.all()`` will return all ``Photo`` objects in
|
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
|
the database, but ``Photo.on_site.all()`` will return only the ``Photo``
|
||||||
associated with the current site, according to the :setting:`SITE_ID` setting.
|
objects associated with the current site, according to the :setting:`SITE_ID`
|
||||||
|
setting.
|
||||||
|
|
||||||
Put another way, these two statements are equivalent::
|
Put another way, these two statements are equivalent::
|
||||||
|
|
||||||
@ -381,8 +384,9 @@ demonstrates this::
|
|||||||
objects = models.Manager()
|
objects = models.Manager()
|
||||||
on_site = CurrentSiteManager("publish_on")
|
on_site = CurrentSiteManager("publish_on")
|
||||||
|
|
||||||
If you attempt to use :class:`~django.contrib.sites.managers.CurrentSiteManager`
|
If you attempt to use
|
||||||
and pass a field name that doesn't exist, Django will raise a ``ValueError``.
|
: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
|
Finally, note that you'll probably want to keep a normal
|
||||||
(non-site-specific) ``Manager`` on your model, even if you use
|
(non-site-specific) ``Manager`` on your model, even if you use
|
||||||
|
@ -67,12 +67,12 @@ This is used by the
|
|||||||
default.
|
default.
|
||||||
|
|
||||||
By default, collected files receive permissions from
|
By default, collected files receive permissions from
|
||||||
:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive permissions
|
:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive
|
||||||
from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would like different
|
permissions from :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would
|
||||||
permissions for these files and/or directories, you can subclass either of the
|
like different permissions for these files and/or directories, you can subclass
|
||||||
:ref:`static files storage classes <staticfiles-storages>` and specify the
|
either of the :ref:`static files storage classes <staticfiles-storages>` and
|
||||||
``file_permissions_mode`` and/or ``directory_permissions_mode`` parameters,
|
specify the ``file_permissions_mode`` and/or ``directory_permissions_mode``
|
||||||
respectively. For example::
|
parameters, respectively. For example::
|
||||||
|
|
||||||
from django.contrib.staticfiles import storage
|
from django.contrib.staticfiles import storage
|
||||||
|
|
||||||
@ -280,10 +280,11 @@ counterparts and update the cache appropriately.
|
|||||||
|
|
||||||
.. class:: storage.ManifestStaticFilesStorage
|
.. class:: storage.ManifestStaticFilesStorage
|
||||||
|
|
||||||
A subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`
|
A subclass of the
|
||||||
storage backend which stores the file names it handles by appending the MD5
|
:class:`~django.contrib.staticfiles.storage.StaticFilesStorage` storage backend
|
||||||
hash of the file's content to the filename. For example, the file
|
which stores the file names it handles by appending the MD5 hash of the file's
|
||||||
``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.
|
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
|
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
|
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
|
.. 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
|
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,
|
code under test and consuming it with testing tools through HTTP (e.g.
|
||||||
PhantomJS, etc.), because of which it's needed that the static assets are also
|
Selenium, PhantomJS, etc.), because of which it's needed that the static assets
|
||||||
published.
|
are also published.
|
||||||
|
|
||||||
But given the fact that it makes use of the
|
But given the fact that it makes use of the
|
||||||
:func:`django.contrib.staticfiles.views.serve` view described above, it can
|
:func:`django.contrib.staticfiles.views.serve` view described above, it can
|
||||||
|
@ -106,8 +106,8 @@ Note:
|
|||||||
See `Publishing Atom and RSS feeds in tandem`_, later, for an example.
|
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>``,
|
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
|
``<link>`` and ``<description>``. We need to tell the framework what data to
|
||||||
into those elements.
|
put into those elements.
|
||||||
|
|
||||||
* For the contents of ``<title>`` and ``<description>``, Django tries
|
* For the contents of ``<title>`` and ``<description>``, Django tries
|
||||||
calling the methods ``item_title()`` and ``item_description()`` on
|
calling the methods ``item_title()`` and ``item_description()`` on
|
||||||
@ -138,10 +138,10 @@ into those elements.
|
|||||||
|
|
||||||
.. method:: Feed.get_context_data(**kwargs)
|
.. method:: Feed.get_context_data(**kwargs)
|
||||||
|
|
||||||
There is also a way to pass additional information to title and description
|
There is also a way to pass additional information to title and
|
||||||
templates, if you need to supply more than the two variables mentioned
|
description templates, if you need to supply more than the two variables
|
||||||
before. You can provide your implementation of ``get_context_data`` method
|
mentioned before. You can provide your implementation of
|
||||||
in your ``Feed`` subclass. For example::
|
``get_context_data`` method in your ``Feed`` subclass. For example::
|
||||||
|
|
||||||
from mysite.models import Article
|
from mysite.models import Article
|
||||||
from django.contrib.syndication.views import Feed
|
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
|
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
|
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
|
:class:`~django.contrib.syndication.views.Feed` class for each police beat;
|
||||||
would violate the :ref:`DRY principle <dry>` and would couple data to
|
that would violate the :ref:`DRY principle <dry>` and would couple data to
|
||||||
programming logic. Instead, the syndication framework lets you access the
|
programming logic. Instead, the syndication framework lets you access the
|
||||||
arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output
|
arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can
|
||||||
items based on information in the feed's URL.
|
output items based on information in the feed's URL.
|
||||||
|
|
||||||
The police beat feeds could be accessible via URLs like this:
|
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
|
Feeds created by the syndication framework automatically include the
|
||||||
appropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). By
|
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
|
default, this is :func:`django.utils.translation.get_language`. You can change
|
||||||
by setting the ``language`` class attribute.
|
it by setting the ``language`` class attribute.
|
||||||
|
|
||||||
URLs
|
URLs
|
||||||
----
|
----
|
||||||
@ -1033,7 +1033,8 @@ They share this interface:
|
|||||||
* ``categories`` should be a sequence of strings.
|
* ``categories`` should be a sequence of strings.
|
||||||
|
|
||||||
:meth:`.SyndicationFeed.write`
|
: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`
|
:meth:`.SyndicationFeed.writeString`
|
||||||
Returns the feed as a string in the given encoding.
|
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
|
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
|
`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,
|
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
|
and there are a set of methods that ``SyndicationFeed`` calls to get these
|
||||||
attributes. Thus, you can subclass the appropriate feed generator class
|
extra attributes. Thus, you can subclass the appropriate feed generator class
|
||||||
(``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:
|
(``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:
|
||||||
|
|
||||||
.. _georss: https://georss.org
|
.. _georss: https://georss.org
|
||||||
@ -1106,10 +1107,11 @@ attributes. Thus, you can subclass the appropriate feed generator class
|
|||||||
|
|
||||||
.. warning::
|
.. warning::
|
||||||
|
|
||||||
If you override any of these methods, be sure to call the superclass methods
|
If you override any of these methods, be sure to call the superclass
|
||||||
since they add the required elements for each feed format.
|
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):
|
class iTunesFeed(Rss201rev2Feed):
|
||||||
def root_attributes(self):
|
def root_attributes(self):
|
||||||
|
@ -46,7 +46,8 @@ The :class:`~django.middleware.csp.ContentSecurityPolicyMiddleware` is
|
|||||||
configured using the following settings:
|
configured using the following settings:
|
||||||
|
|
||||||
* :setting:`SECURE_CSP`: defines the **enforced Content Security Policy**.
|
* :setting:`SECURE_CSP`: defines the **enforced Content Security Policy**.
|
||||||
* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security Policy**.
|
* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security
|
||||||
|
Policy**.
|
||||||
|
|
||||||
.. admonition:: These settings can be used independently or together
|
.. admonition:: These settings can be used independently or together
|
||||||
|
|
||||||
|
@ -13,9 +13,9 @@ who visits the malicious site in their browser. A related type of attack,
|
|||||||
'login CSRF', where an attacking site tricks a user's browser into logging into
|
'login CSRF', where an attacking site tricks a user's browser into logging into
|
||||||
a site with someone else's credentials, is also covered.
|
a site with someone else's credentials, is also covered.
|
||||||
|
|
||||||
The first defense against CSRF attacks is to ensure that GET requests (and other
|
The first defense against CSRF attacks is to ensure that GET requests (and
|
||||||
'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect free.
|
other 'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect
|
||||||
Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be
|
free. Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be
|
||||||
protected by the steps outlined in :ref:`using-csrf`.
|
protected by the steps outlined in :ref:`using-csrf`.
|
||||||
|
|
||||||
.. _Cross Site Request Forgeries: https://owasp.org/www-community/attacks/csrf#overview
|
.. _Cross Site Request Forgeries: https://owasp.org/www-community/attacks/csrf#overview
|
||||||
@ -120,13 +120,14 @@ vulnerability allows and much worse).
|
|||||||
Limitations
|
Limitations
|
||||||
===========
|
===========
|
||||||
|
|
||||||
Subdomains within a site will be able to set cookies on the client for the whole
|
Subdomains within a site will be able to set cookies on the client for the
|
||||||
domain. By setting the cookie and using a corresponding token, subdomains will
|
whole domain. By setting the cookie and using a corresponding token, subdomains
|
||||||
be able to circumvent the CSRF protection. The only way to avoid this is to
|
will be able to circumvent the CSRF protection. The only way to avoid this is
|
||||||
ensure that subdomains are controlled by trusted users (or, are at least unable
|
to ensure that subdomains are controlled by trusted users (or, are at least
|
||||||
to set cookies). Note that even without CSRF, there are other vulnerabilities,
|
unable to set cookies). Note that even without CSRF, there are other
|
||||||
such as session fixation, that make giving subdomains to untrusted parties a bad
|
vulnerabilities, such as session fixation, that make giving subdomains to
|
||||||
idea, and these vulnerabilities cannot easily be fixed with current browsers.
|
untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed
|
||||||
|
with current browsers.
|
||||||
|
|
||||||
Utilities
|
Utilities
|
||||||
=========
|
=========
|
||||||
|
@ -439,10 +439,10 @@ Django supports MySQL 8.0.11 and higher.
|
|||||||
Django's ``inspectdb`` feature uses the ``information_schema`` database, which
|
Django's ``inspectdb`` feature uses the ``information_schema`` database, which
|
||||||
contains detailed data on all database schemas.
|
contains detailed data on all database schemas.
|
||||||
|
|
||||||
Django expects the database to support Unicode (UTF-8 encoding) and delegates to
|
Django expects the database to support Unicode (UTF-8 encoding) and delegates
|
||||||
it the task of enforcing transactions and referential integrity. It is important
|
to it the task of enforcing transactions and referential integrity. It is
|
||||||
to be aware of the fact that the two latter ones aren't actually enforced by
|
important to be aware of the fact that the two latter ones aren't actually
|
||||||
MySQL when using the MyISAM storage engine, see the next section.
|
enforced by MySQL when using the MyISAM storage engine, see the next section.
|
||||||
|
|
||||||
.. _mysql-storage-engines:
|
.. _mysql-storage-engines:
|
||||||
|
|
||||||
@ -691,8 +691,8 @@ storage engine, you have a couple of options.
|
|||||||
Table names
|
Table names
|
||||||
-----------
|
-----------
|
||||||
|
|
||||||
There are `known issues`_ in even the latest versions of MySQL that can cause the
|
There are `known issues`_ in even the latest versions of MySQL that can cause
|
||||||
case of a table name to be altered when certain SQL statements are executed
|
the case of a table name to be altered when certain SQL statements are executed
|
||||||
under certain conditions. It is recommended that you use lowercase table
|
under certain conditions. It is recommended that you use lowercase table
|
||||||
names, if possible, to avoid any problems that might arise from this behavior.
|
names, if possible, to avoid any problems that might arise from this behavior.
|
||||||
Django uses lowercase table names when it auto-generates table names from
|
Django uses lowercase table names when it auto-generates table names from
|
||||||
@ -710,10 +710,10 @@ Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
|
|||||||
|
|
||||||
If you use the MyISAM storage engine please be aware of the fact that you will
|
If you use the MyISAM storage engine please be aware of the fact that you will
|
||||||
receive database-generated errors if you try to use the :ref:`savepoint-related
|
receive database-generated errors if you try to use the :ref:`savepoint-related
|
||||||
methods of the transactions API <topics-db-transactions-savepoints>`. The reason
|
methods of the transactions API <topics-db-transactions-savepoints>`. The
|
||||||
for this is that detecting the storage engine of a MySQL database/table is an
|
reason for this is that detecting the storage engine of a MySQL database/table
|
||||||
expensive operation so it was decided it isn't worth to dynamically convert
|
is an expensive operation so it was decided it isn't worth to dynamically
|
||||||
these methods in no-op's based in the results of such detection.
|
convert these methods in no-op's based in the results of such detection.
|
||||||
|
|
||||||
Notes on specific fields
|
Notes on specific fields
|
||||||
------------------------
|
------------------------
|
||||||
@ -748,9 +748,9 @@ MySQL can store fractional seconds, provided that the column definition
|
|||||||
includes a fractional indication (e.g. ``DATETIME(6)``).
|
includes a fractional indication (e.g. ``DATETIME(6)``).
|
||||||
|
|
||||||
Django will not upgrade existing columns to include fractional seconds if the
|
Django will not upgrade existing columns to include fractional seconds if the
|
||||||
database server supports it. If you want to enable them on an existing database,
|
database server supports it. If you want to enable them on an existing
|
||||||
it's up to you to either manually update the column on the target database, by
|
database, it's up to you to either manually update the column on the target
|
||||||
executing a command like:
|
database, by executing a command like:
|
||||||
|
|
||||||
.. code-block:: sql
|
.. code-block:: sql
|
||||||
|
|
||||||
@ -762,11 +762,12 @@ or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
|
|||||||
``TIMESTAMP`` columns
|
``TIMESTAMP`` columns
|
||||||
~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
|
If you are using a legacy database that contains ``TIMESTAMP`` columns, you
|
||||||
set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
|
must set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
|
||||||
:djadmin:`inspectdb` maps these columns to
|
:djadmin:`inspectdb` maps these columns to
|
||||||
:class:`~django.db.models.DateTimeField` and if you enable timezone support,
|
:class:`~django.db.models.DateTimeField` and if you enable timezone support,
|
||||||
both MySQL and Django will attempt to convert the values from UTC to local time.
|
both MySQL and Django will attempt to convert the values from UTC to local
|
||||||
|
time.
|
||||||
|
|
||||||
Row locking with ``QuerySet.select_for_update()``
|
Row locking with ``QuerySet.select_for_update()``
|
||||||
-------------------------------------------------
|
-------------------------------------------------
|
||||||
@ -795,9 +796,10 @@ Automatic typecasting can cause unexpected results
|
|||||||
When performing a query on a string type, but with an integer value, MySQL will
|
When performing a query on a string type, but with an integer value, MySQL will
|
||||||
coerce the types of all values in the table to an integer before performing the
|
coerce the types of all values in the table to an integer before performing the
|
||||||
comparison. If your table contains the values ``'abc'``, ``'def'`` and you
|
comparison. If your table contains the values ``'abc'``, ``'def'`` and you
|
||||||
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
|
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE
|
||||||
will match the value ``'abc1'``. Therefore, string type fields included in Django
|
mycolumn=1`` will match the value ``'abc1'``. Therefore, string type fields
|
||||||
will always cast the value to a string before using it in a query.
|
included in Django will always cast the value to a string before using it in a
|
||||||
|
query.
|
||||||
|
|
||||||
If you implement custom model fields that inherit from
|
If you implement custom model fields that inherit from
|
||||||
:class:`~django.db.models.Field` directly, are overriding
|
:class:`~django.db.models.Field` directly, are overriding
|
||||||
@ -865,14 +867,13 @@ __ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes
|
|||||||
SQLite is meant to be a lightweight database, and thus can't support a high
|
SQLite is meant to be a lightweight database, and thus can't support a high
|
||||||
level of concurrency. ``OperationalError: database is locked`` errors indicate
|
level of concurrency. ``OperationalError: database is locked`` errors indicate
|
||||||
that your application is experiencing more concurrency than ``sqlite`` can
|
that your application is experiencing more concurrency than ``sqlite`` can
|
||||||
handle in default configuration. This error means that one thread or process has
|
handle in default configuration. This error means that one thread or process
|
||||||
an exclusive lock on the database connection and another thread timed out
|
has an exclusive lock on the database connection and another thread timed out
|
||||||
waiting for the lock the be released.
|
waiting for the lock the be released.
|
||||||
|
|
||||||
Python's SQLite wrapper has
|
Python's SQLite wrapper has a default timeout value that determines how long
|
||||||
a default timeout value that determines how long the second thread is allowed to
|
the second thread is allowed to wait on the lock before it times out and raises
|
||||||
wait on the lock before it times out and raises the ``OperationalError: database
|
the ``OperationalError: database is locked`` error.
|
||||||
is locked`` error.
|
|
||||||
|
|
||||||
If you're getting this error, you can solve it by:
|
If you're getting this error, you can solve it by:
|
||||||
|
|
||||||
|
@ -54,8 +54,8 @@ command and a list of its available options.
|
|||||||
App names
|
App names
|
||||||
---------
|
---------
|
||||||
|
|
||||||
Many commands take a list of "app names." An "app name" is the basename of
|
Many commands take a list of "app names." An "app name" is the basename of the
|
||||||
the package containing your models. For example, if your :setting:`INSTALLED_APPS`
|
package containing your models. For example, if your :setting:`INSTALLED_APPS`
|
||||||
contains the string ``'mysite.blog'``, the app name is ``blog``.
|
contains the string ``'mysite.blog'``, the app name is ``blog``.
|
||||||
|
|
||||||
Determining the version
|
Determining the version
|
||||||
@ -126,13 +126,14 @@ Lists all available tags.
|
|||||||
|
|
||||||
.. django-admin-option:: --deploy
|
.. django-admin-option:: --deploy
|
||||||
|
|
||||||
Activates some additional checks that are only relevant in a deployment setting.
|
Activates some additional checks that are only relevant in a deployment
|
||||||
|
setting.
|
||||||
|
|
||||||
You can use this option in your local development environment, but since your
|
You can use this option in your local development environment, but since your
|
||||||
local development settings module may not have many of your production settings,
|
local development settings module may not have many of your production
|
||||||
you will probably want to point the ``check`` command at a different settings
|
settings, you will probably want to point the ``check`` command at a different
|
||||||
module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE` environment
|
settings module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE`
|
||||||
variable, or by passing the ``--settings`` option:
|
environment variable, or by passing the ``--settings`` option:
|
||||||
|
|
||||||
.. console::
|
.. console::
|
||||||
|
|
||||||
@ -317,8 +318,8 @@ When result of ``dumpdata`` is saved as a file, it can serve as a
|
|||||||
|
|
||||||
Note that ``dumpdata`` uses the default manager on the model for selecting the
|
Note that ``dumpdata`` uses the default manager on the model for selecting the
|
||||||
records to dump. If you're using a :ref:`custom manager <custom-managers>` as
|
records to dump. If you're using a :ref:`custom manager <custom-managers>` as
|
||||||
the default manager and it filters some of the available records, not all of the
|
the default manager and it filters some of the available records, not all of
|
||||||
objects will be dumped.
|
the objects will be dumped.
|
||||||
|
|
||||||
.. django-admin-option:: --all, -a
|
.. django-admin-option:: --all, -a
|
||||||
|
|
||||||
@ -459,12 +460,12 @@ Django doesn't create database defaults when a
|
|||||||
Similarly, database defaults aren't translated to model field defaults or
|
Similarly, database defaults aren't translated to model field defaults or
|
||||||
detected in any fashion by ``inspectdb``.
|
detected in any fashion by ``inspectdb``.
|
||||||
|
|
||||||
By default, ``inspectdb`` creates unmanaged models. That is, ``managed = False``
|
By default, ``inspectdb`` creates unmanaged models. That is, ``managed =
|
||||||
in the model's ``Meta`` class tells Django not to manage each table's creation,
|
False`` in the model's ``Meta`` class tells Django not to manage each table's
|
||||||
modification, and deletion. If you do want to allow Django to manage the
|
creation, modification, and deletion. If you do want to allow Django to manage
|
||||||
table's lifecycle, you'll need to change the
|
the table's lifecycle, you'll need to change the
|
||||||
:attr:`~django.db.models.Options.managed` option to ``True`` (or remove
|
:attr:`~django.db.models.Options.managed` option to ``True`` (or remove it
|
||||||
it because ``True`` is its default value).
|
because ``True`` is its default value).
|
||||||
|
|
||||||
Database-specific notes
|
Database-specific notes
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
@ -860,8 +861,8 @@ optimized.
|
|||||||
.. django-admin:: runserver [addrport]
|
.. django-admin:: runserver [addrport]
|
||||||
|
|
||||||
Starts a lightweight development web server on the local machine. By default,
|
Starts a lightweight development web server on the local machine. By default,
|
||||||
the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an
|
the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in
|
||||||
IP address and port number explicitly.
|
an IP address and port number explicitly.
|
||||||
|
|
||||||
If you run this script as a user with normal privileges (recommended), you
|
If you run this script as a user with normal privileges (recommended), you
|
||||||
might not have access to start a port on a low port number. Low port numbers
|
might not have access to start a port on a low port number. Low port numbers
|
||||||
@ -1234,10 +1235,10 @@ Specifies the database for which to print the SQL. Defaults to ``default``.
|
|||||||
|
|
||||||
.. django-admin:: squashmigrations app_label [start_migration_name] migration_name
|
.. django-admin:: squashmigrations app_label [start_migration_name] migration_name
|
||||||
|
|
||||||
Squashes the migrations for ``app_label`` up to and including ``migration_name``
|
Squashes the migrations for ``app_label`` up to and including
|
||||||
down into fewer migrations, if possible. The resulting squashed migrations
|
``migration_name`` down into fewer migrations, if possible. The resulting
|
||||||
can live alongside the unsquashed ones safely. For more information,
|
squashed migrations can live alongside the unsquashed ones safely. For more
|
||||||
please read :ref:`migration-squashing`.
|
information, please read :ref:`migration-squashing`.
|
||||||
|
|
||||||
When ``start_migration_name`` is given, Django will only include migrations
|
When ``start_migration_name`` is given, Django will only include migrations
|
||||||
starting from and including this migration. This helps to mitigate the
|
starting from and including this migration. This helps to mitigate the
|
||||||
@ -1633,9 +1634,9 @@ For example, this command:
|
|||||||
|
|
||||||
This is useful in a number of ways:
|
This is useful in a number of ways:
|
||||||
|
|
||||||
* When you're writing :doc:`unit tests </topics/testing/overview>` of how your views
|
* When you're writing :doc:`unit tests </topics/testing/overview>` of how your
|
||||||
act with certain fixture data, you can use ``testserver`` to interact with
|
views act with certain fixture data, you can use ``testserver`` to interact
|
||||||
the views in a web browser, manually.
|
with the views in a web browser, manually.
|
||||||
|
|
||||||
* Let's say you're developing your Django application and have a "pristine"
|
* Let's say you're developing your Django application and have a "pristine"
|
||||||
copy of a database that you'd like to interact with. You can dump your
|
copy of a database that you'd like to interact with. You can dump your
|
||||||
@ -1758,10 +1759,10 @@ it when running interactively.
|
|||||||
|
|
||||||
Specifies the database into which the superuser object will be saved.
|
Specifies the database into which the superuser object will be saved.
|
||||||
|
|
||||||
You can subclass the management command and override ``get_input_data()`` if you
|
You can subclass the management command and override ``get_input_data()`` if
|
||||||
want to customize data input and validation. Consult the source code for
|
you want to customize data input and validation. Consult the source code for
|
||||||
details on the existing implementation and the method's parameters. For example,
|
details on the existing implementation and the method's parameters. For
|
||||||
it could be useful if you have a ``ForeignKey`` in
|
example, it could be useful if you have a ``ForeignKey`` in
|
||||||
:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to
|
:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to
|
||||||
allow creating an instance instead of entering the primary key of an existing
|
allow creating an instance instead of entering the primary key of an existing
|
||||||
instance.
|
instance.
|
||||||
@ -1831,8 +1832,8 @@ Please refer to its :djadmin:`description <collectstatic>` in the
|
|||||||
This command is only available if the :doc:`static files application
|
This command is only available if the :doc:`static files application
|
||||||
</howto/static-files/index>` (``django.contrib.staticfiles``) is installed.
|
</howto/static-files/index>` (``django.contrib.staticfiles``) is installed.
|
||||||
|
|
||||||
Please refer to its :djadmin:`description <findstatic>` in the :doc:`staticfiles
|
Please refer to its :djadmin:`description <findstatic>` in the
|
||||||
</ref/contrib/staticfiles>` documentation.
|
:doc:`staticfiles </ref/contrib/staticfiles>` documentation.
|
||||||
|
|
||||||
Default options
|
Default options
|
||||||
===============
|
===============
|
||||||
@ -2085,8 +2086,8 @@ Bash completion
|
|||||||
---------------
|
---------------
|
||||||
|
|
||||||
If you use the Bash shell, consider installing the Django bash completion
|
If you use the Bash shell, consider installing the Django bash completion
|
||||||
script, which lives in :source:`extras/django_bash_completion` in the Django source
|
script, which lives in :source:`extras/django_bash_completion` in the Django
|
||||||
distribution. It enables tab-completion of ``django-admin`` and
|
source distribution. It enables tab-completion of ``django-admin`` and
|
||||||
``manage.py`` commands, so you can, for instance...
|
``manage.py`` commands, so you can, for instance...
|
||||||
|
|
||||||
* Type ``django-admin``.
|
* Type ``django-admin``.
|
||||||
@ -2150,7 +2151,8 @@ Examples::
|
|||||||
management.call_command(loaddata.Command(), "test_data", verbosity=0)
|
management.call_command(loaddata.Command(), "test_data", verbosity=0)
|
||||||
|
|
||||||
Note that command options that take no arguments are passed as keywords
|
Note that command options that take no arguments are passed as keywords
|
||||||
with ``True`` or ``False``, as you can see with the ``interactive`` option above.
|
with ``True`` or ``False``, as you can see with the ``interactive`` option
|
||||||
|
above.
|
||||||
|
|
||||||
Named arguments can be passed by using either one of the following syntaxes::
|
Named arguments can be passed by using either one of the following syntaxes::
|
||||||
|
|
||||||
|
@ -36,11 +36,11 @@ The ``File`` class
|
|||||||
Some subclasses of :class:`File`, including
|
Some subclasses of :class:`File`, including
|
||||||
:class:`~django.core.files.base.ContentFile` and
|
:class:`~django.core.files.base.ContentFile` and
|
||||||
:class:`~django.db.models.fields.files.FieldFile`, may replace this
|
:class:`~django.db.models.fields.files.FieldFile`, may replace this
|
||||||
attribute with an object other than a Python :py:term:`file object`.
|
attribute with an object other than a Python :py:term:`file
|
||||||
In these cases, this attribute may itself be a :class:`File`
|
object`. In these cases, this attribute may itself be a
|
||||||
subclass (and not necessarily the same subclass). Whenever
|
:class:`File` subclass (and not necessarily the same subclass).
|
||||||
possible, use the attributes and methods of the subclass itself
|
Whenever possible, use the attributes and methods of the subclass
|
||||||
rather than the those of the subclass's ``file`` attribute.
|
itself rather than the those of the subclass's ``file`` attribute.
|
||||||
|
|
||||||
.. attribute:: mode
|
.. attribute:: mode
|
||||||
|
|
||||||
|
@ -25,8 +25,8 @@ You'll usually use one of these methods to access the uploaded content:
|
|||||||
.. method:: UploadedFile.multiple_chunks(chunk_size=None)
|
.. method:: UploadedFile.multiple_chunks(chunk_size=None)
|
||||||
|
|
||||||
Returns ``True`` if the uploaded file is big enough to require reading in
|
Returns ``True`` if the uploaded file is big enough to require reading in
|
||||||
multiple chunks. By default this will be any file larger than 2.5 megabytes,
|
multiple chunks. By default this will be any file larger than 2.5
|
||||||
but that's configurable; see below.
|
megabytes, but that's configurable; see below.
|
||||||
|
|
||||||
.. method:: UploadedFile.chunks(chunk_size=None)
|
.. method:: UploadedFile.chunks(chunk_size=None)
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user