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

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

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

View File

@ -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?
===============================================================================================
The :class:`~django.contrib.admin.ModelAdmin` class provides customization hooks
that allow you to transform an object as it saved, using details from the
The :class:`~django.contrib.admin.ModelAdmin` class provides customization
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
: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
@ -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
hooks that allow you to control the visibility and editability of objects in the
admin. Using the same trick of extracting the user from the request, the
hooks that allow you to control the visibility and editability of objects in
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.has_change_permission` can be used to
control the visibility and editability of objects in the admin.

View File

@ -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?
=====================================================
Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the 1930s
to early 1950s. To this day, he's considered one of the best guitarists of all time.
Django is named after `Django Reinhardt`_, a jazz manouche guitarist from the
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.
@ -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
can browse documentation changes just like you can browse code changes.
Technically, the docs on Django's site are generated from the latest development
versions of those reST documents, so the docs on the Django site may offer more
information than the docs that come with the latest Django release.
Technically, the docs on Django's site are generated from the latest
development versions of those reST documents, so the docs on the Django site
may offer more information than the docs that come with the latest Django
release.
How do I cite Django?
=====================

View File

@ -8,8 +8,8 @@ How do I get started?
#. `Download the code`_.
#. Install Django (read the :doc:`installation guide </intro/install>`).
#. Walk through the :doc:`tutorial </intro/tutorial01>`.
#. Check out the rest of the :doc:`documentation </index>`, and `ask questions`_ if you
run into trouble.
#. Check out the rest of the :doc:`documentation </index>`, and
`ask questions`_ if you run into trouble.
.. _`Download the code`: https://www.djangoproject.com/download/
.. _ask questions: https://www.djangoproject.com/community/

View File

@ -27,8 +27,8 @@ the following:
``connection.queries`` includes all SQL statements -- INSERTs, UPDATES,
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
same interface on each member of the ``connections`` dictionary:
If you are using :doc:`multiple databases</topics/db/multi-db>`, you can use
the same interface on each member of the ``connections`` dictionary:
.. code-block:: pycon

View File

@ -51,7 +51,8 @@ Glossary
See :class:`property`.
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`.

View File

@ -37,9 +37,9 @@ Using CSRF protection with AJAX
===============================
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
every POST request. For this reason, there is an alternative method: on each
XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
inconveniences: you have to remember to pass the CSRF token in as POST data
with every POST request. For this reason, there is an alternative method: on
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
often easier because many JavaScript frameworks provide hooks that allow
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
functions, due to the need for the CSRF token which must be sent with every POST
request. For this reason, Django's HTTP client for tests has been modified 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
(e.g. sending cookies etc.), they behave the same.
functions, due to the need for the CSRF token which must be sent with every
POST request. For this reason, Django's HTTP client for tests has been modified
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 (e.g.
sending cookies etc.), they behave the same.
If, for some reason, you *want* the test client to perform CSRF
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
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
section.
situations. The scenarios they might be needed in are described in the
following section.
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.
Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
should be the innermost decorator).
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e.
``requires_csrf_token`` should be the innermost decorator).
Protecting a view for only one path
-----------------------------------
@ -304,8 +304,8 @@ view that sends the page.
CSRF protection in reusable applications
========================================
Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
the security of these applications against CSRF. It is recommended that the
developers of other reusable apps that want the same guarantees also use the
``csrf_protect`` decorator on their views.
Because it is possible for the developer to turn off the
``CsrfViewMiddleware``, all relevant views in contrib apps use the
``csrf_protect`` decorator to ensure the security of these applications against
CSRF. It is recommended that the developers of other reusable apps that want
the same guarantees also use the ``csrf_protect`` decorator on their views.

View File

@ -16,8 +16,9 @@ You'll need to follow these steps:
class MyStorage(Storage): ...
#. Django must be able to instantiate your storage system without any arguments.
This means that any settings should be taken from ``django.conf.settings``::
#. Django must be able to instantiate your storage system without any
arguments. This means that any settings should be taken from
``django.conf.settings``::
from django.conf import settings
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
the ``path()`` method.
#. Your storage class must be :ref:`deconstructible <custom-deconstruct-method>`
so it can be serialized when it's used on a field in a migration. As long
as your field has arguments that are themselves
:ref:`serializable <migration-serializing>`, you can use the
#. Your storage class must be :ref:`deconstructible
<custom-deconstruct-method>` so it can be serialized when it's used on a
field in a migration. As long as your field has arguments that are
themselves :ref:`serializable <migration-serializing>`, you can use the
``django.utils.deconstruct.deconstructible`` class decorator for this
(that's what Django uses on FileSystemStorage).
@ -73,16 +74,16 @@ objects. These are:
**Required**.
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,
you'll want to return some subclass here that implements logic specific to the
backend storage system. The :exc:`FileNotFoundError` exception should be raised
when a file doesn't exist.
uses to open the file. This must return a ``File`` object, though in most
cases, you'll want to return some subclass here that implements logic specific
to the backend storage system. The :exc:`FileNotFoundError` exception should be
raised when a file doesn't exist.
.. method:: _save(name, content)
Called by ``Storage.save()``. The ``name`` will already have gone through
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
``File`` object itself.
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be
a ``File`` object itself.
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

View File

@ -39,9 +39,9 @@ lookup, then we need to tell Django about it::
return "%s <> %s" % (lhs, rhs), params
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
makes sense on all ``Field`` subclasses, so we register it with ``Field``
directly::
the field class we want the lookup to be available for. In this case, the
lookup makes sense on all ``Field`` subclasses, so we register it with
``Field`` directly::
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``.
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``
and use ``NotEqual`` to generate the SQL. By convention, these names are always
lowercase strings containing only letters, but the only hard requirement is
that it must not contain the string ``__``.
``lookup_name``. This allows the ORM to understand how to interpret
``name__ne`` and use ``NotEqual`` to generate the SQL. By convention, these
names are always lowercase strings containing only letters, but the only hard
requirement is that it must not contain the string ``__``.
We then need to define the ``as_sql`` method. This takes a ``SQLCompiler``
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,
and without duplicating functionality already in Django.
We will start by writing an ``AbsoluteValue`` transformer. This will use the SQL
function ``ABS()`` to transform the value before comparison::
We will start by writing an ``AbsoluteValue`` transformer. This will use the
SQL function ``ABS()`` to transform the value before comparison::
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.
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
than a plain integer value (for example an ``F()`` reference) we can't do the
transformations in Python.
database. The reason for doing this is that if the ``self.rhs`` is something
else than a plain integer value (for example an ``F()`` reference) we can't do
the transformations in Python.
.. note::
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
do so as you can make use of the indexes. However with PostgreSQL you may
want to add an index on ``abs(change)`` which would allow these queries to
be very efficient.
like this, and on most database backends it is likely to be more sensible
to do so as you can make use of the indexes. However with PostgreSQL you
may want to add an index on ``abs(change)`` which would allow these queries
to be very efficient.
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
transformations in a database-agnostic way.
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to
transform the values before comparison. We define
:attr:`bilateral = True <django.db.models.Transform.bilateral>` to indicate that
this transformation should apply to both ``lhs`` and ``rhs``::
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()``
to transform the values before comparison. We define :attr:`bilateral = True
<django.db.models.Transform.bilateral>` to indicate that this transformation
should apply to both ``lhs`` and ``rhs``::
from django.db.models import Transform
@ -272,8 +272,8 @@ Next, let's register it::
CharField.register_lookup(UpperCase)
TextField.register_lookup(UpperCase)
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a case
insensitive query like this:
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a
case insensitive query like this:
.. code-block:: sql

View File

@ -28,8 +28,8 @@ whose name doesn't begin with an underscore. For example:
tests.py
views.py
In this example, the ``closepoll`` command will be made available to any project
that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
In this example, the ``closepoll`` command will be made available to any
project that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
The ``_private.py`` module will not be available as a management command.
@ -73,13 +73,12 @@ look like this::
.. _management-commands-output:
.. note::
When you are using management commands and wish to provide console
output, you should write to ``self.stdout`` and ``self.stderr``,
instead of printing to ``stdout`` and ``stderr`` directly. By
using these proxies, it becomes much easier to test your custom
command. Note also that you don't need to end messages with a newline
character, it will be added automatically, unless you specify the ``ending``
parameter::
When you are using management commands and wish to provide console output,
you should write to ``self.stdout`` and ``self.stderr``, instead of
printing to ``stdout`` and ``stderr`` directly. By using these proxies, it
becomes much easier to test your custom command. Note also that you don't
need to end messages with a newline character, it will be added
automatically, unless you specify the ``ending`` parameter::
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
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):
def add_arguments(self, parser):
@ -273,7 +273,8 @@ the :meth:`~BaseCommand.handle` method must be implemented.
Django.
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)

View File

@ -7,17 +7,18 @@ How to create custom model fields
Introduction
============
The :doc:`model reference </topics/db/models>` documentation explains how to use
Django's standard field classes -- :class:`~django.db.models.CharField`,
The :doc:`model reference </topics/db/models>` documentation explains how to
use Django's standard field classes -- :class:`~django.db.models.CharField`,
: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
requirements, or you'll want to use a field that is entirely different from
those shipped with Django.
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
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
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
@ -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
mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
of :class:`django.db.models.Field`. Most of the information that Django records
about a field is common to all fields -- name, help text, uniqueness and so
forth. Storing all that information is handled by ``Field``. We'll get into the
precise details of what ``Field`` can do later on; for now, suffice it to say
that everything descends from ``Field`` and then customizes key pieces of the
class behavior.
mean model fields and not :doc:`form fields </ref/forms/fields>`) are
subclasses of :class:`django.db.models.Field`. Most of the information that
Django records about a field is common to all fields -- name, help text,
uniqueness and so forth. Storing all that information is handled by ``Field``.
We'll get into the precise details of what ``Field`` can do later on; for now,
suffice it to say that everything descends from ``Field`` and then customizes
key pieces of the class behavior.
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
@ -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`
class, from which everything is descended.
Initializing your new field is a matter of separating out any arguments that are
specific to your case from the common arguments and passing the latter to the
``__init__()`` method of :class:`~django.db.models.Field` (or your parent
Initializing your new field is a matter of separating out any arguments that
are specific to your case from the common arguments and passing the latter to
the ``__init__()`` method of :class:`~django.db.models.Field` (or your parent
class).
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.help_text`
* :attr:`~django.db.models.Field.db_column`
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
ignore this option.
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if
the backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can
usually ignore this option.
* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was
automatically created, as for the :class:`~django.db.models.OneToOneField`
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.
For example, in our ``HandField`` class we're always forcibly setting
max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``
class will see this and try to return it in the keyword arguments; thus,
we can drop it from the keyword arguments for readability::
max_length in ``__init__()``. The ``deconstruct()`` method on the base
``Field`` class will see this and try to return it in the keyword arguments;
thus, we can drop it from the keyword arguments for readability::
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
the way.
The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``
and ``OneToOneField`` that point to another field to determine their database
column data types. For example, if you have an ``UnsignedAutoField``, you also
need the foreign keys that point to that field to use the same data type::
The :meth:`~Field.rel_db_type` method is called by fields such as
``ForeignKey`` and ``OneToOneField`` that point to another field to determine
their database column data types. For example, if you have an
``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).
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
can override the :meth:`~Field.formfield` method to return ``None``.
Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
as::
Continuing our ongoing example, we can write the :meth:`~Field.formfield`
method as::
class HandField(models.Field):
# ...

View File

@ -285,13 +285,13 @@ Template filter code falls into one of two situations:
order to make things easier for your template authors.
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.
(If you don't specify this flag, it defaults to ``False``). This flag tells
Django that your filter function wants to be passed an extra keyword
argument, called ``autoescape``, that is ``True`` if auto-escaping is in
effect and ``False`` otherwise. It is recommended to set the default of the
``autoescape`` parameter to ``True``, so that if you call the function
from Python code it will have escaping enabled by default.
``needs_autoescape`` flag to ``True`` when you register your filter
function. (If you don't specify this flag, it defaults to ``False``). This
flag tells Django that your filter function wants to be passed an extra
keyword argument, called ``autoescape``, that is ``True`` if auto-escaping
is in effect and ``False`` otherwise. It is recommended to set the default
of the ``autoescape`` parameter to ``True``, so that if you call the
function from Python code it will have escaping enabled by default.
For example, let's write a filter that emphasizes the first character of
a string::
@ -827,8 +827,8 @@ Advanced custom template tags
-----------------------------
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
a template tag from the ground up.
Don't worry, Django gives you complete access to the internals required to
build a template tag from the ground up.
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.
For example, let's write a full implementation of our template tag,
``{% current_time %}``, that displays the current date/time, formatted according
to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good
idea to decide the tag syntax before anything else. In our case, let's say the
tag should be used like this:
``{% current_time %}``, that displays the current date/time, formatted
according to a parameter given in the tag, in :func:`~time.strftime` syntax.
It's a good idea to decide the tag syntax before anything else. In our case,
let's say the tag should be used like this:
.. 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
different in that it allows broken template tags to appear between
``{% comment %}`` and ``{% endcomment %}``. It does so by calling
``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))``
followed by ``parser.delete_first_token()``, thus avoiding the generation of a
node list.
``parser.skip_past('endcomment')`` instead of
``parser.parse(('endcomment',))`` followed by
``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
returns an instance of ``django.template.NodeList``, which is a list of

View File

@ -40,8 +40,9 @@ For more advanced usage, please read the `Uvicorn documentation <Uvicorn_>`_.
Deploying Django using Uvicorn and Gunicorn
===========================================
Gunicorn_ is a robust web server that implements process monitoring and automatic
restarts. This can be useful when running Uvicorn in a production environment.
Gunicorn_ is a robust web server that implements process monitoring and
automatic restarts. This can be useful when running Uvicorn in a production
environment.
To install Uvicorn and Gunicorn, use the following:

View File

@ -2,10 +2,10 @@
How to authenticate against Django's user database from Apache
==============================================================
Since keeping multiple authentication databases in sync is a common problem when
dealing with Apache, you can configure Apache to authenticate against Django's
:doc:`authentication system </topics/auth/index>` directly. This requires Apache
version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
Since keeping multiple authentication databases in sync is a common problem
when dealing with Apache, you can configure Apache to authenticate against
Django's :doc:`authentication system </topics/auth/index>` directly. This
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.

View File

@ -37,9 +37,9 @@ deployments.
WSGI servers obtain the path to the ``application`` callable from their
configuration. Django's built-in server, namely the :djadmin:`runserver`
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's
set to ``<project_name>.wsgi.application``, which points to the ``application``
callable in :file:`<project_name>/wsgi.py`.
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default,
it's set to ``<project_name>.wsgi.application``, which points to the
``application`` callable in :file:`<project_name>/wsgi.py`.
Configuring the settings module
===============================

View File

@ -124,8 +124,8 @@ use ``WSGIPythonPath``; instead you should use the ``python-path`` option to
WSGIProcessGroup example.com
If you want to serve your project in a subdirectory
(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias``
to the configuration above:
(``https://example.com/mysite`` in this example), you can add
``WSGIScriptAlias`` to the configuration above:
.. code-block:: apache

View File

@ -4,8 +4,8 @@ How to manage error reporting
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
also prevent malicious users from seeing details of your application that can be
revealed by the error pages.
also prevent malicious users from seeing details of your application that can
be revealed by the error pages.
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
@ -87,11 +87,11 @@ regular expression objects. For example::
re.compile(r"^/phpmyadmin/"),
]
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
reported. Neither will any URL starting with ``/phpmyadmin/``.
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not*
be reported. Neither will any URL starting with ``/phpmyadmin/``.
The following example shows how to exclude some conventional URLs that browsers and
crawlers often request::
The following example shows how to exclude some conventional URLs that browsers
and crawlers often request::
import re
@ -220,7 +220,8 @@ filtered out of error reports in a production environment (that is, where
disclosed.
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()
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
: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
and only report/log errors if :setting:`DEBUG` is ``False``.
error handling, it's a good idea to emulate Django's built-in error
handling and only report/log errors if :setting:`DEBUG` is ``False``.

View File

@ -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
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.
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML
(with PyYAML_ installed) documents. The :doc:`serialization documentation
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or
YAML (with PyYAML_ installed) documents. The :doc:`serialization documentation
</topics/serialization>` has more details about each of these supported
:ref:`serialization formats <serialization-formats>`.

View File

@ -44,8 +44,8 @@ Save this as a file by using standard Unix output redirection:
$ python manage.py inspectdb > models.py
This feature is meant as a shortcut, not as definitive model generation. See the
:djadmin:`documentation of inspectdb <inspectdb>` for more information.
This feature is meant as a shortcut, not as definitive model generation. See
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
the Python package that holds your app. Then add the app to your

View File

@ -3,8 +3,8 @@ How to create CSV output
========================
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
Django template system.
using Django views. To do this, you can either use the Python CSV library or
the Django template system.
Using the Python CSV library
============================
@ -101,9 +101,10 @@ the assembly and transmission of a large CSV file::
Using the template system
=========================
Alternatively, you can use the :doc:`Django template system </topics/templates>`
to generate CSV. This is lower-level than using the convenient Python :mod:`csv`
module, but the solution is presented here for completeness.
Alternatively, you can use the :doc:`Django template system
</topics/templates>` to generate CSV. This is lower-level than using the
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
template output the commas in a :ttag:`for` loop.

View File

@ -87,8 +87,8 @@ mention:
browsers will handle the PDF using whatever program/plugin they've been
configured to use for PDFs.
* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers
in the "Save as..." dialog.
* You can provide an arbitrary ``filename`` parameter. It'll be used by
browsers in the "Save as..." dialog.
* You can hook into the ReportLab API: The same buffer passed as the first
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
bits using ``reportlab``. You can use a similar technique to generate any
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
when generated text-based formats.
:doc:`/howto/outputting-csv` for another example and some techniques you can
use when generated text-based formats.
.. seealso::

View File

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

View File

@ -155,10 +155,10 @@ file-serving functionality: It doesn't know about the finders feature of the
collected under :setting:`STATIC_ROOT`.
Because of this, ``staticfiles`` ships its own
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass
of the built-in one that has the ability to transparently serve all the assets
during execution of these tests in a way very similar to what we get at
development time with ``DEBUG = True``, i.e. without having to collect them
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a
subclass of the built-in one that has the ability to transparently serve all
the assets during execution of these tests in a way very similar to what we get
at development time with ``DEBUG = True``, i.e. without having to collect them
using :djadmin:`collectstatic` first.
Deployment

View File

@ -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
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::
@ -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
are caching pickled objects as these objects are not guaranteed to be
pickle-compatible across Django versions. A past instance of incompatibility
was caching pickled :class:`~django.http.HttpResponse` objects, either
directly or indirectly via the :func:`~django.views.decorators.cache.cache_page`
was caching pickled :class:`~django.http.HttpResponse` objects, either directly
or indirectly via the :func:`~django.views.decorators.cache.cache_page`
decorator.

View File

@ -173,7 +173,8 @@ the respective field according to your needs.
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
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
another.
If you plan to remove the old app later, you'll need to set the ``dependencies``
property based on whether or not the old app is installed. Otherwise, you'll
have missing dependencies once you uninstall the old app. Similarly, you'll
need to catch :exc:`LookupError` in the ``apps.get_model()`` call that
retrieves models from the old app. This approach allows you to deploy your
project anywhere without first installing and then uninstalling the old app.
If you plan to remove the old app later, you'll need to set the
``dependencies`` property based on whether or not the old app is installed.
Otherwise, you'll have missing dependencies once you uninstall the old app.
Similarly, you'll need to catch :exc:`LookupError` in the ``apps.get_model()``
call that retrieves models from the old app. This approach allows you to deploy
your project anywhere without first installing and then uninstalling the old
app.
Here's a sample migration:

View File

@ -4,7 +4,8 @@ Committing code
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
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:

View File

@ -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
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,
in this case). Check if the test fails. If so, mark that point as "bad"
(``git bisect bad``), then check out an earlier revision and recheck. Once you
find a revision where your test passes, mark it as "good":
``git checkout HEAD~100`` to check out an earlier revision (100 commits
earlier, in this case). Check if the test fails. If so, mark that point as
"bad" (``git bisect bad``), then check out an earlier revision and recheck.
Once you find a revision where your test passes, mark it as "good":
.. code-block:: shell

View File

@ -96,13 +96,12 @@ Python style
* In docstrings, follow the style of existing docstrings and :pep:`257`.
* In tests, use
:meth:`~django.test.SimpleTestCase.assertRaisesMessage` and
:meth:`~django.test.SimpleTestCase.assertWarnsMessage`
instead of :meth:`~unittest.TestCase.assertRaises` and
:meth:`~unittest.TestCase.assertWarns` so you can check the
exception or warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex`
and :meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular
* In tests, use :meth:`~django.test.SimpleTestCase.assertRaisesMessage` and
:meth:`~django.test.SimpleTestCase.assertWarnsMessage` instead of
:meth:`~unittest.TestCase.assertRaises` and
:meth:`~unittest.TestCase.assertWarns` so you can check the exception or
warning message. Use :meth:`~unittest.TestCase.assertRaisesRegex` and
:meth:`~unittest.TestCase.assertWarnsRegex` only if you need regular
expression matching.
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,
other Django components, local Django component, try/excepts. Sort lines in
each group alphabetically by the full module name. Place all ``import module``
statements before ``from module import objects`` in each section. Use absolute
imports for other Django components and relative imports for local components.
each group alphabetically by the full module name. Place all
``import module`` statements before ``from module import objects`` in each
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
the lowercase items.

View File

@ -17,8 +17,8 @@ Code style
for indentation, but there are some exceptions.
* When naming variables, use ``camelCase`` instead of ``underscore_case``.
Different JavaScript files sometimes use a different code style. Please try to
conform to the code style of each file.
Different JavaScript files sometimes use a different code style. Please try
to conform to the code style of each file.
* 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
@ -89,8 +89,8 @@ The JavaScript tests may be run from a web browser or from the command line.
Testing from a web browser
~~~~~~~~~~~~~~~~~~~~~~~~~~
To run the tests from a web browser, open up :source:`js_tests/tests.html` in your
browser.
To run the tests from a web browser, open up :source:`js_tests/tests.html` in
your browser.
To measure code coverage when running the tests, you need to view that file
over HTTP. To view code coverage:

View File

@ -204,9 +204,12 @@ whether to accept it.
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 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>`_
* `DEP 181: ORM Expressions
<https://github.com/django/deps/blob/main/final/0181-orm-expressions.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 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
the library, the library will be deprecated in Django.
As the :ref:`deprecation policy<internal-release-deprecation-policy>` describes,
the first release of Django that deprecates a feature (``A.B``) should raise a
``RemovedInDjangoXXWarning`` (where XX is the Django version where the feature
will be removed) when the deprecated feature is invoked. Assuming we have good
test coverage, these warnings are converted to errors when :ref:`running the
test suite <running-unit-tests>` with warnings enabled:
As the :ref:`deprecation policy<internal-release-deprecation-policy>`
describes, the first release of Django that deprecates a feature (``A.B``)
should raise a ``RemovedInDjangoXXWarning`` (where XX is the Django version
where the feature will be removed) when the deprecated feature is invoked.
Assuming we have good test coverage, these warnings are converted to errors
when :ref:`running the test suite <running-unit-tests>` with warnings enabled:
``python -Wa runtests.py``. Thus, when adding a ``RemovedInDjangoXXWarning``
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.
Next you can silence warnings in tests that actually test the deprecated
behavior by using the ``ignore_warnings`` decorator, either at the test or class
level:
The first step is to remove any use of the deprecated behavior by Django
itself. Next you can silence warnings in tests that actually test the
deprecated behavior by using the ``ignore_warnings`` decorator, either at the
test or class level:
#) 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
the "Features deprecated in A.B" heading.
#) Add an entry in the deprecation timeline (``docs/internals/deprecation.txt``)
under the appropriate version describing what code will be removed.
#) Add an entry in the deprecation timeline
(``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.
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 applied)?
* If it's a bug that :ref:`qualifies for a backport <supported-versions-policy>`
to the stable version of Django, is there a release note in
``docs/releases/A.B.C.txt``? Bug fixes that will be applied only to the main
branch don't need a release note.
* If it's a bug that :ref:`qualifies for a backport
<supported-versions-policy>` to the stable version of Django, is there a
release note in ``docs/releases/A.B.C.txt``? Bug fixes that will be applied
only to the main branch don't need a release note.
New Features
------------

View File

@ -398,9 +398,9 @@ and also excludes several directories not relevant to the results
Contrib apps
============
Tests for contrib apps can be found in the :source:`tests/` directory, typically
under ``<app_name>_tests``. For example, tests for ``contrib.auth`` are located
in :source:`tests/auth_tests`.
Tests for contrib apps can be found in the :source:`tests/` directory,
typically under ``<app_name>_tests``. For example, tests for ``contrib.auth``
are located in :source:`tests/auth_tests`.
.. _troubleshooting-unit-tests:

View File

@ -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
<coding-style-pre-commit>` if configured.
The check can also be run manually: provided that ``blacken-docs`` is installed,
run the following command from the ``docs`` directory:
The check can also be run manually: provided that ``blacken-docs`` is
installed, run the following command from the ``docs`` directory:
.. 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
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
point to the latest or stable version of the documentation, e.g. ``/en/stable/`` →
``/en/3.2/``.
point to the latest or stable version of the documentation, e.g.
``/en/stable/`` → ``/en/3.2/``.
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
as the ``versionadded`` mentioned above.
These ``versionadded`` and ``versionchanged`` blocks should be "self-contained."
In other words, since we only keep these annotations around for two releases,
it's nice to be able to remove the annotation and its contents without having
to reflow, reindent, or edit the surrounding text. For example, instead of
putting the entire description of a new or changed feature in a block, do
something like this:
These ``versionadded`` and ``versionchanged`` blocks should be
"self-contained." In other words, since we only keep these annotations around
for two releases, it's nice to be able to remove the annotation and its
contents without having to reflow, reindent, or edit the surrounding text. For
example, instead of putting the entire description of a new or changed feature
in a block, do something like this:
.. code-block:: rst
@ -659,12 +659,12 @@ you'd like to help translate the documentation into another language.
``django-admin`` man page
=========================
Sphinx can generate a manual page for the
:doc:`django-admin </ref/django-admin>` command. This is configured in
``docs/conf.py``. Unlike other documentation output, this man page should be
included in the Django repository and the releases as
``docs/man/django-admin.1``. There isn't a need to update this file when
updating the documentation, as it's updated once as part of the release process.
Sphinx can generate a manual page for the :doc:`django-admin
</ref/django-admin>` command. This is configured in ``docs/conf.py``. Unlike
other documentation output, this man page should be included in the Django
repository and the releases as ``docs/man/django-admin.1``. There isn't a need
to update this file when updating the documentation, as it's updated once as
part of the release process.
To generate an updated version of the man page, in the ``docs`` directory, run:

View File

@ -748,8 +748,8 @@ details on these changes.
(replaced by :py:mod:`argparse`).
* The class ``django.core.management.NoArgsCommand`` will be removed. Use
:class:`~django.core.management.BaseCommand` instead, which takes no arguments
by default.
:class:`~django.core.management.BaseCommand` instead, which takes no
arguments by default.
* ``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_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.
@ -805,7 +806,8 @@ details on these changes.
``django.contrib.admin.helpers.InlineAdminForm`` will be removed.
* 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:
@ -872,14 +874,14 @@ details on these changes.
* Support for the legacy ``%(<foo>)s`` syntax in ``ModelFormMixin.success_url``
will be removed.
* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``, ``extent3d()``,
``make_line()``, and ``unionagg()`` will be removed.
* ``GeoQuerySet`` aggregate methods ``collect()``, ``extent()``,
``extent3d()``, ``make_line()``, and ``unionagg()`` will be removed.
* Ability to specify ``ContentType.name`` when creating a content type instance
will be removed.
* Support for the old signature of ``allow_migrate`` will be removed. It changed
from ``allow_migrate(self, db, model)`` to
* Support for the old signature of ``allow_migrate`` will be removed. It
changed from ``allow_migrate(self, db, model)`` to
``allow_migrate(self, db, app_label, model_name=None, **hints)``.
* 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_string``.
* ``ssi`` and ``url`` template tags will be removed from the ``future`` template
tag library (used during the 1.3/1.4 deprecation period).
* ``ssi`` and ``url`` template tags will be removed from the ``future``
template tag library (used during the 1.3/1.4 deprecation period).
* ``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
:class:`~django.forms.ModelMultipleChoiceField` will be removed.
* The default value of the
:attr:`RedirectView.permanent <django.views.generic.base.RedirectView.permanent>`
attribute will change from ``True`` to ``False``.
* The default value of the :attr:`RedirectView.permanent
<django.views.generic.base.RedirectView.permanent>` attribute will change
from ``True`` to ``False``.
* ``django.contrib.sitemaps.FlatPageSitemap`` will be removed in favor of
``django.contrib.flatpages.sitemaps.FlatPageSitemap``.
@ -1098,8 +1100,8 @@ details on these changes.
* The ``CACHE_MIDDLEWARE_ANONYMOUS_ONLY`` setting will be removed.
* 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
forms for ManyToMany model fields will not be performed by Django anymore
more than one.* string to override or append to user-provided ``help_text``
in forms for ManyToMany model fields will not be performed by Django anymore
either at the model or forms layer.
* 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.sitemap``).
* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter and
``django.utils.html.clean_html`` will be removed following an accelerated deprecation.
* ``django.utils.html.fix_ampersands``, the ``fix_ampersands`` template filter
and ``django.utils.html.clean_html`` will be removed following an accelerated
deprecation.
.. _deprecation-removed-in-1.7:
@ -1251,8 +1254,8 @@ details on these changes.
* Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of
template filter functions will no longer be supported.
* The attribute ``HttpRequest.raw_post_data`` was renamed to ``HttpRequest.body``
in 1.4. The backward compatibility will be removed --
* The attribute ``HttpRequest.raw_post_data`` was renamed to
``HttpRequest.body`` in 1.4. The backward compatibility will be removed --
``HttpRequest.raw_post_data`` will no longer work.
* 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
timeframe.
* Translations located under the so-called *project path* will be ignored during
the translation building process performed at runtime. The
:setting:`LOCALE_PATHS` setting can be used for the same task by including the
filesystem path to a ``locale`` directory containing non-app-specific
* Translations located under the so-called *project path* will be ignored
during the translation building process performed at runtime. The
:setting:`LOCALE_PATHS` setting can be used for the same task by including
the filesystem path to a ``locale`` directory containing non-app-specific
translations in its value.
* The Markup contrib app will no longer support versions of Python-Markdown

View File

@ -115,11 +115,11 @@ updates.
committed until the final release happened.
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,
and so it no longer receives direct maintenance from the Django project.
However, that and all other similarly named branches continue to exist, and
interested community members have occasionally used them to provide
unofficial support for old Django releases.
``stable/1.3.x`` was created. Official support for that release has
expired, and so it no longer receives direct maintenance from the Django
project. However, that and all other similarly named branches continue to
exist, and interested community members have occasionally used them to
provide unofficial support for old Django releases.
Tags
====

View File

@ -471,7 +471,8 @@ Building the artifacts
.. 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
<https://code.djangoproject.com/wiki/ReleaseScript>`_

View File

@ -72,9 +72,9 @@ to make the role of Merger sustainable.
The following restrictions apply to the role of Merger:
- A person must not simultaneously serve as a member of the steering council. If
a Merger is elected to the steering council, they shall cease to be a Merger
immediately upon taking up membership in the steering council.
- A person must not simultaneously serve as a member of the steering council.
If a Merger is elected to the steering council, they shall cease to be a
Merger immediately upon taking up membership in the steering council.
- 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
@ -122,10 +122,10 @@ upload them to the :pypi:`Python Package Index <Django>` and to the
Membership
----------
`The steering council`_ selects Releasers_ as necessary to maintain their number
at a minimum of three, in order to spread the workload and avoid over-burdening
or burning out any individual Releaser. There is no upper limit to the number
of Releasers.
`The steering council`_ selects Releasers_ as necessary to maintain their
number at a minimum of three, in order to spread the workload and avoid
over-burdening or burning out any individual Releaser. There is no upper limit
to the number of Releasers.
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
@ -223,13 +223,14 @@ who demonstrate:
years must still demonstrate an understanding of Django's changes and
direction within those three years.
A new council is elected after each release cycle of Django. The election process
works as follows:
A new council is elected after each release cycle of Django. The election
process works as follows:
#. The steering council directs one of its members to notify the Secretary of the
Django Software Foundation, in writing, of the triggering of the election,
and the condition which triggered it. The Secretary post to the appropriate
venue -- the `Django Forum`_ to announce the election and its timeline.
#. The steering council directs one of its members to notify the Secretary of
the Django Software Foundation, in writing, of the triggering of the
election, and the condition which triggered it. The Secretary post to the
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
voter registration. All `individual members of the DSF`_ are automatically
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
of the Django Software Foundation.
- 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
of the steering council, and the `DSF Board`_. A valid determination of
ineligibility requires that all other members of the steering council and all
members of the DSF Board vote who can vote on the issue (the affected person,
if a DSF Board member, must not vote) vote "yes" on a motion that the person
in question is ineligible.
steering council. This determination must be made jointly by the other
members of the steering council, and the `DSF Board`_. A valid determination
of ineligibility requires that all other members of the steering council and
all members of the DSF Board vote who can vote on the issue (the affected
person, if a DSF Board member, must not vote) vote "yes" on a motion that the
person in question is ineligible.
.. _`Django Forum`: https://forum.djangoproject.com/
.. _`Django Git repository`: https://github.com/django/django/

View File

@ -45,8 +45,8 @@ security purposes, please see :doc:`our security policies <security>`.
bugs and/or security issues.
These releases will be 100% compatible with the associated feature release,
unless this is impossible for security reasons or to prevent data loss.
So the answer to "should I upgrade to the latest patch release?" will always
unless this is impossible for security reasons or to prevent data loss. So
the answer to "should I upgrade to the latest patch release?" will always
be "yes."
Long-term support release
@ -123,8 +123,8 @@ See also the :ref:`deprecating-a-feature` guide.
Supported versions
==================
At any moment in time, Django's developer team will support a set of releases to
varying levels. See `the supported versions section
At any moment in time, Django's developer team will support a set of releases
to varying levels. See `the supported versions section
<https://www.djangoproject.com/download/#supported-versions>`_ of the download
page for the current state of support for each version.

View File

@ -292,7 +292,8 @@ requires a security release:
* Exploits which fail to follow security best practices, such as failure to
sanitize user input. For other examples, see our :ref:`security
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 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
from the package maintainers.
If you are unsure whether your finding meets these criteria, please still report
it :ref:`privately by emailing security@djangoproject.com
If you are unsure whether your finding meets these criteria, please still
report it :ref:`privately by emailing security@djangoproject.com
<reporting-security-issues>`. The security team will review your report and
recommend the correct course of action.

View File

@ -32,9 +32,9 @@ don't, `Dive Into Python`_ is a fantastic (and free) online book for beginning
Python programmers.
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.
However, you'll probably want to read some more about these different tools if
you plan on contributing to Django regularly.
that this tutorial and its links include just enough information to get
started. However, you'll probably want to read some more about these different
tools if you plan on contributing to Django regularly.
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.
@ -52,9 +52,9 @@ so that it can be of use to the widest audience.
What does this tutorial cover?
------------------------------
We'll be walking you through contributing to Django for the first time.
By the end of this tutorial, you should have a basic understanding of both the
tools and the processes involved. Specifically, we'll be covering the following:
We'll be walking you through contributing to Django for the first time. By the
end of this tutorial, you should have a basic understanding of both the tools
and the processes involved. Specifically, we'll be covering the following:
* Installing Git.
* 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.
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
==============
@ -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
to ~70 MB.
Now that you have a local copy of Django, you can install it just like you would
install any package using ``pip``. The most convenient way to do so is by using
a *virtual environment*, which is a feature built into Python that allows you
to keep a separate directory of installed packages for each of your projects so
that they don't interfere with each other.
Now that you have a local copy of Django, you can install it just like you
would install any package using ``pip``. The most convenient way to do so is by
using a *virtual environment*, which is a feature built into Python that allows
you to keep a separate directory of installed packages for each of your
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
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/
The installed version of Django is now pointing at your local copy by installing
in editable mode. You will immediately see any changes you make to it, which is
of great help when testing your first contribution.
The installed version of Django is now pointing at your local copy by
installing in editable mode. You will immediately see any changes you make to
it, which is of great help when testing your first contribution.
Running Django's test suite for the first time
==============================================
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
works after you make your changes is by running Django's test suite. If all
the tests still pass, then you can be reasonably sure that your changes
work and haven't broken other parts of Django. If you've never run Django's test
suite before, it's a good idea to run it once beforehand to get familiar with
its output.
works after you make your changes is by running Django's test suite. If all the
tests still pass, then you can be reasonably sure that your changes work and
haven't broken other parts of Django. If you've never run Django's test suite
before, it's a good idea to run it once beforehand to get familiar with its
output.
Before running the test suite, enter the Django ``tests/`` directory using the
``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
If the tests ran correctly, you should see one failure corresponding to the test
method we added, with this error:
If the tests ran correctly, you should see one failure corresponding to the
test method we added, with this error:
.. code-block:: pytb

View File

@ -24,8 +24,8 @@ place: read this material to quickly get up and running.
.. seealso::
If you're new to Python_, you might want to start by getting an idea of what
the language is like. Django is 100% Python, so if you've got minimal
If you're new to Python_, you might want to start by getting an idea of
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.
If you're new to programming entirely, you might want to start with this

View File

@ -32,9 +32,9 @@ you should see something like:
Set up a database
=================
This step is only necessary if you'd like to work with a "large" database engine
like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult
the :ref:`database installation information <database-installation>`.
This step is only necessary if you'd like to work with a "large" database
engine like PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database,
consult the :ref:`database installation information <database-installation>`.
Install Django
==============

View File

@ -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
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
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more
detailed documentation </topics/index>`.
:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into
more detailed documentation </topics/index>`.
Design your model
=================
Although you can use Django without a database, it comes with an
`object-relational mapper`_ in which you describe your database layout in Python
code.
`object-relational mapper`_ in which you describe your database layout in
Python code.
.. _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}
return render(request, "news/year_archive.html", context)
This example uses Django's :doc:`template system </topics/templates>`, which has
several powerful features but strives to stay simple enough for non-programmers
to use.
This example uses Django's :doc:`template system </topics/templates>`, which
has several powerful features but strives to stay simple enough for
non-programmers to use.
Design your templates
=====================
The code above loads the ``news/year_archive.html`` template.
Django has a template search path, which allows you to minimize redundancy among
templates. In your Django settings, you specify a list of directories to check
for templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template doesn't exist
in the first directory, it checks the second, and so on.
Django has a template search path, which allows you to minimize redundancy
among templates. In your Django settings, you specify a list of directories to
check for templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template
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
might look like:
@ -287,14 +287,14 @@ used only for attribute lookup. They also can do dictionary-key lookup, index
lookup and function calls.
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
of a variable. In this case, the date filter formats a Python datetime object in
the given format (as found in PHP's date function).
character). This is called a template filter, and it's a way to filter the
value of a variable. In this case, the date filter formats a Python datetime
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
template filters <howto-writing-custom-template-filters>`. You can write
:doc:`custom template tags </howto/custom-template-tags>`, which run custom
Python code behind the scenes.
You can chain together as many filters as you'd like. You can write
:ref:`custom template filters <howto-writing-custom-template-filters>`. You can
write :doc:`custom template tags </howto/custom-template-tags>`, which run
custom Python code behind the scenes.
Finally, Django uses the concept of "template inheritance". That's what the
``{% 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>
</html>
Simplistically, it defines the look-and-feel of the site (with the site's logo),
and provides "holes" for child templates to fill. This means that a site redesign
can be done by changing a single file -- the base template.
Simplistically, it defines the look-and-feel of the site (with the site's
logo), and provides "holes" for child templates to fill. This means that a site
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
templates, while reusing child templates. Django's creators have used this

View File

@ -344,8 +344,8 @@ the world! If this wasn't just an example, you could now:
* Upload the package on your website.
* Post the package on a public repository, such as `the Python Package Index
(PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
(PyPI)`_. There is `a good tutorial
<https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
for doing this.
Installing Python packages with a virtual environment

View File

@ -39,8 +39,8 @@ Creating a project
==================
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
Django :term:`project` -- a collection of settings for an instance of Django,
initial setup. Namely, you'll need to auto-generate some code that establishes
a Django :term:`project` -- a collection of settings for an instance of Django,
including database configuration, Django-specific options and
application-specific settings.
@ -122,8 +122,8 @@ You'll see the following output on the command line:
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
You have unapplied migrations; your app may not work properly until they are
applied. Run 'python manage.py migrate' to apply them.
|today| - 15:50:53
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
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`

View File

@ -51,7 +51,8 @@ come with Django:
* :mod:`django.contrib.staticfiles` -- A framework for managing
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,
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
The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting
and creates any necessary database tables according to the database settings
in your :file:`mysite/settings.py` file and the database migrations shipped
with the app (we'll cover those later). You'll see a message for each
migration it applies. If you're interested, run the command-line client for your
database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL),
``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to
display the tables Django created.
and creates any necessary database tables according to the database settings in
your :file:`mysite/settings.py` file and the database migrations shipped with
the app (we'll cover those later). You'll see a message for each migration it
applies. If you're interested, run the command-line client for your database
and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL), ``.tables``
(SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to display the
tables Django created.
.. admonition:: For the minimalists
@ -94,8 +95,8 @@ additional metadata.
Django follows the :ref:`DRY Principle <dry>`. The goal is to define your
data model in one place and automatically derive things from it.
This includes the migrations - unlike in Ruby On Rails, for example, migrations
are entirely derived from your models file, and are essentially a
This includes the migrations - unlike in Ruby On Rails, for example,
migrations are entirely derived from your models file, and are essentially a
history that Django can roll through to update your database schema to
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.
You can use an optional first positional argument to a
:class:`~django.db.models.Field` to designate a human-readable name. That's used
in a couple of introspective parts of Django, and it doubles as documentation.
If this field isn't provided, Django will use the machine-readable name. In this
example, we've only defined a human-readable name for ``Question.pub_date``.
For all other fields in this model, the field's machine-readable name will
suffice as its human-readable name.
:class:`~django.db.models.Field` to designate a human-readable name. That's
used in a couple of introspective parts of Django, and it doubles as
documentation. If this field isn't provided, Django will use the
machine-readable name. In this example, we've only defined a human-readable
name for ``Question.pub_date``. For all other fields in this model, the field's
machine-readable name will suffice as its human-readable name.
Some :class:`~django.db.models.Field` classes have required arguments.
: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:
* 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.
@ -223,8 +225,8 @@ they're designed to be human-editable in case you want to manually tweak how
Django changes things.
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
moment - but first, let's see what SQL that migration would run. The
schema automatically - that's called :djadmin:`migrate`, and we'll come to it
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:
.. 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
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::
@ -534,8 +537,8 @@ Introducing the Django Admin
Django was written in a newsroom environment, with a very clear separation
between "content publishers" and the "public" site. Site managers use the
system to add news stories, events, sports scores, etc., and that content is
displayed on the public site. Django solves the problem of creating a
system to add news stories, events, sports scores, etc., and that content
is displayed on the public site. Django solves the problem of creating a
unified interface for site administrators to edit content.
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
--------------------
Now, try logging in with the superuser account you created in the previous step.
You should see the Django admin index page:
Now, try logging in with the superuser account you created in the previous
step. You should see the Django admin index page:
.. image:: _images/admin02.png
:alt: Django admin index page
@ -628,15 +631,15 @@ edit it to look like this:
Explore the free admin functionality
------------------------------------
Now that we've registered ``Question``, Django knows that it should be displayed on
the admin index page:
Now that we've registered ``Question``, Django knows that it should be
displayed on the admin index page:
.. image:: _images/admin03t.png
:alt: Django admin index page, now with polls displayed
Click "Questions". Now you're at the "change list" page for questions. This page
displays all the questions in the database and lets you choose one to change it.
There's the "What's up?" question we created earlier:
Click "Questions". Now you're at the "change list" page for questions. This
page displays all the questions in the database and lets you choose one to
change it. There's the "What's up?" question we created earlier:
.. image:: _images/admin04t.png
:alt: Polls change list page

View File

@ -2,8 +2,8 @@
Writing your first Django app, part 3
=====================================
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're
continuing the web-poll application and will focus on creating the public
This tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off.
We're continuing the web-poll application and will focus on creating the public
interface -- "views."
.. 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
``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
*URL patterns* than that.
You will be pleased to know that Django allows us much more elegant *URL
patterns* than that.
A URL pattern is the general form of a URL - for example:
``/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
:class:`~django.http.HttpResponse` object containing the content for the
requested page, or raising an exception such as :exc:`~django.http.Http404`. The
rest is up to you.
requested page, or raising an exception such as :exc:`~django.http.Http404`.
The rest is up to you.
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.
@ -167,9 +167,9 @@ commas, according to publication date:
# 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
you want to change the way the page looks, you'll have to edit this Python code.
So let's use Django's template system to separate the design from Python by
creating a template that the view can use.
you want to change the way the page looks, you'll have to edit this Python
code. So let's use Django's template system to separate the design from Python
by creating a template that the view can use.
First, create a directory called ``templates`` in your ``polls`` directory.
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
:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll
want to keep ``HttpResponse`` if you still have the stub methods for ``detail``,
``results``, and ``vote``).
want to keep ``HttpResponse`` if you still have the stub methods for
``detail``, ``results``, and ``vote``).
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
@ -279,8 +279,8 @@ object of the given template rendered with the given context.
Raising a 404 error
===================
Now, let's tackle the question detail view -- the page that displays the question text
for a given poll. Here's the view:
Now, let's tackle the question detail view -- the page that displays the
question text for a given poll. Here's the view:
.. code-block:: python
:caption: ``polls/views.py``
@ -361,8 +361,8 @@ Use the template system
=======================
Back to the ``detail()`` view for our poll application. Given the context
variable ``question``, here's what the ``polls/detail.html`` template might look
like:
variable ``question``, here's what the ``polls/detail.html`` template might
look like:
.. code-block:: html+django
:caption: ``polls/templates/polls/detail.html``
@ -375,15 +375,15 @@ like:
</ul>
The template system uses dot-lookup syntax to access variable attributes. In
the example of ``{{ question.question_text }}``, first Django does a dictionary lookup
on the object ``question``. Failing that, it tries an attribute lookup -- which
works, in this case. If attribute lookup had failed, it would've tried a
list-index lookup.
the example of ``{{ question.question_text }}``, first Django does a dictionary
lookup on the object ``question``. Failing that, it tries an attribute lookup
-- which works, in this case. If attribute lookup had failed, it would've tried
a list-index lookup.
Method-calling happens in the :ttag:`{% for %}<for>` loop:
``question.choice_set.all`` is interpreted as the Python code
``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is
suitable for use in the :ttag:`{% for %}<for>` tag.
``question.choice_set.all()``, which returns an iterable of ``Choice`` objects
and is suitable for use in the :ttag:`{% for %}<for>` tag.
See the :doc:`template guide </topics/templates>` for more about templates.

View File

@ -2,8 +2,8 @@
Writing your first Django app, part 4
=====================================
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're
continuing the web-poll application and will focus on form processing and
This tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off.
We're continuing the web-poll application and will focus on form processing and
cutting down our code.
.. 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
basic concept of HTML forms.
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we
set ``method="post"``. Using ``method="post"`` (as opposed to
* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and
we set ``method="post"``. Using ``method="post"`` (as opposed to
``method="get"``) is very important, because the act of submitting this
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
@ -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
response documentation </ref/request-response>`.
After somebody votes in a question, the ``vote()`` view redirects to the results
page for the question. Let's write that view:
After somebody votes in a question, the ``vote()`` view redirects to the
results page for the question. Let's write that view:
.. code-block:: python
: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>
Now, go to ``/polls/1/`` in your browser and vote in the question. You should see a
results page that gets updated each time you vote. If you submit the form
Now, go to ``/polls/1/`` in your browser and vote in the question. You should
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.
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
shortcut, called the "generic views" system.
Generic views abstract common patterns to the point where you don't even need to
write Python code to write an app. For example, the
Generic views abstract common patterns to the point where you don't even need
to write Python code to write an app. For example, the
:class:`~django.views.generic.list.ListView` and
:class:`~django.views.generic.detail.DetailView` generic views
abstract the concepts of "display a list of objects" and
"display a detail page for a particular type of object" respectively.
:class:`~django.views.generic.detail.DetailView` generic views abstract the
concepts of "display a list of objects" and "display a detail page for a
particular type of object" respectively.
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.

View File

@ -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.
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
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.
@ -135,9 +136,10 @@ We identify a bug
-----------------
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
the ``Question`` was published within the last day (which is correct) but also if
the ``Question``s ``pub_date`` field is in the future (which certainly isn't).
right away: the ``Question.was_published_recently()`` method returns ``True``
if the ``Question`` was published within the last day (which is correct) but
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
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)
self.assertIs(future_question.was_published_recently(), False)
Here we have created a :class:`django.test.TestCase` subclass with a method that
creates a ``Question`` instance with a ``pub_date`` in the future. We then check
the output of ``was_published_recently()`` - which *ought* to be False.
Here we have created a :class:`django.test.TestCase` subclass with a method
that creates a ``Question`` instance with a ``pub_date`` in the future. We then
check the output of ``was_published_recently()`` - which *ought* to be False.
Running tests
-------------
@ -242,8 +244,8 @@ What happened is this:
* it looked for test methods - ones whose names begin with ``test``
* in ``test_was_published_recently_with_future_question`` it created a ``Question``
instance whose ``pub_date`` field is 30 days in the future
* in ``test_was_published_recently_with_future_question`` it created a
``Question`` instance whose ``pub_date`` field is 30 days in the future
* ... and using the ``assertIs()`` method, it discovered that its
``was_published_recently()`` returns ``True``, though we wanted it to return
@ -255,10 +257,10 @@ occurred.
Fixing the bug
--------------
We already know what the problem is: ``Question.was_published_recently()`` should
return ``False`` if its ``pub_date`` is in the future. Amend the method in
``models.py``, so that it will only return ``True`` if the date is also in the
past:
We already know what the problem is: ``Question.was_published_recently()``
should return ``False`` if its ``pub_date`` is in the future. Amend the method
in ``models.py``, so that it will only return ``True`` if the date is also in
the past:
.. code-block:: python
:caption: ``polls/models.py``
@ -292,8 +294,8 @@ More comprehensive tests
------------------------
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
introduced another.
method; in fact, it would be positively embarrassing if in fixing one bug we
had introduced another.
Add two more test methods to the same class, to test the behavior of the method
more comprehensively:
@ -320,8 +322,9 @@ more comprehensively:
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
And now we have three tests that confirm that ``Question.was_published_recently()``
returns sensible values for past, recent, and future questions.
And now we have three tests that confirm that
``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
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
============================
It might seem that our tests are growing out of control. At this rate there will
soon be more code in our tests than in our application, and the repetition
It might seem that our tests are growing out of control. At this rate there
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.
**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
as you continue to develop your program.
Sometimes tests will need to be updated. Suppose that we amend our views so that
only ``Question`` entries with associated ``Choice`` instances are published.
In that case, many of our existing tests will fail - *telling us exactly which
tests need to be amended to bring them up to date*, so to that extent tests
help look after themselves.
Sometimes tests will need to be updated. Suppose that we amend our views so
that only ``Question`` entries with associated ``Choice`` instances are
published. In that case, many of our existing tests will fail - *telling us
exactly which tests need to be amended to bring them up to date*, so to that
extent tests help look after themselves.
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

View File

@ -2,10 +2,10 @@
Writing your first Django app, part 7
=====================================
This tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off. We're
continuing the web-poll application and will focus on customizing Django's
automatically-generated admin site that we first explored in :doc:`Tutorial 2
</intro/tutorial02>`.
This tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off.
We're continuing the web-poll application and will focus on customizing
Django's automatically-generated admin site that we first explored in
:doc:`Tutorial 2 </intro/tutorial02>`.
.. admonition:: Where to get help:
@ -71,8 +71,8 @@ up into fieldsets:
admin.site.register(Question, QuestionAdmin)
The first element of each tuple in
:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset.
Here's what our form looks like now:
:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the
fieldset. Here's what our form looks like now:
.. image:: _images/admin08t.png
:alt: Form has fieldsets now
@ -104,10 +104,10 @@ looks like this:
.. image:: _images/admin09.png
:alt: Choice admin page
In that form, the "Question" field is a select box containing every question in the
database. Django knows that a :class:`~django.db.models.ForeignKey` should be
represented in the admin as a ``<select>`` box. In our case, only one question
exists at this point.
In that form, the "Question" field is a select box containing every question in
the database. Django knows that a :class:`~django.db.models.ForeignKey` should
be represented in the admin as a ``<select>`` box. In our case, only one
question exists at this point.
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
@ -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
"Add choice" form you're looking at.
But, really, this is an inefficient way of adding ``Choice`` objects to the system.
It'd be better if you could add a bunch of Choices directly when you create the
``Question`` object. Let's make that happen.
But, really, this is an inefficient way of adding ``Choice`` objects to the
system. It'd be better if you could add a bunch of Choices directly when you
create the ``Question`` object. Let's make that happen.
Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question``
registration code to read:
Remove the ``register()`` call for the ``Choice`` model. Then, edit the
``Question`` registration code to read:
.. code-block:: python
:caption: ``polls/admin.py``
@ -146,8 +146,8 @@ registration code to read:
admin.site.register(Question, QuestionAdmin)
This tells Django: "``Choice`` objects are edited on the ``Question`` admin page. By
default, provide enough fields for 3 choices."
This tells Django: "``Choice`` objects are edited on the ``Question`` admin
page. By default, provide enough fields for 3 choices."
Load the "Add question" page to see how that looks:
@ -167,8 +167,8 @@ image shows an added slot:
:alt: Additional slot added dynamically
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
tabular way of displaying inline related objects. To use it, change the
fields for entering related ``Choice`` objects. For that reason, Django offers
a tabular way of displaying inline related objects. To use it, change the
``ChoiceInline`` declaration to read:
.. code-block:: python
@ -278,10 +278,10 @@ This is shaping up well. Let's add some search capability::
search_fields = ["question_text"]
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
fields as you'd like -- although because it uses a ``LIKE`` query behind the
scenes, limiting the number of search fields to a reasonable number will make
it easier for your database to do the search.
search terms, Django will search the ``question_text`` field. You can use as
many fields as you'd like -- although because it uses a ``LIKE`` query behind
the scenes, limiting the number of search fields to a reasonable number will
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
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
admin index page.
By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
registered with the admin application, in alphabetical order. You may want to
make significant changes to the layout. After all, the index is probably the
By default, it displays all the apps in :setting:`INSTALLED_APPS` that have
been registered with the admin application, in alphabetical order. You may want
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.
The template to customize is ``admin/index.html``. (Do the same as with

View File

@ -2,11 +2,11 @@
Writing your first Django app, part 8
=====================================
This tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>` left off. We've
built our web-poll application and will now look at third-party packages. One of
Django's strengths is the rich ecosystem of third-party packages. They're
community developed packages that can be used to quickly improve the feature set
of an application.
This tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>` left off.
We've built our web-poll application and will now look at third-party packages.
One of Django's strengths is the rich ecosystem of third-party packages.
They're community developed packages that can be used to quickly improve the
feature set of an application.
This tutorial will show how to add :pypi:`Django Debug Toolbar
<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
outlines troubleshooting options.
#. Search for similar issues on the package's issue tracker. Django Debug
Toolbars is `on GitHub <https://github.com/django-commons/django-debug-toolbar/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc>`_.
Toolbars is `on GitHub
<https://github.com/django-commons/django-debug-toolbar/issues>`_.
#. Consult the `Django Forum <https://forum.djangoproject.com/>`_.
#. Join the `Django Discord server <https://chat.djangoproject.com>`_.

View File

@ -10,8 +10,8 @@ with this intro (in fact, if you've read every single word, you've read about
So what's next?
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
to learn new tricks, come back to the documentation. There's also a bigger
know enough to start a project of your own and start fooling around. As you
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
created.
@ -100,8 +100,8 @@ reasons:
* To add documentation for new features as new features get added, or as
Django APIs or behaviors change.
Django's documentation is kept in the same source control system as its code. It
lives in the :source:`docs` directory of our Git repository. Each document
Django's documentation is kept in the same source control system as its code.
It lives in the :source:`docs` directory of our Git repository. Each document
online is a separate text file in the repository.
Where to get it
@ -115,15 +115,16 @@ On the web
The most recent version of the Django documentation lives at
https://docs.djangoproject.com/en/dev/. These HTML pages are generated
automatically from the text files in source control. That means they reflect the
"latest and greatest" in Django -- they include the very latest corrections and
additions, and they discuss the latest Django features, which may only be
automatically from the text files in source control. That means they reflect
the "latest and greatest" in Django -- they include the very latest corrections
and additions, and they discuss the latest Django features, which may only be
available to users of the Django development version. (See
:ref:`differences-between-doc-versions` below.)
We encourage you to help improve the docs by submitting changes, corrections and
suggestions in the `ticket system`_. The Django developers actively monitor the
ticket system and use your feedback to improve the documentation for everybody.
We encourage you to help improve the docs by submitting changes, corrections
and suggestions in the `ticket system`_. The Django developers actively monitor
the ticket system and use your feedback to improve the documentation for
everybody.
Note, however, that tickets should explicitly relate to the documentation,
rather than asking broad tech-support questions. If you need help with your

View File

@ -145,7 +145,7 @@ if __name__ == "__main__":
"--disable",
"line-too-long", # Disable sphinx-lint version
"--max-line-length",
"80",
"79",
*params,
]
)

View File

@ -34,9 +34,9 @@ stack are independent of another wherever possible.
Less code
---------
Django apps should use as little code as possible; they should lack boilerplate.
Django should take full advantage of Python's dynamic capabilities, such as
introspection.
Django apps should use as little code as possible; they should lack
boilerplate. Django should take full advantage of Python's dynamic
capabilities, such as introspection.
.. _quick-development:

View File

@ -3,10 +3,10 @@ Third-party distributions of Django
===================================
Many third-party distributors are now providing versions of Django integrated
with their package-management systems. These can make installation and upgrading
much easier for users of Django since the integration includes the ability to
automatically install dependencies (like database adapters) that Django
requires.
with their package-management systems. These can make installation and
upgrading much easier for users of Django since the integration includes the
ability to automatically install dependencies (like database adapters) that
Django requires.
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
@ -21,15 +21,14 @@ a list of `Third Party Distributions`_ to help you out.
.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions
For distributors
================
If you'd like to package Django for distribution, we'd be happy to help out!
Please introduce yourself on the `Django Forum`_.
We also encourage all distributors to subscribe to the |django-announce| mailing
list, which is a (very) low-traffic list for announcing new releases of Django
and important bugfixes.
We also encourage all distributors to subscribe to the |django-announce|
mailing list, which is a (very) low-traffic list for announcing new releases of
Django and important bugfixes.
.. _Django Forum: https://forum.djangoproject.com/

View File

@ -2,8 +2,8 @@
Meta-documentation and miscellany
=================================
Documentation that we can't find a more organized place for. Like that drawer in
your kitchen with the scissors, batteries, duct tape, and other junk.
Documentation that we can't find a more organized place for. Like that drawer
in your kitchen with the scissors, batteries, duct tape, and other junk.
.. toctree::
:maxdepth: 2

View File

@ -321,12 +321,12 @@ Methods
.. note::
In the usual initialization process, the ``ready`` method is only called
once by Django. But in some corner cases, particularly in tests which
are fiddling with installed applications, ``ready`` might be called more
than once. In that case, either write idempotent methods, or put a flag
on your ``AppConfig`` classes to prevent rerunning code which should
be executed exactly one time.
In the usual initialization process, the ``ready`` method is only
called once by Django. But in some corner cases, particularly in tests
which are fiddling with installed applications, ``ready`` might be
called more than once. In that case, either write idempotent methods,
or put a flag on your ``AppConfig`` classes to prevent rerunning code
which should be executed exactly one time.
.. _namespace package:

View File

@ -189,11 +189,13 @@ Model fields
* **fields.E121**: ``max_length`` must be a positive integer.
* **fields.W122**: ``max_length`` is ignored when used with
``<integer field type>``.
* **fields.E130**: ``DecimalField``\s must define a ``decimal_places`` attribute.
* **fields.E130**: ``DecimalField``\s must define a ``decimal_places``
attribute.
* **fields.E131**: ``decimal_places`` must be a non-negative integer.
* **fields.E132**: ``DecimalField``\s must define a ``max_digits`` attribute.
* **fields.E133**: ``max_digits`` must be a positive integer.
* **fields.E134**: ``max_digits`` must be greater or equal to ``decimal_places``.
* **fields.E134**: ``max_digits`` must be greater or equal to
``decimal_places``.
* **fields.E140**: ``FilePathField``\s must have either ``allow_files`` or
``allow_folders`` set to True.
* **fields.E150**: ``GenericIPAddressField``\s cannot have ``blank=True`` if
@ -324,7 +326,8 @@ Related fields
``<model>``.
* **fields.E338**: The intermediary model ``<through model>`` has no field
``<field name>``.
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to ``<model>``.
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to
``<model>``.
* **fields.E340**: The field's intermediary table ``<table name>`` clashes with
the table name of ``<model>``/``<model>.<field name>``.
* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.
@ -382,7 +385,8 @@ Models
* **models.E019**: Autogenerated column name too long for M2M field
``<M2M field>``. Maximum length is ``<maximum length>`` for database
``<alias>``.
* **models.E020**: The ``<model>.check()`` class method is currently overridden.
* **models.E020**: The ``<model>.check()`` class method is currently
overridden.
* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used
together.
* **models.E022**: ``<function>`` contains a lazy reference to
@ -442,7 +446,8 @@ Models
Management Commands
-------------------
The following checks verify custom management commands are correctly configured:
The following checks verify custom management commands are correctly
configured:
* **commands.E001**: The ``migrate`` and ``makemigrations`` commands must have
the same ``autodetector``.
@ -489,12 +494,13 @@ The following checks are run if you use the :option:`check --deploy` option:
* **security.W005**: You have not set the
:setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this,
your site is potentially vulnerable to attack via an insecure connection to a
subdomain. Only set this to ``True`` if you are certain that all subdomains of
your domain should be served exclusively via SSL.
subdomain. Only set this to ``True`` if you are certain that all subdomains
of your domain should be served exclusively via SSL.
* **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not
set to ``True``, so your pages will not be served with an
``'X-Content-Type-Options: nosniff'`` header. You should consider enabling
this header to prevent the browser from identifying content types incorrectly.
this header to prevent the browser from identifying content types
incorrectly.
* **security.W007**: Your ``SECURE_BROWSER_XSS_FILTER`` setting is not
set to ``True``, so your pages will not be served with an
``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling
@ -504,7 +510,8 @@ The following checks are run if you use the :option:`check --deploy` option:
* **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to
``True``. Unless your site should be available over both SSL and non-SSL
connections, you may want to either set this setting to ``True`` or configure
a load balancer or reverse-proxy server to redirect all connections to HTTPS.
a load balancer or reverse-proxy server to redirect all connections to
HTTPS.
* **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters,
less than 5 unique characters, or it's prefixed with ``'django-insecure-'``
indicating that it was generated automatically by Django. Please generate a
@ -521,18 +528,19 @@ The following checks are run if you use the :option:`check --deploy` option:
to ``True``. Using a secure-only session cookie makes it more difficult for
network traffic sniffers to hijack user sessions.
* **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``.
Using a secure-only session cookie makes it more difficult for network traffic
sniffers to hijack user sessions.
Using a secure-only session cookie makes it more difficult for network
traffic sniffers to hijack user sessions.
* **security.W013**: You have :mod:`django.contrib.sessions` in your
:setting:`INSTALLED_APPS`, but you have not set
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
cookie makes it more difficult for cross-site scripting attacks to hijack user
sessions.
cookie makes it more difficult for cross-site scripting attacks to hijack
user sessions.
* **security.W014**: You have
:class:`django.contrib.sessions.middleware.SessionMiddleware` in your
:setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY`
to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for
cross-site scripting attacks to hijack user sessions.
:setting:`MIDDLEWARE`, but you have not set
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
cookie makes it more difficult for cross-site scripting attacks to hijack
user sessions.
* **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``.
Using an ``HttpOnly`` session cookie makes it more difficult for cross-site
scripting attacks to hijack user sessions.
@ -585,8 +593,8 @@ Signals
-------
* **signals.E001**: ``<handler>`` was connected to the ``<signal>`` signal with
a lazy reference to the sender ``<app label>.<model>``, but app ``<app label>``
isn't installed or doesn't provide model ``<model>``.
a lazy reference to the sender ``<app label>.<model>``, but app
``<app label>`` isn't installed or doesn't provide model ``<model>``.
Templates
---------
@ -871,8 +879,8 @@ The following checks are performed on the default
unique.
* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin
permission for model ``<model>``.
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for model
``<model>``.
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for
model ``<model>``.
* **auth.E007**: The :attr:`verbose_name
<django.db.models.Options.verbose_name>` of model ``<model>`` must be at most
244 characters for its builtin permission names

View File

@ -10,8 +10,8 @@ views.
Many of Django's built-in class-based views inherit from other class-based
views or various mixins. Because this inheritance chain is very important, the
ancestor classes are documented under the section title of **Ancestors (MRO)**.
MRO is an acronym for Method Resolution Order.
ancestor classes are documented under the section title of **Ancestors
(MRO)**. MRO is an acronym for Method Resolution Order.
``View``
========
@ -103,9 +103,9 @@ MRO is an acronym for Method Resolution Order.
delegate to a method that matches the HTTP method; a ``GET`` will be
delegated to ``get()``, a ``POST`` to ``post()``, and so on.
By default, a ``HEAD`` request will be delegated to ``get()``.
If you need to handle ``HEAD`` requests in a different way than ``GET``,
you can override the ``head()`` method. See
By default, a ``HEAD`` request will be delegated to ``get()``. If you
need to handle ``HEAD`` requests in a different way than ``GET``, you
can override the ``head()`` method. See
:ref:`supporting-other-http-methods` for an example.
.. method:: http_method_not_allowed(request, *args, **kwargs)

View File

@ -222,9 +222,9 @@ views for displaying drilldown pages for date-based data.
context will be:
* ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`
object containing all days that have objects available in the given month,
according to ``queryset``, represented as :class:`datetime.datetime`
objects, in ascending order.
object containing all days that have objects available in the given
month, according to ``queryset``, represented as
:class:`datetime.datetime` objects, in ascending order.
* ``month``: A :class:`~datetime.date` object
representing the given month.

View File

@ -78,8 +78,9 @@ Multiple object mixins
.. attribute:: ordering
A string or list of strings specifying the ordering to apply to the ``queryset``.
Valid values are the same as those for :meth:`~django.db.models.query.QuerySet.order_by`.
A string or list of strings specifying the ordering to apply to the
``queryset``. Valid values are the same as those for
:meth:`~django.db.models.query.QuerySet.order_by`.
.. attribute:: paginate_by
@ -106,10 +107,10 @@ Multiple object mixins
.. attribute:: paginator_class
The paginator class to be used for pagination. By default,
:class:`django.core.paginator.Paginator` is used. If the custom paginator
class doesn't have the same constructor interface as
:class:`django.core.paginator.Paginator`, you will also need to
provide an implementation for :meth:`get_paginator`.
:class:`django.core.paginator.Paginator` is used. If the custom
paginator class doesn't have the same constructor interface as
:class:`django.core.paginator.Paginator`, you will also need to provide
an implementation for :meth:`get_paginator`.
.. attribute:: context_object_name
@ -122,8 +123,8 @@ Multiple object mixins
.. method:: get_ordering()
Returns a string (or iterable of strings) that defines the ordering that
will be applied to the ``queryset``.
Returns a string (or iterable of strings) that defines the ordering
that will be applied to the ``queryset``.
Returns :attr:`ordering` by default.
@ -132,10 +133,10 @@ Multiple object mixins
Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
``is_paginated``).
Constructed by paginating ``queryset`` into pages of size ``page_size``.
If the request contains a ``page`` argument, either as a captured URL
argument or as a GET argument, ``object_list`` will correspond to the
objects from that page.
Constructed by paginating ``queryset`` into pages of size
``page_size``. If the request contains a ``page`` argument, either as a
captured URL argument or as a GET argument, ``object_list`` will
correspond to the objects from that page.
.. method:: get_paginate_by(queryset)

View File

@ -102,9 +102,10 @@ Single object mixins
Returns context data for displaying the object.
The base implementation of this method requires that the ``self.object``
attribute be set by the view (even if ``None``). Be sure to do this if
you are using this mixin without one of the built-in views that does so.
The base implementation of this method requires that the
``self.object`` attribute be set by the view (even if ``None``). Be
sure to do this if you are using this mixin without one of the built-in
views that does so.
It returns a dictionary with these contents:

View File

@ -2,7 +2,8 @@
Class-based views mixins
========================
Class-based views API reference. For introductory material, see :doc:`/topics/class-based-views/mixins`.
Class-based views API reference. For introductory material, see
:doc:`/topics/class-based-views/mixins`.
.. toctree::
:maxdepth: 1

View File

@ -15,13 +15,14 @@ have loaded in a hidden frame or iframe.
An example of clickjacking
==========================
Suppose an online store has a page where a logged-in user can click "Buy Now" to
purchase an item. A user has chosen to stay logged into the store all the time
for convenience. An attacker site might create an "I Like Ponies" button on one
of their own pages, and load the store's page in a transparent iframe such that
the "Buy Now" button is invisibly overlaid on the "I Like Ponies" button. If the
user visits the attacker's site, clicking "I Like Ponies" will cause an
inadvertent click on the "Buy Now" button and an unknowing purchase of the item.
Suppose an online store has a page where a logged-in user can click "Buy Now"
to purchase an item. A user has chosen to stay logged into the store all the
time for convenience. An attacker site might create an "I Like Ponies" button
on one of their own pages, and load the store's page in a transparent iframe
such that the "Buy Now" button is invisibly overlaid on the "I Like Ponies"
button. If the user visits the attacker's site, clicking "I Like Ponies" will
cause an inadvertent click on the "Buy Now" button and an unknowing purchase of
the item.
.. _clickjacking-prevention:
@ -93,8 +94,8 @@ that tells the middleware not to set the header::
Setting ``X-Frame-Options`` per view
------------------------------------
To set the ``X-Frame-Options`` header on a per view basis, Django provides these
decorators::
To set the ``X-Frame-Options`` header on a per view basis, Django provides
these decorators::
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_deny

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -46,7 +46,8 @@ The :class:`~django.middleware.csp.ContentSecurityPolicyMiddleware` is
configured using the following settings:
* :setting:`SECURE_CSP`: defines the **enforced Content Security Policy**.
* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security Policy**.
* :setting:`SECURE_CSP_REPORT_ONLY`: defines a **report-only Content Security
Policy**.
.. admonition:: These settings can be used independently or together

View File

@ -13,9 +13,9 @@ who visits the malicious site in their browser. A related type of attack,
'login CSRF', where an attacking site tricks a user's browser into logging into
a site with someone else's credentials, is also covered.
The first defense against CSRF attacks is to ensure that GET requests (and other
'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect free.
Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be
The first defense against CSRF attacks is to ensure that GET requests (and
other 'safe' methods, as defined by :rfc:`9110#section-9.2.1`) are side effect
free. Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be
protected by the steps outlined in :ref:`using-csrf`.
.. _Cross Site Request Forgeries: https://owasp.org/www-community/attacks/csrf#overview
@ -120,13 +120,14 @@ vulnerability allows and much worse).
Limitations
===========
Subdomains within a site will be able to set cookies on the client for the whole
domain. By setting the cookie and using a corresponding token, subdomains will
be able to circumvent the CSRF protection. The only way to avoid this is to
ensure that subdomains are controlled by trusted users (or, are at least unable
to set cookies). Note that even without CSRF, there are other vulnerabilities,
such as session fixation, that make giving subdomains to untrusted parties a bad
idea, and these vulnerabilities cannot easily be fixed with current browsers.
Subdomains within a site will be able to set cookies on the client for the
whole domain. By setting the cookie and using a corresponding token, subdomains
will be able to circumvent the CSRF protection. The only way to avoid this is
to ensure that subdomains are controlled by trusted users (or, are at least
unable to set cookies). Note that even without CSRF, there are other
vulnerabilities, such as session fixation, that make giving subdomains to
untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed
with current browsers.
Utilities
=========

View File

@ -439,10 +439,10 @@ Django supports MySQL 8.0.11 and higher.
Django's ``inspectdb`` feature uses the ``information_schema`` database, which
contains detailed data on all database schemas.
Django expects the database to support Unicode (UTF-8 encoding) and delegates to
it the task of enforcing transactions and referential integrity. It is important
to be aware of the fact that the two latter ones aren't actually enforced by
MySQL when using the MyISAM storage engine, see the next section.
Django expects the database to support Unicode (UTF-8 encoding) and delegates
to it the task of enforcing transactions and referential integrity. It is
important to be aware of the fact that the two latter ones aren't actually
enforced by MySQL when using the MyISAM storage engine, see the next section.
.. _mysql-storage-engines:
@ -691,8 +691,8 @@ storage engine, you have a couple of options.
Table names
-----------
There are `known issues`_ in even the latest versions of MySQL that can cause the
case of a table name to be altered when certain SQL statements are executed
There are `known issues`_ in even the latest versions of MySQL that can cause
the case of a table name to be altered when certain SQL statements are executed
under certain conditions. It is recommended that you use lowercase table
names, if possible, to avoid any problems that might arise from this behavior.
Django uses lowercase table names when it auto-generates table names from
@ -710,10 +710,10 @@ Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
If you use the MyISAM storage engine please be aware of the fact that you will
receive database-generated errors if you try to use the :ref:`savepoint-related
methods of the transactions API <topics-db-transactions-savepoints>`. The reason
for this is that detecting the storage engine of a MySQL database/table is an
expensive operation so it was decided it isn't worth to dynamically convert
these methods in no-op's based in the results of such detection.
methods of the transactions API <topics-db-transactions-savepoints>`. The
reason for this is that detecting the storage engine of a MySQL database/table
is an expensive operation so it was decided it isn't worth to dynamically
convert these methods in no-op's based in the results of such detection.
Notes on specific fields
------------------------
@ -748,9 +748,9 @@ MySQL can store fractional seconds, provided that the column definition
includes a fractional indication (e.g. ``DATETIME(6)``).
Django will not upgrade existing columns to include fractional seconds if the
database server supports it. If you want to enable them on an existing database,
it's up to you to either manually update the column on the target database, by
executing a command like:
database server supports it. If you want to enable them on an existing
database, it's up to you to either manually update the column on the target
database, by executing a command like:
.. code-block:: sql
@ -762,11 +762,12 @@ or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
``TIMESTAMP`` columns
~~~~~~~~~~~~~~~~~~~~~
If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
If you are using a legacy database that contains ``TIMESTAMP`` columns, you
must set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
:djadmin:`inspectdb` maps these columns to
:class:`~django.db.models.DateTimeField` and if you enable timezone support,
both MySQL and Django will attempt to convert the values from UTC to local time.
both MySQL and Django will attempt to convert the values from UTC to local
time.
Row locking with ``QuerySet.select_for_update()``
-------------------------------------------------
@ -795,9 +796,10 @@ Automatic typecasting can cause unexpected results
When performing a query on a string type, but with an integer value, MySQL will
coerce the types of all values in the table to an integer before performing the
comparison. If your table contains the values ``'abc'``, ``'def'`` and you
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
will match the value ``'abc1'``. Therefore, string type fields included in Django
will always cast the value to a string before using it in a query.
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE
mycolumn=1`` will match the value ``'abc1'``. Therefore, string type fields
included in Django will always cast the value to a string before using it in a
query.
If you implement custom model fields that inherit from
:class:`~django.db.models.Field` directly, are overriding
@ -865,14 +867,13 @@ __ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes
SQLite is meant to be a lightweight database, and thus can't support a high
level of concurrency. ``OperationalError: database is locked`` errors indicate
that your application is experiencing more concurrency than ``sqlite`` can
handle in default configuration. This error means that one thread or process has
an exclusive lock on the database connection and another thread timed out
handle in default configuration. This error means that one thread or process
has an exclusive lock on the database connection and another thread timed out
waiting for the lock the be released.
Python's SQLite wrapper has
a default timeout value that determines how long the second thread is allowed to
wait on the lock before it times out and raises the ``OperationalError: database
is locked`` error.
Python's SQLite wrapper has a default timeout value that determines how long
the second thread is allowed to wait on the lock before it times out and raises
the ``OperationalError: database is locked`` error.
If you're getting this error, you can solve it by:

View File

@ -54,8 +54,8 @@ command and a list of its available options.
App names
---------
Many commands take a list of "app names." An "app name" is the basename of
the package containing your models. For example, if your :setting:`INSTALLED_APPS`
Many commands take a list of "app names." An "app name" is the basename of the
package containing your models. For example, if your :setting:`INSTALLED_APPS`
contains the string ``'mysite.blog'``, the app name is ``blog``.
Determining the version
@ -126,13 +126,14 @@ Lists all available tags.
.. django-admin-option:: --deploy
Activates some additional checks that are only relevant in a deployment setting.
Activates some additional checks that are only relevant in a deployment
setting.
You can use this option in your local development environment, but since your
local development settings module may not have many of your production settings,
you will probably want to point the ``check`` command at a different settings
module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE` environment
variable, or by passing the ``--settings`` option:
local development settings module may not have many of your production
settings, you will probably want to point the ``check`` command at a different
settings module, either by setting the :envvar:`DJANGO_SETTINGS_MODULE`
environment variable, or by passing the ``--settings`` option:
.. console::
@ -317,8 +318,8 @@ When result of ``dumpdata`` is saved as a file, it can serve as a
Note that ``dumpdata`` uses the default manager on the model for selecting the
records to dump. If you're using a :ref:`custom manager <custom-managers>` as
the default manager and it filters some of the available records, not all of the
objects will be dumped.
the default manager and it filters some of the available records, not all of
the objects will be dumped.
.. django-admin-option:: --all, -a
@ -459,12 +460,12 @@ Django doesn't create database defaults when a
Similarly, database defaults aren't translated to model field defaults or
detected in any fashion by ``inspectdb``.
By default, ``inspectdb`` creates unmanaged models. That is, ``managed = False``
in the model's ``Meta`` class tells Django not to manage each table's creation,
modification, and deletion. If you do want to allow Django to manage the
table's lifecycle, you'll need to change the
:attr:`~django.db.models.Options.managed` option to ``True`` (or remove
it because ``True`` is its default value).
By default, ``inspectdb`` creates unmanaged models. That is, ``managed =
False`` in the model's ``Meta`` class tells Django not to manage each table's
creation, modification, and deletion. If you do want to allow Django to manage
the table's lifecycle, you'll need to change the
:attr:`~django.db.models.Options.managed` option to ``True`` (or remove it
because ``True`` is its default value).
Database-specific notes
~~~~~~~~~~~~~~~~~~~~~~~
@ -860,8 +861,8 @@ optimized.
.. django-admin:: runserver [addrport]
Starts a lightweight development web server on the local machine. By default,
the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an
IP address and port number explicitly.
the server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in
an IP address and port number explicitly.
If you run this script as a user with normal privileges (recommended), you
might not have access to start a port on a low port number. Low port numbers
@ -1234,10 +1235,10 @@ Specifies the database for which to print the SQL. Defaults to ``default``.
.. django-admin:: squashmigrations app_label [start_migration_name] migration_name
Squashes the migrations for ``app_label`` up to and including ``migration_name``
down into fewer migrations, if possible. The resulting squashed migrations
can live alongside the unsquashed ones safely. For more information,
please read :ref:`migration-squashing`.
Squashes the migrations for ``app_label`` up to and including
``migration_name`` down into fewer migrations, if possible. The resulting
squashed migrations can live alongside the unsquashed ones safely. For more
information, please read :ref:`migration-squashing`.
When ``start_migration_name`` is given, Django will only include migrations
starting from and including this migration. This helps to mitigate the
@ -1633,9 +1634,9 @@ For example, this command:
This is useful in a number of ways:
* When you're writing :doc:`unit tests </topics/testing/overview>` of how your views
act with certain fixture data, you can use ``testserver`` to interact with
the views in a web browser, manually.
* When you're writing :doc:`unit tests </topics/testing/overview>` of how your
views act with certain fixture data, you can use ``testserver`` to interact
with the views in a web browser, manually.
* Let's say you're developing your Django application and have a "pristine"
copy of a database that you'd like to interact with. You can dump your
@ -1758,10 +1759,10 @@ it when running interactively.
Specifies the database into which the superuser object will be saved.
You can subclass the management command and override ``get_input_data()`` if you
want to customize data input and validation. Consult the source code for
details on the existing implementation and the method's parameters. For example,
it could be useful if you have a ``ForeignKey`` in
You can subclass the management command and override ``get_input_data()`` if
you want to customize data input and validation. Consult the source code for
details on the existing implementation and the method's parameters. For
example, it could be useful if you have a ``ForeignKey`` in
:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to
allow creating an instance instead of entering the primary key of an existing
instance.
@ -1831,8 +1832,8 @@ Please refer to its :djadmin:`description <collectstatic>` in the
This command is only available if the :doc:`static files application
</howto/static-files/index>` (``django.contrib.staticfiles``) is installed.
Please refer to its :djadmin:`description <findstatic>` in the :doc:`staticfiles
</ref/contrib/staticfiles>` documentation.
Please refer to its :djadmin:`description <findstatic>` in the
:doc:`staticfiles </ref/contrib/staticfiles>` documentation.
Default options
===============
@ -2085,8 +2086,8 @@ Bash completion
---------------
If you use the Bash shell, consider installing the Django bash completion
script, which lives in :source:`extras/django_bash_completion` in the Django source
distribution. It enables tab-completion of ``django-admin`` and
script, which lives in :source:`extras/django_bash_completion` in the Django
source distribution. It enables tab-completion of ``django-admin`` and
``manage.py`` commands, so you can, for instance...
* Type ``django-admin``.
@ -2150,7 +2151,8 @@ Examples::
management.call_command(loaddata.Command(), "test_data", verbosity=0)
Note that command options that take no arguments are passed as keywords
with ``True`` or ``False``, as you can see with the ``interactive`` option above.
with ``True`` or ``False``, as you can see with the ``interactive`` option
above.
Named arguments can be passed by using either one of the following syntaxes::

View File

@ -36,11 +36,11 @@ The ``File`` class
Some subclasses of :class:`File`, including
:class:`~django.core.files.base.ContentFile` and
:class:`~django.db.models.fields.files.FieldFile`, may replace this
attribute with an object other than a Python :py:term:`file object`.
In these cases, this attribute may itself be a :class:`File`
subclass (and not necessarily the same subclass). Whenever
possible, use the attributes and methods of the subclass itself
rather than the those of the subclass's ``file`` attribute.
attribute with an object other than a Python :py:term:`file
object`. In these cases, this attribute may itself be a
:class:`File` subclass (and not necessarily the same subclass).
Whenever possible, use the attributes and methods of the subclass
itself rather than the those of the subclass's ``file`` attribute.
.. attribute:: mode

View File

@ -25,8 +25,8 @@ You'll usually use one of these methods to access the uploaded content:
.. method:: UploadedFile.multiple_chunks(chunk_size=None)
Returns ``True`` if the uploaded file is big enough to require reading in
multiple chunks. By default this will be any file larger than 2.5 megabytes,
but that's configurable; see below.
multiple chunks. By default this will be any file larger than 2.5
megabytes, but that's configurable; see below.
.. method:: UploadedFile.chunks(chunk_size=None)

Some files were not shown because too many files have changed in this diff Show More