Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- testbed/django__django/docs/ref/checks.txt +907 -0
- testbed/django__django/docs/ref/clickjacking.txt +149 -0
- testbed/django__django/docs/ref/databases.txt +1193 -0
- testbed/django__django/docs/ref/exceptions.txt +350 -0
- testbed/django__django/docs/ref/index.txt +35 -0
- testbed/django__django/docs/ref/logging.txt +408 -0
- testbed/django__django/docs/ref/middleware.txt +619 -0
- testbed/django__django/docs/ref/models/lookups.txt +234 -0
- testbed/django__django/docs/ref/models/meta.txt +123 -0
- testbed/django__django/docs/ref/request-response.txt +1347 -0
- testbed/django__django/docs/ref/schema-editor.txt +210 -0
- testbed/django__django/docs/ref/settings.txt +0 -0
- testbed/django__django/docs/ref/signals.txt +705 -0
- testbed/django__django/docs/ref/template-response.txt +307 -0
- testbed/django__django/docs/ref/unicode.txt +358 -0
- testbed/django__django/docs/ref/urlresolvers.txt +243 -0
- testbed/django__django/docs/ref/urls.txt +197 -0
- testbed/django__django/docs/ref/utils.txt +1136 -0
- testbed/django__django/docs/ref/validators.txt +378 -0
- testbed/django__django/docs/releases/0.95.txt +122 -0
- testbed/django__django/docs/releases/1.0.1.txt +64 -0
- testbed/django__django/docs/releases/1.1.3.txt +50 -0
- testbed/django__django/docs/releases/1.1.4.txt +68 -0
- testbed/django__django/docs/releases/1.10.1.txt +86 -0
- testbed/django__django/docs/releases/1.10.2.txt +30 -0
- testbed/django__django/docs/releases/1.10.4.txt +31 -0
- testbed/django__django/docs/releases/1.10.5.txt +22 -0
- testbed/django__django/docs/releases/1.10.6.txt +25 -0
- testbed/django__django/docs/releases/1.10.7.txt +39 -0
- testbed/django__django/docs/releases/1.10.8.txt +16 -0
- testbed/django__django/docs/releases/1.11.10.txt +39 -0
- testbed/django__django/docs/releases/1.11.11.txt +30 -0
- testbed/django__django/docs/releases/1.11.12.txt +18 -0
- testbed/django__django/docs/releases/1.11.14.txt +16 -0
- testbed/django__django/docs/releases/1.11.15.txt +20 -0
- testbed/django__django/docs/releases/1.11.16.txt +13 -0
- testbed/django__django/docs/releases/1.11.17.txt +15 -0
- testbed/django__django/docs/releases/1.11.18.txt +18 -0
- testbed/django__django/docs/releases/1.11.19.txt +18 -0
- testbed/django__django/docs/releases/1.11.2.txt +64 -0
- testbed/django__django/docs/releases/1.11.20.txt +12 -0
- testbed/django__django/docs/releases/1.11.21.txt +21 -0
- testbed/django__django/docs/releases/1.11.22.txt +27 -0
- testbed/django__django/docs/releases/1.11.23.txt +57 -0
- testbed/django__django/docs/releases/1.11.24.txt +15 -0
- testbed/django__django/docs/releases/1.11.25.txt +14 -0
- testbed/django__django/docs/releases/1.11.26.txt +15 -0
- testbed/django__django/docs/releases/1.11.27.txt +31 -0
- testbed/django__django/docs/releases/1.11.28.txt +13 -0
- testbed/django__django/docs/releases/1.11.29.txt +13 -0
testbed/django__django/docs/ref/checks.txt
ADDED
|
@@ -0,0 +1,907 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
======================
|
| 2 |
+
System check framework
|
| 3 |
+
======================
|
| 4 |
+
|
| 5 |
+
.. currentmodule:: django.core.checks
|
| 6 |
+
|
| 7 |
+
The system check framework is a set of static checks for validating Django
|
| 8 |
+
projects. It detects common problems and provides hints for how to fix them.
|
| 9 |
+
The framework is extensible so you can easily add your own checks.
|
| 10 |
+
|
| 11 |
+
For details on how to add your own checks and integrate them with Django's
|
| 12 |
+
system checks, see the :doc:`System check topic guide </topics/checks>`.
|
| 13 |
+
|
| 14 |
+
API reference
|
| 15 |
+
=============
|
| 16 |
+
|
| 17 |
+
``CheckMessage``
|
| 18 |
+
----------------
|
| 19 |
+
|
| 20 |
+
.. class:: CheckMessage(level, msg, hint=None, obj=None, id=None)
|
| 21 |
+
|
| 22 |
+
The warnings and errors raised by system checks must be instances of
|
| 23 |
+
``CheckMessage``. An instance encapsulates a single reportable error or
|
| 24 |
+
warning. It also provides context and hints applicable to the message, and a
|
| 25 |
+
unique identifier that is used for filtering purposes.
|
| 26 |
+
|
| 27 |
+
Constructor arguments are:
|
| 28 |
+
|
| 29 |
+
``level``
|
| 30 |
+
The severity of the message. Use one of the predefined values: ``DEBUG``,
|
| 31 |
+
``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. If the level is greater or
|
| 32 |
+
equal to ``ERROR``, then Django will prevent management commands from
|
| 33 |
+
executing. Messages with level lower than ``ERROR`` (i.e. warnings) are
|
| 34 |
+
reported to the console, but can be silenced.
|
| 35 |
+
|
| 36 |
+
``msg``
|
| 37 |
+
A short (less than 80 characters) string describing the problem. The string
|
| 38 |
+
should *not* contain newlines.
|
| 39 |
+
|
| 40 |
+
``hint``
|
| 41 |
+
A single-line string providing a hint for fixing the problem. If no hint
|
| 42 |
+
can be provided, or the hint is self-evident from the error message, the
|
| 43 |
+
hint can be omitted, or a value of ``None`` can be used.
|
| 44 |
+
|
| 45 |
+
``obj``
|
| 46 |
+
Optional. An object providing context for the message (for example, the
|
| 47 |
+
model where the problem was discovered). The object should be a model,
|
| 48 |
+
field, or manager or any other object that defines a ``__str__()`` method.
|
| 49 |
+
The method is used while reporting all messages and its result precedes the
|
| 50 |
+
message.
|
| 51 |
+
|
| 52 |
+
``id``
|
| 53 |
+
Optional string. A unique identifier for the issue. Identifiers should
|
| 54 |
+
follow the pattern ``applabel.X001``, where ``X`` is one of the letters
|
| 55 |
+
``CEWID``, indicating the message severity (``C`` for criticals, ``E`` for
|
| 56 |
+
errors and so). The number can be allocated by the application, but should
|
| 57 |
+
be unique within that application.
|
| 58 |
+
|
| 59 |
+
There are subclasses to make creating messages with common levels easier. When
|
| 60 |
+
using them you can omit the ``level`` argument because it is implied by the
|
| 61 |
+
class name.
|
| 62 |
+
|
| 63 |
+
.. class:: Debug(msg, hint=None, obj=None, id=None)
|
| 64 |
+
.. class:: Info(msg, hint=None, obj=None, id=None)
|
| 65 |
+
.. class:: Warning(msg, hint=None obj=None, id=None)
|
| 66 |
+
.. class:: Error(msg, hint=None, obj=None, id=None)
|
| 67 |
+
.. class:: Critical(msg, hint=None, obj=None, id=None)
|
| 68 |
+
|
| 69 |
+
.. _system-check-builtin-tags:
|
| 70 |
+
|
| 71 |
+
Builtin tags
|
| 72 |
+
============
|
| 73 |
+
|
| 74 |
+
Django's system checks are organized using the following tags:
|
| 75 |
+
|
| 76 |
+
* ``admin``: Checks of any admin site declarations.
|
| 77 |
+
* ``async_support``: Checks asynchronous-related configuration.
|
| 78 |
+
* ``caches``: Checks cache related configuration.
|
| 79 |
+
* ``compatibility``: Flags potential problems with version upgrades.
|
| 80 |
+
* ``database``: Checks database-related configuration issues. Database checks
|
| 81 |
+
are not run by default because they do more than static code analysis as
|
| 82 |
+
regular checks do. They are only run by the :djadmin:`migrate` command or if
|
| 83 |
+
you specify configured database aliases using the ``--database`` option when
|
| 84 |
+
calling the :djadmin:`check` command.
|
| 85 |
+
* ``files``: Checks files related configuration.
|
| 86 |
+
* ``models``: Checks of model, field, and manager definitions.
|
| 87 |
+
* ``security``: Checks security related configuration.
|
| 88 |
+
* ``signals``: Checks on signal declarations and handler registrations.
|
| 89 |
+
* ``sites``: Checks :mod:`django.contrib.sites` configuration.
|
| 90 |
+
* ``staticfiles``: Checks :mod:`django.contrib.staticfiles` configuration.
|
| 91 |
+
* ``templates``: Checks template related configuration.
|
| 92 |
+
* ``translation``: Checks translation related configuration.
|
| 93 |
+
* ``urls``: Checks URL configuration.
|
| 94 |
+
|
| 95 |
+
Some checks may be registered with multiple tags.
|
| 96 |
+
|
| 97 |
+
Core system checks
|
| 98 |
+
==================
|
| 99 |
+
|
| 100 |
+
Asynchronous support
|
| 101 |
+
--------------------
|
| 102 |
+
|
| 103 |
+
The following checks verify your setup for :doc:`/topics/async`:
|
| 104 |
+
|
| 105 |
+
* **async.E001**: You should not set the :envvar:`DJANGO_ALLOW_ASYNC_UNSAFE`
|
| 106 |
+
environment variable in deployment. This disables :ref:`async safety
|
| 107 |
+
protection <async-safety>`.
|
| 108 |
+
|
| 109 |
+
Backwards compatibility
|
| 110 |
+
-----------------------
|
| 111 |
+
|
| 112 |
+
Compatibility checks warn of potential problems that might occur after
|
| 113 |
+
upgrading Django.
|
| 114 |
+
|
| 115 |
+
* **2_0.W001**: Your URL pattern ``<pattern>`` has a ``route`` that contains
|
| 116 |
+
``(?P<``, begins with a ``^``, or ends with a ``$``. This was likely an
|
| 117 |
+
oversight when migrating from ``url()`` to :func:`~django.urls.path`.
|
| 118 |
+
* **4_0.E001**: As of Django 4.0, the values in the
|
| 119 |
+
:setting:`CSRF_TRUSTED_ORIGINS` setting must start with a scheme (usually
|
| 120 |
+
``http://`` or ``https://``) but found ``<hostname>``.
|
| 121 |
+
|
| 122 |
+
Caches
|
| 123 |
+
------
|
| 124 |
+
|
| 125 |
+
The following checks verify that your :setting:`CACHES` setting is correctly
|
| 126 |
+
configured:
|
| 127 |
+
|
| 128 |
+
* **caches.E001**: You must define a ``'default'`` cache in your
|
| 129 |
+
:setting:`CACHES` setting.
|
| 130 |
+
* **caches.W002**: Your ``<cache>`` configuration might expose your cache or
|
| 131 |
+
lead to corruption of your data because its
|
| 132 |
+
:setting:`LOCATION <CACHES-LOCATION>` matches/is inside/contains
|
| 133 |
+
:setting:`MEDIA_ROOT`/:setting:`STATIC_ROOT`/:setting:`STATICFILES_DIRS`.
|
| 134 |
+
* **caches.W003**: Your ``<cache>`` cache :setting:`LOCATION <CACHES-LOCATION>`
|
| 135 |
+
is relative. Use an absolute path instead.
|
| 136 |
+
|
| 137 |
+
Database
|
| 138 |
+
--------
|
| 139 |
+
|
| 140 |
+
MySQL and MariaDB
|
| 141 |
+
~~~~~~~~~~~~~~~~~
|
| 142 |
+
|
| 143 |
+
If you're using MySQL or MariaDB, the following checks will be performed:
|
| 144 |
+
|
| 145 |
+
* **mysql.E001**: MySQL/MariaDB does not allow unique ``CharField``\s to have a
|
| 146 |
+
``max_length`` > 255. *This check was changed to* ``mysql.W003`` *in Django
|
| 147 |
+
3.1 as the real maximum size depends on many factors.*
|
| 148 |
+
* **mysql.W002**: MySQL/MariaDB Strict Mode is not set for database connection
|
| 149 |
+
``<alias>``. See also :ref:`mysql-sql-mode`.
|
| 150 |
+
* **mysql.W003**: MySQL/MariaDB may not allow unique ``CharField``\s to have a
|
| 151 |
+
``max_length`` > 255.
|
| 152 |
+
|
| 153 |
+
Managing files
|
| 154 |
+
--------------
|
| 155 |
+
|
| 156 |
+
The following checks verify your setup for :doc:`/topics/files`:
|
| 157 |
+
|
| 158 |
+
* **files.E001**: The :setting:`FILE_UPLOAD_TEMP_DIR` setting refers to the
|
| 159 |
+
nonexistent directory ``<path>``.
|
| 160 |
+
|
| 161 |
+
Model fields
|
| 162 |
+
------------
|
| 163 |
+
|
| 164 |
+
* **fields.E001**: Field names must not end with an underscore.
|
| 165 |
+
* **fields.E002**: Field names must not contain ``"__"``.
|
| 166 |
+
* **fields.E003**: ``pk`` is a reserved word that cannot be used as a field
|
| 167 |
+
name.
|
| 168 |
+
* **fields.E004**: ``choices`` must be an iterable (e.g., a list or tuple).
|
| 169 |
+
* **fields.E005**: ``choices`` must be an iterable containing ``(actual value,
|
| 170 |
+
human readable name)`` tuples.
|
| 171 |
+
* **fields.E006**: ``db_index`` must be ``None``, ``True`` or ``False``.
|
| 172 |
+
* **fields.E007**: Primary keys must not have ``null=True``.
|
| 173 |
+
* **fields.E008**: All ``validators`` must be callable.
|
| 174 |
+
* **fields.E009**: ``max_length`` is too small to fit the longest value in
|
| 175 |
+
``choices`` (``<count>`` characters).
|
| 176 |
+
* **fields.E010**: ``<field>`` default should be a callable instead of an
|
| 177 |
+
instance so that it's not shared between all field instances.
|
| 178 |
+
* **fields.E011**: ``<database>`` does not support default database values with
|
| 179 |
+
expressions (``db_default``).
|
| 180 |
+
* **fields.E012**: ``<expression>`` cannot be used in ``db_default``.
|
| 181 |
+
* **fields.E100**: ``AutoField``\s must set primary_key=True.
|
| 182 |
+
* **fields.E110**: ``BooleanField``\s do not accept null values. *This check
|
| 183 |
+
appeared before support for null values was added in Django 2.1.*
|
| 184 |
+
* **fields.E120**: ``CharField``\s must define a ``max_length`` attribute.
|
| 185 |
+
* **fields.E121**: ``max_length`` must be a positive integer.
|
| 186 |
+
* **fields.W122**: ``max_length`` is ignored when used with
|
| 187 |
+
``<integer field type>``.
|
| 188 |
+
* **fields.E130**: ``DecimalField``\s must define a ``decimal_places`` attribute.
|
| 189 |
+
* **fields.E131**: ``decimal_places`` must be a non-negative integer.
|
| 190 |
+
* **fields.E132**: ``DecimalField``\s must define a ``max_digits`` attribute.
|
| 191 |
+
* **fields.E133**: ``max_digits`` must be a positive integer.
|
| 192 |
+
* **fields.E134**: ``max_digits`` must be greater or equal to ``decimal_places``.
|
| 193 |
+
* **fields.E140**: ``FilePathField``\s must have either ``allow_files`` or
|
| 194 |
+
``allow_folders`` set to True.
|
| 195 |
+
* **fields.E150**: ``GenericIPAddressField``\s cannot have ``blank=True`` if
|
| 196 |
+
``null=False``, as blank values are stored as nulls.
|
| 197 |
+
* **fields.E160**: The options ``auto_now``, ``auto_now_add``, and ``default``
|
| 198 |
+
are mutually exclusive. Only one of these options may be present.
|
| 199 |
+
* **fields.W161**: Fixed default value provided.
|
| 200 |
+
* **fields.W162**: ``<database>`` does not support a database index on
|
| 201 |
+
``<field data type>`` columns.
|
| 202 |
+
* **fields.W163**: ``<database>`` does not support comments on columns
|
| 203 |
+
(``db_comment``).
|
| 204 |
+
* **fields.E170**: ``BinaryField``’s ``default`` cannot be a string. Use bytes
|
| 205 |
+
content instead.
|
| 206 |
+
* **fields.E180**: ``<database>`` does not support ``JSONField``\s.
|
| 207 |
+
* **fields.E190**: ``<database>`` does not support a database collation on
|
| 208 |
+
``<field_type>``\s.
|
| 209 |
+
* **fields.E900**: ``IPAddressField`` has been removed except for support in
|
| 210 |
+
historical migrations.
|
| 211 |
+
* **fields.W900**: ``IPAddressField`` has been deprecated. Support for it
|
| 212 |
+
(except in historical migrations) will be removed in Django 1.9. *This check
|
| 213 |
+
appeared in Django 1.7 and 1.8*.
|
| 214 |
+
* **fields.W901**: ``CommaSeparatedIntegerField`` has been deprecated. Support
|
| 215 |
+
for it (except in historical migrations) will be removed in Django 2.0. *This
|
| 216 |
+
check appeared in Django 1.10 and 1.11*.
|
| 217 |
+
* **fields.E901**: ``CommaSeparatedIntegerField`` is removed except for support
|
| 218 |
+
in historical migrations.
|
| 219 |
+
* **fields.W902**: ``FloatRangeField`` is deprecated and will be removed in
|
| 220 |
+
Django 3.1. *This check appeared in Django 2.2 and 3.0*.
|
| 221 |
+
* **fields.W903**: ``NullBooleanField`` is deprecated. Support for it (except
|
| 222 |
+
in historical migrations) will be removed in Django 4.0. *This check appeared
|
| 223 |
+
in Django 3.1 and 3.2*.
|
| 224 |
+
* **fields.E903**: ``NullBooleanField`` is removed except for support in
|
| 225 |
+
historical migrations.
|
| 226 |
+
* **fields.W904**: ``django.contrib.postgres.fields.JSONField`` is deprecated.
|
| 227 |
+
Support for it (except in historical migrations) will be removed in Django
|
| 228 |
+
4.0. *This check appeared in Django 3.1 and 3.2*.
|
| 229 |
+
* **fields.E904**: ``django.contrib.postgres.fields.JSONField`` is removed
|
| 230 |
+
except for support in historical migrations.
|
| 231 |
+
* **fields.W905**: ``django.contrib.postgres.fields.CICharField`` is
|
| 232 |
+
deprecated. Support for it (except in historical migrations) will be removed
|
| 233 |
+
in Django 5.1.
|
| 234 |
+
* **fields.W906**: ``django.contrib.postgres.fields.CIEmailField`` is
|
| 235 |
+
deprecated. Support for it (except in historical migrations) will be removed
|
| 236 |
+
in Django 5.1.
|
| 237 |
+
* **fields.W907**: ``django.contrib.postgres.fields.CITextField`` is
|
| 238 |
+
deprecated. Support for it (except in historical migrations) will be removed
|
| 239 |
+
in Django 5.1.
|
| 240 |
+
|
| 241 |
+
File fields
|
| 242 |
+
~~~~~~~~~~~
|
| 243 |
+
|
| 244 |
+
* **fields.E200**: ``unique`` is not a valid argument for a ``FileField``.
|
| 245 |
+
*This check is removed in Django 1.11*.
|
| 246 |
+
* **fields.E201**: ``primary_key`` is not a valid argument for a ``FileField``.
|
| 247 |
+
* **fields.E202**: ``FileField``’s ``upload_to`` argument must be a relative
|
| 248 |
+
path, not an absolute path.
|
| 249 |
+
* **fields.E210**: Cannot use ``ImageField`` because Pillow is not installed.
|
| 250 |
+
|
| 251 |
+
Related fields
|
| 252 |
+
~~~~~~~~~~~~~~
|
| 253 |
+
|
| 254 |
+
* **fields.E300**: Field defines a relation with model ``<model>``, which is
|
| 255 |
+
either not installed, or is abstract.
|
| 256 |
+
* **fields.E301**: Field defines a relation with the model
|
| 257 |
+
``<app_label>.<model>`` which has been swapped out.
|
| 258 |
+
* **fields.E302**: Reverse accessor ``<related model>.<accessor name>`` for
|
| 259 |
+
``<app_label>.<model>.<field name>`` clashes with field name
|
| 260 |
+
``<app_label>.<model>.<field name>``.
|
| 261 |
+
* **fields.E303**: Reverse query name for ``<app_label>.<model>.<field name>``
|
| 262 |
+
clashes with field name ``<app_label>.<model>.<field name>``.
|
| 263 |
+
* **fields.E304**: Reverse accessor ``<related model>.<accessor name>`` for
|
| 264 |
+
``<app_label>.<model>.<field name>`` clashes with reverse accessor for
|
| 265 |
+
``<app_label>.<model>.<field name>``.
|
| 266 |
+
* **fields.E305**: Reverse query name for ``<app_label>.<model>.<field name>``
|
| 267 |
+
clashes with reverse query name for ``<app_label>.<model>.<field name>``.
|
| 268 |
+
* **fields.E306**: The name ``<name>`` is invalid ``related_name`` for field
|
| 269 |
+
``<model>.<field name>``.
|
| 270 |
+
* **fields.E307**: The field ``<app label>.<model>.<field name>`` was declared
|
| 271 |
+
with a lazy reference to ``<app label>.<model>``, but app ``<app label>``
|
| 272 |
+
isn't installed or doesn't provide model ``<model>``.
|
| 273 |
+
* **fields.E308**: Reverse query name ``<related query name>`` must not end
|
| 274 |
+
with an underscore.
|
| 275 |
+
* **fields.E309**: Reverse query name ``<related query name>`` must not contain
|
| 276 |
+
``'__'``.
|
| 277 |
+
* **fields.E310**: No subset of the fields ``<field1>``, ``<field2>``, ... on
|
| 278 |
+
model ``<model>`` is unique.
|
| 279 |
+
* **fields.E311**: ``<model>.<field name>`` must be unique because it is
|
| 280 |
+
referenced by a ``ForeignKey``.
|
| 281 |
+
* **fields.E312**: The ``to_field`` ``<field name>`` doesn't exist on the
|
| 282 |
+
related model ``<app label>.<model>``.
|
| 283 |
+
* **fields.E320**: Field specifies ``on_delete=SET_NULL``, but cannot be null.
|
| 284 |
+
* **fields.E321**: The field specifies ``on_delete=SET_DEFAULT``, but has no
|
| 285 |
+
default value.
|
| 286 |
+
* **fields.E330**: ``ManyToManyField``\s cannot be unique.
|
| 287 |
+
* **fields.E331**: Field specifies a many-to-many relation through model
|
| 288 |
+
``<model>``, which has not been installed.
|
| 289 |
+
* **fields.E332**: Many-to-many fields with intermediate tables must not be
|
| 290 |
+
symmetrical. *This check appeared before Django 3.0.*
|
| 291 |
+
* **fields.E333**: The model is used as an intermediate model by ``<model>``,
|
| 292 |
+
but it has more than two foreign keys to ``<model>``, which is ambiguous.
|
| 293 |
+
You must specify which two foreign keys Django should use via the
|
| 294 |
+
``through_fields`` keyword argument.
|
| 295 |
+
* **fields.E334**: The model is used as an intermediate model by ``<model>``,
|
| 296 |
+
but it has more than one foreign key from ``<model>``, which is ambiguous.
|
| 297 |
+
You must specify which foreign key Django should use via the
|
| 298 |
+
``through_fields`` keyword argument.
|
| 299 |
+
* **fields.E335**: The model is used as an intermediate model by ``<model>``,
|
| 300 |
+
but it has more than one foreign key to ``<model>``, which is ambiguous.
|
| 301 |
+
You must specify which foreign key Django should use via the
|
| 302 |
+
``through_fields`` keyword argument.
|
| 303 |
+
* **fields.E336**: The model is used as an intermediary model by ``<model>``,
|
| 304 |
+
but it does not have foreign key to ``<model>`` or ``<model>``.
|
| 305 |
+
* **fields.E337**: Field specifies ``through_fields`` but does not provide the
|
| 306 |
+
names of the two link fields that should be used for the relation through
|
| 307 |
+
``<model>``.
|
| 308 |
+
* **fields.E338**: The intermediary model ``<through model>`` has no field
|
| 309 |
+
``<field name>``.
|
| 310 |
+
* **fields.E339**: ``<model>.<field name>`` is not a foreign key to ``<model>``.
|
| 311 |
+
* **fields.E340**: The field's intermediary table ``<table name>`` clashes with
|
| 312 |
+
the table name of ``<model>``/``<model>.<field name>``.
|
| 313 |
+
* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.
|
| 314 |
+
* **fields.W341**: ``ManyToManyField`` does not support ``validators``.
|
| 315 |
+
* **fields.W342**: Setting ``unique=True`` on a ``ForeignKey`` has the same
|
| 316 |
+
effect as using a ``OneToOneField``.
|
| 317 |
+
* **fields.W343**: ``limit_choices_to`` has no effect on ``ManyToManyField``
|
| 318 |
+
with a ``through`` model. *This check appeared before Django 4.0.*
|
| 319 |
+
* **fields.W344**: The field's intermediary table ``<table name>`` clashes with
|
| 320 |
+
the table name of ``<model>``/``<model>.<field name>``.
|
| 321 |
+
* **fields.W345**: ``related_name`` has no effect on ``ManyToManyField`` with a
|
| 322 |
+
symmetrical relationship, e.g. to "self".
|
| 323 |
+
* **fields.W346**: ``db_comment`` has no effect on ``ManyToManyField``.
|
| 324 |
+
|
| 325 |
+
Models
|
| 326 |
+
------
|
| 327 |
+
|
| 328 |
+
* **models.E001**: ``<swappable>`` is not of the form ``app_label.app_name``.
|
| 329 |
+
* **models.E002**: ``<SETTING>`` references ``<model>``, which has not been
|
| 330 |
+
installed, or is abstract.
|
| 331 |
+
* **models.E003**: The model has two identical many-to-many relations through
|
| 332 |
+
the intermediate model ``<app_label>.<model>``.
|
| 333 |
+
* **models.E004**: ``id`` can only be used as a field name if the field also
|
| 334 |
+
sets ``primary_key=True``.
|
| 335 |
+
* **models.E005**: The field ``<field name>`` from parent model ``<model>``
|
| 336 |
+
clashes with the field ``<field name>`` from parent model ``<model>``.
|
| 337 |
+
* **models.E006**: The field ``<field name>`` clashes with the field
|
| 338 |
+
``<field name>`` from model ``<model>``.
|
| 339 |
+
* **models.E007**: Field ``<field name>`` has column name ``<column name>``
|
| 340 |
+
that is used by another field.
|
| 341 |
+
* **models.E008**: ``index_together`` must be a list or tuple.
|
| 342 |
+
* **models.E009**: All ``index_together`` elements must be lists or tuples.
|
| 343 |
+
* **models.E010**: ``unique_together`` must be a list or tuple.
|
| 344 |
+
* **models.E011**: All ``unique_together`` elements must be lists or tuples.
|
| 345 |
+
* **models.E012**: ``constraints/indexes/index_together/unique_together``
|
| 346 |
+
refers to the nonexistent field ``<field name>``.
|
| 347 |
+
* **models.E013**: ``constraints/indexes/index_together/unique_together``
|
| 348 |
+
refers to a ``ManyToManyField`` ``<field name>``, but ``ManyToManyField``\s
|
| 349 |
+
are not supported for that option.
|
| 350 |
+
* **models.E014**: ``ordering`` must be a tuple or list (even if you want to
|
| 351 |
+
order by only one field).
|
| 352 |
+
* **models.E015**: ``ordering`` refers to the nonexistent field, related field,
|
| 353 |
+
or lookup ``<field name>``.
|
| 354 |
+
* **models.E016**: ``constraints/indexes/index_together/unique_together``
|
| 355 |
+
refers to field ``<field_name>`` which is not local to model ``<model>``.
|
| 356 |
+
* **models.E017**: Proxy model ``<model>`` contains model fields.
|
| 357 |
+
* **models.E018**: Autogenerated column name too long for field ``<field>``.
|
| 358 |
+
Maximum length is ``<maximum length>`` for database ``<alias>``.
|
| 359 |
+
* **models.E019**: Autogenerated column name too long for M2M field
|
| 360 |
+
``<M2M field>``. Maximum length is ``<maximum length>`` for database
|
| 361 |
+
``<alias>``.
|
| 362 |
+
* **models.E020**: The ``<model>.check()`` class method is currently overridden.
|
| 363 |
+
* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used
|
| 364 |
+
together.
|
| 365 |
+
* **models.E022**: ``<function>`` contains a lazy reference to
|
| 366 |
+
``<app label>.<model>``, but app ``<app label>`` isn't installed or
|
| 367 |
+
doesn't provide model ``<model>``.
|
| 368 |
+
* **models.E023**: The model name ``<model>`` cannot start or end with an
|
| 369 |
+
underscore as it collides with the query lookup syntax.
|
| 370 |
+
* **models.E024**: The model name ``<model>`` cannot contain double underscores
|
| 371 |
+
as it collides with the query lookup syntax.
|
| 372 |
+
* **models.E025**: The property ``<property name>`` clashes with a related
|
| 373 |
+
field accessor.
|
| 374 |
+
* **models.E026**: The model cannot have more than one field with
|
| 375 |
+
``primary_key=True``.
|
| 376 |
+
* **models.W027**: ``<database>`` does not support check constraints.
|
| 377 |
+
* **models.E028**: ``db_table`` ``<db_table>`` is used by multiple models:
|
| 378 |
+
``<model list>``.
|
| 379 |
+
* **models.E029**: index name ``<index>`` is not unique for model ``<model>``.
|
| 380 |
+
* **models.E030**: index name ``<index>`` is not unique among models:
|
| 381 |
+
``<model list>``.
|
| 382 |
+
* **models.E031**: constraint name ``<constraint>`` is not unique for model
|
| 383 |
+
``<model>``.
|
| 384 |
+
* **models.E032**: constraint name ``<constraint>`` is not unique among
|
| 385 |
+
models: ``<model list>``.
|
| 386 |
+
* **models.E033**: The index name ``<index>`` cannot start with an underscore
|
| 387 |
+
or a number.
|
| 388 |
+
* **models.E034**: The index name ``<index>`` cannot be longer than
|
| 389 |
+
``<max_length>`` characters.
|
| 390 |
+
* **models.W035**: ``db_table`` ``<db_table>`` is used by multiple models:
|
| 391 |
+
``<model list>``.
|
| 392 |
+
* **models.W036**: ``<database>`` does not support unique constraints with
|
| 393 |
+
conditions.
|
| 394 |
+
* **models.W037**: ``<database>`` does not support indexes with conditions.
|
| 395 |
+
* **models.W038**: ``<database>`` does not support deferrable unique
|
| 396 |
+
constraints.
|
| 397 |
+
* **models.W039**: ``<database>`` does not support unique constraints with
|
| 398 |
+
non-key columns.
|
| 399 |
+
* **models.W040**: ``<database>`` does not support indexes with non-key
|
| 400 |
+
columns.
|
| 401 |
+
* **models.E041**: ``constraints`` refers to the joined field ``<field name>``.
|
| 402 |
+
* **models.W042**: Auto-created primary key used when not defining a primary
|
| 403 |
+
key type, by default ``django.db.models.AutoField``.
|
| 404 |
+
* **models.W043**: ``<database>`` does not support indexes on expressions.
|
| 405 |
+
* **models.W044**: ``<database>`` does not support unique constraints on
|
| 406 |
+
expressions.
|
| 407 |
+
* **models.W045**: Check constraint ``<constraint>`` contains ``RawSQL()``
|
| 408 |
+
expression and won't be validated during the model ``full_clean()``.
|
| 409 |
+
* **models.W046**: ``<database>`` does not support comments on tables
|
| 410 |
+
(``db_table_comment``).
|
| 411 |
+
|
| 412 |
+
Security
|
| 413 |
+
--------
|
| 414 |
+
|
| 415 |
+
The security checks do not make your site secure. They do not audit code, do
|
| 416 |
+
intrusion detection, or do anything particularly complex. Rather, they help
|
| 417 |
+
perform an automated, low-hanging-fruit checklist, that can help you to improve
|
| 418 |
+
your site's security.
|
| 419 |
+
|
| 420 |
+
Some of these checks may not be appropriate for your particular deployment
|
| 421 |
+
configuration. For instance, if you do your HTTP to HTTPS redirection in a load
|
| 422 |
+
balancer, it'd be irritating to be constantly warned about not having enabled
|
| 423 |
+
:setting:`SECURE_SSL_REDIRECT`. Use :setting:`SILENCED_SYSTEM_CHECKS` to
|
| 424 |
+
silence unneeded checks.
|
| 425 |
+
|
| 426 |
+
The following checks are run if you use the :option:`check --deploy` option:
|
| 427 |
+
|
| 428 |
+
* **security.W001**: You do not have
|
| 429 |
+
:class:`django.middleware.security.SecurityMiddleware` in your
|
| 430 |
+
:setting:`MIDDLEWARE` so the :setting:`SECURE_HSTS_SECONDS`,
|
| 431 |
+
:setting:`SECURE_CONTENT_TYPE_NOSNIFF`, :setting:`SECURE_REFERRER_POLICY`,
|
| 432 |
+
:setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY`, and
|
| 433 |
+
:setting:`SECURE_SSL_REDIRECT` settings will have no effect.
|
| 434 |
+
* **security.W002**: You do not have
|
| 435 |
+
:class:`django.middleware.clickjacking.XFrameOptionsMiddleware` in your
|
| 436 |
+
:setting:`MIDDLEWARE`, so your pages will not be served with an
|
| 437 |
+
``'x-frame-options'`` header. Unless there is a good reason for your
|
| 438 |
+
site to be served in a frame, you should consider enabling this
|
| 439 |
+
header to help prevent clickjacking attacks.
|
| 440 |
+
* **security.W003**: You don't appear to be using Django's built-in cross-site
|
| 441 |
+
request forgery protection via the middleware
|
| 442 |
+
(:class:`django.middleware.csrf.CsrfViewMiddleware` is not in your
|
| 443 |
+
:setting:`MIDDLEWARE`). Enabling the middleware is the safest
|
| 444 |
+
approach to ensure you don't leave any holes.
|
| 445 |
+
* **security.W004**: You have not set a value for the
|
| 446 |
+
:setting:`SECURE_HSTS_SECONDS` setting. If your entire site is served only
|
| 447 |
+
over SSL, you may want to consider setting a value and enabling :ref:`HTTP
|
| 448 |
+
Strict Transport Security <http-strict-transport-security>`. Be sure to read
|
| 449 |
+
the documentation first; enabling HSTS carelessly can cause serious,
|
| 450 |
+
irreversible problems.
|
| 451 |
+
* **security.W005**: You have not set the
|
| 452 |
+
:setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this,
|
| 453 |
+
your site is potentially vulnerable to attack via an insecure connection to a
|
| 454 |
+
subdomain. Only set this to ``True`` if you are certain that all subdomains of
|
| 455 |
+
your domain should be served exclusively via SSL.
|
| 456 |
+
* **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not
|
| 457 |
+
set to ``True``, so your pages will not be served with an
|
| 458 |
+
``'X-Content-Type-Options: nosniff'`` header. You should consider enabling
|
| 459 |
+
this header to prevent the browser from identifying content types incorrectly.
|
| 460 |
+
* **security.W007**: Your ``SECURE_BROWSER_XSS_FILTER`` setting is not
|
| 461 |
+
set to ``True``, so your pages will not be served with an
|
| 462 |
+
``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling
|
| 463 |
+
this header to activate the browser's XSS filtering and help prevent XSS
|
| 464 |
+
attacks. *This check is removed in Django 3.0 as the* ``X-XSS-Protection``
|
| 465 |
+
*header is no longer honored by modern browsers.*
|
| 466 |
+
* **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to
|
| 467 |
+
``True``. Unless your site should be available over both SSL and non-SSL
|
| 468 |
+
connections, you may want to either set this setting to ``True`` or configure
|
| 469 |
+
a load balancer or reverse-proxy server to redirect all connections to HTTPS.
|
| 470 |
+
* **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters,
|
| 471 |
+
less than 5 unique characters, or it's prefixed with ``'django-insecure-'``
|
| 472 |
+
indicating that it was generated automatically by Django. Please generate a
|
| 473 |
+
long and random value, otherwise many of Django's security-critical features
|
| 474 |
+
will be vulnerable to attack.
|
| 475 |
+
* **security.W010**: You have :mod:`django.contrib.sessions` in your
|
| 476 |
+
:setting:`INSTALLED_APPS` but you have not set
|
| 477 |
+
:setting:`SESSION_COOKIE_SECURE` to ``True``. Using a secure-only session
|
| 478 |
+
cookie makes it more difficult for network traffic sniffers to hijack user
|
| 479 |
+
sessions.
|
| 480 |
+
* **security.W011**: You have
|
| 481 |
+
:class:`django.contrib.sessions.middleware.SessionMiddleware` in your
|
| 482 |
+
:setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_SECURE`
|
| 483 |
+
to ``True``. Using a secure-only session cookie makes it more difficult for
|
| 484 |
+
network traffic sniffers to hijack user sessions.
|
| 485 |
+
* **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``.
|
| 486 |
+
Using a secure-only session cookie makes it more difficult for network traffic
|
| 487 |
+
sniffers to hijack user sessions.
|
| 488 |
+
* **security.W013**: You have :mod:`django.contrib.sessions` in your
|
| 489 |
+
:setting:`INSTALLED_APPS`, but you have not set
|
| 490 |
+
:setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session
|
| 491 |
+
cookie makes it more difficult for cross-site scripting attacks to hijack user
|
| 492 |
+
sessions.
|
| 493 |
+
* **security.W014**: You have
|
| 494 |
+
:class:`django.contrib.sessions.middleware.SessionMiddleware` in your
|
| 495 |
+
:setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY`
|
| 496 |
+
to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for
|
| 497 |
+
cross-site scripting attacks to hijack user sessions.
|
| 498 |
+
* **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``.
|
| 499 |
+
Using an ``HttpOnly`` session cookie makes it more difficult for cross-site
|
| 500 |
+
scripting attacks to hijack user sessions.
|
| 501 |
+
* **security.W016**: :setting:`CSRF_COOKIE_SECURE` is not set to ``True``.
|
| 502 |
+
Using a secure-only CSRF cookie makes it more difficult for network traffic
|
| 503 |
+
sniffers to steal the CSRF token.
|
| 504 |
+
* **security.W017**: :setting:`CSRF_COOKIE_HTTPONLY` is not set to ``True``.
|
| 505 |
+
Using an ``HttpOnly`` CSRF cookie makes it more difficult for cross-site
|
| 506 |
+
scripting attacks to steal the CSRF token. *This check is removed in Django
|
| 507 |
+
1.11 as the* :setting:`CSRF_COOKIE_HTTPONLY` *setting offers no practical
|
| 508 |
+
benefit.*
|
| 509 |
+
* **security.W018**: You should not have :setting:`DEBUG` set to ``True`` in
|
| 510 |
+
deployment.
|
| 511 |
+
* **security.W019**: You have
|
| 512 |
+
:class:`django.middleware.clickjacking.XFrameOptionsMiddleware` in your
|
| 513 |
+
:setting:`MIDDLEWARE`, but :setting:`X_FRAME_OPTIONS` is not set to
|
| 514 |
+
``'DENY'``. Unless there is a good reason for your site to serve other parts
|
| 515 |
+
of itself in a frame, you should change it to ``'DENY'``.
|
| 516 |
+
* **security.W020**: :setting:`ALLOWED_HOSTS` must not be empty in deployment.
|
| 517 |
+
* **security.W021**: You have not set the
|
| 518 |
+
:setting:`SECURE_HSTS_PRELOAD` setting to ``True``. Without this, your site
|
| 519 |
+
cannot be submitted to the browser preload list.
|
| 520 |
+
* **security.W022**: You have not set the :setting:`SECURE_REFERRER_POLICY`
|
| 521 |
+
setting. Without this, your site will not send a Referrer-Policy header. You
|
| 522 |
+
should consider enabling this header to protect user privacy.
|
| 523 |
+
* **security.E023**: You have set the :setting:`SECURE_REFERRER_POLICY` setting
|
| 524 |
+
to an invalid value.
|
| 525 |
+
* **security.E024**: You have set the
|
| 526 |
+
:setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` setting to an invalid value.
|
| 527 |
+
* **security.W025**: Your
|
| 528 |
+
:setting:`SECRET_KEY_FALLBACKS[n] <SECRET_KEY_FALLBACKS>` has less than 50
|
| 529 |
+
characters, less than 5 unique characters, or it's prefixed with
|
| 530 |
+
``'django-insecure-'`` indicating that it was generated automatically by
|
| 531 |
+
Django. Please generate a long and random value, otherwise many of Django's
|
| 532 |
+
security-critical features will be vulnerable to attack.
|
| 533 |
+
|
| 534 |
+
The following checks verify that your security-related settings are correctly
|
| 535 |
+
configured:
|
| 536 |
+
|
| 537 |
+
* **security.E100**: ``DEFAULT_HASHING_ALGORITHM`` must be ``'sha1'`` or
|
| 538 |
+
``'sha256'``. *This check appeared in Django 3.1 and 3.2*.
|
| 539 |
+
* **security.E101**: The CSRF failure view ``'path.to.view'`` does not take the
|
| 540 |
+
correct number of arguments.
|
| 541 |
+
* **security.E102**: The CSRF failure view ``'path.to.view'`` could not be
|
| 542 |
+
imported.
|
| 543 |
+
|
| 544 |
+
Signals
|
| 545 |
+
-------
|
| 546 |
+
|
| 547 |
+
* **signals.E001**: ``<handler>`` was connected to the ``<signal>`` signal with
|
| 548 |
+
a lazy reference to the sender ``<app label>.<model>``, but app ``<app label>``
|
| 549 |
+
isn't installed or doesn't provide model ``<model>``.
|
| 550 |
+
|
| 551 |
+
Templates
|
| 552 |
+
---------
|
| 553 |
+
|
| 554 |
+
The following checks verify that your :setting:`TEMPLATES` setting is correctly
|
| 555 |
+
configured:
|
| 556 |
+
|
| 557 |
+
* **templates.E001**: You have ``'APP_DIRS': True`` in your
|
| 558 |
+
:setting:`TEMPLATES` but also specify ``'loaders'`` in ``OPTIONS``. Either
|
| 559 |
+
remove ``APP_DIRS`` or remove the ``'loaders'`` option.
|
| 560 |
+
* **templates.E002**: ``string_if_invalid`` in :setting:`TEMPLATES`
|
| 561 |
+
:setting:`OPTIONS <TEMPLATES-OPTIONS>` must be a string but got: ``{value}``
|
| 562 |
+
(``{type}``).
|
| 563 |
+
* **templates.E003**:``<name>`` is used for multiple template tag modules:
|
| 564 |
+
``<module list>``. *This check was changed to* ``templates.W003`` *in Django
|
| 565 |
+
4.1.2*.
|
| 566 |
+
* **templates.W003**:``<name>`` is used for multiple template tag modules:
|
| 567 |
+
``<module list>``.
|
| 568 |
+
|
| 569 |
+
Translation
|
| 570 |
+
-----------
|
| 571 |
+
|
| 572 |
+
The following checks are performed on your translation configuration:
|
| 573 |
+
|
| 574 |
+
* **translation.E001**: You have provided an invalid value for the
|
| 575 |
+
:setting:`LANGUAGE_CODE` setting: ``<value>``.
|
| 576 |
+
* **translation.E002**: You have provided an invalid language code in the
|
| 577 |
+
:setting:`LANGUAGES` setting: ``<value>``.
|
| 578 |
+
* **translation.E003**: You have provided an invalid language code in the
|
| 579 |
+
:setting:`LANGUAGES_BIDI` setting: ``<value>``.
|
| 580 |
+
* **translation.E004**: You have provided a value for the
|
| 581 |
+
:setting:`LANGUAGE_CODE` setting that is not in the :setting:`LANGUAGES`
|
| 582 |
+
setting.
|
| 583 |
+
|
| 584 |
+
URLs
|
| 585 |
+
----
|
| 586 |
+
|
| 587 |
+
The following checks are performed on your URL configuration:
|
| 588 |
+
|
| 589 |
+
* **urls.W001**: Your URL pattern ``<pattern>`` uses
|
| 590 |
+
:func:`~django.urls.include` with a ``route`` ending with a ``$``. Remove the
|
| 591 |
+
dollar from the ``route`` to avoid problems including URLs.
|
| 592 |
+
* **urls.W002**: Your URL pattern ``<pattern>`` has a ``route`` beginning with
|
| 593 |
+
a ``/``. Remove this slash as it is unnecessary. If this pattern is targeted
|
| 594 |
+
in an :func:`~django.urls.include`, ensure the :func:`~django.urls.include`
|
| 595 |
+
pattern has a trailing ``/``.
|
| 596 |
+
* **urls.W003**: Your URL pattern ``<pattern>`` has a ``name``
|
| 597 |
+
including a ``:``. Remove the colon, to avoid ambiguous namespace
|
| 598 |
+
references.
|
| 599 |
+
* **urls.E004**: Your URL pattern ``<pattern>`` is invalid. Ensure that
|
| 600 |
+
``urlpatterns`` is a list of :func:`~django.urls.path` and/or
|
| 601 |
+
:func:`~django.urls.re_path` instances.
|
| 602 |
+
* **urls.W005**: URL namespace ``<namespace>`` isn't unique. You may not be
|
| 603 |
+
able to reverse all URLs in this namespace.
|
| 604 |
+
* **urls.E006**: The :setting:`MEDIA_URL`/ :setting:`STATIC_URL` setting must
|
| 605 |
+
end with a slash.
|
| 606 |
+
* **urls.E007**: The custom ``handlerXXX`` view ``'path.to.view'`` does not
|
| 607 |
+
take the correct number of arguments (…).
|
| 608 |
+
* **urls.E008**: The custom ``handlerXXX`` view ``'path.to.view'`` could not be
|
| 609 |
+
imported.
|
| 610 |
+
* **urls.E009**: Your URL pattern ``<pattern>`` has an invalid view, pass
|
| 611 |
+
``<view>.as_view()`` instead of ``<view>``.
|
| 612 |
+
|
| 613 |
+
``contrib`` app checks
|
| 614 |
+
======================
|
| 615 |
+
|
| 616 |
+
``admin``
|
| 617 |
+
---------
|
| 618 |
+
|
| 619 |
+
Admin checks are all performed as part of the ``admin`` tag.
|
| 620 |
+
|
| 621 |
+
The following checks are performed on any
|
| 622 |
+
:class:`~django.contrib.admin.ModelAdmin` (or subclass) that is registered
|
| 623 |
+
with the admin site:
|
| 624 |
+
|
| 625 |
+
* **admin.E001**: The value of ``raw_id_fields`` must be a list or tuple.
|
| 626 |
+
* **admin.E002**: The value of ``raw_id_fields[n]`` refers to ``<field name>``,
|
| 627 |
+
which is not a field of ``<model>``.
|
| 628 |
+
* **admin.E003**: The value of ``raw_id_fields[n]`` must be a foreign key or
|
| 629 |
+
a many-to-many field.
|
| 630 |
+
* **admin.E004**: The value of ``fields`` must be a list or tuple.
|
| 631 |
+
* **admin.E005**: Both ``fieldsets`` and ``fields`` are specified.
|
| 632 |
+
* **admin.E006**: The value of ``fields`` contains duplicate field(s).
|
| 633 |
+
* **admin.E007**: The value of ``fieldsets`` must be a list or tuple.
|
| 634 |
+
* **admin.E008**: The value of ``fieldsets[n]`` must be a list or tuple.
|
| 635 |
+
* **admin.E009**: The value of ``fieldsets[n]`` must be of length 2.
|
| 636 |
+
* **admin.E010**: The value of ``fieldsets[n][1]`` must be a dictionary.
|
| 637 |
+
* **admin.E011**: The value of ``fieldsets[n][1]`` must contain the key
|
| 638 |
+
``fields``.
|
| 639 |
+
* **admin.E012**: There are duplicate field(s) in ``fieldsets[n][1]``.
|
| 640 |
+
* **admin.E013**: The value of
|
| 641 |
+
``fields[n]/filter_horizontal[n]/filter_vertical[n]/fieldsets[n][m]`` cannot
|
| 642 |
+
include the ``ManyToManyField`` ``<field name>``, because that field manually
|
| 643 |
+
specifies a relationship model.
|
| 644 |
+
* **admin.E014**: The value of ``exclude`` must be a list or tuple.
|
| 645 |
+
* **admin.E015**: The value of ``exclude`` contains duplicate field(s).
|
| 646 |
+
* **admin.E016**: The value of ``form`` must inherit from ``BaseModelForm``.
|
| 647 |
+
* **admin.E017**: The value of ``filter_vertical`` must be a list or tuple.
|
| 648 |
+
* **admin.E018**: The value of ``filter_horizontal`` must be a list or tuple.
|
| 649 |
+
* **admin.E019**: The value of ``filter_vertical[n]/filter_horizontal[n]``
|
| 650 |
+
refers to ``<field name>``, which is not a field of ``<model>``.
|
| 651 |
+
* **admin.E020**: The value of ``filter_vertical[n]/filter_horizontal[n]``
|
| 652 |
+
must be a many-to-many field.
|
| 653 |
+
* **admin.E021**: The value of ``radio_fields`` must be a dictionary.
|
| 654 |
+
* **admin.E022**: The value of ``radio_fields`` refers to ``<field name>``,
|
| 655 |
+
which is not a field of ``<model>``.
|
| 656 |
+
* **admin.E023**: The value of ``radio_fields`` refers to ``<field name>``,
|
| 657 |
+
which is not an instance of ``ForeignKey``, and does not have a ``choices``
|
| 658 |
+
definition.
|
| 659 |
+
* **admin.E024**: The value of ``radio_fields[<field name>]`` must be either
|
| 660 |
+
``admin.HORIZONTAL`` or ``admin.VERTICAL``.
|
| 661 |
+
* **admin.E025**: The value of ``view_on_site`` must be either a callable or a
|
| 662 |
+
boolean value.
|
| 663 |
+
* **admin.E026**: The value of ``prepopulated_fields`` must be a dictionary.
|
| 664 |
+
* **admin.E027**: The value of ``prepopulated_fields`` refers to
|
| 665 |
+
``<field name>``, which is not a field of ``<model>``.
|
| 666 |
+
* **admin.E028**: The value of ``prepopulated_fields`` refers to
|
| 667 |
+
``<field name>``, which must not be a ``DateTimeField``, a ``ForeignKey``,
|
| 668 |
+
a ``OneToOneField``, or a ``ManyToManyField`` field.
|
| 669 |
+
* **admin.E029**: The value of ``prepopulated_fields[<field name>]`` must be a
|
| 670 |
+
list or tuple.
|
| 671 |
+
* **admin.E030**: The value of ``prepopulated_fields`` refers to
|
| 672 |
+
``<field name>``, which is not a field of ``<model>``.
|
| 673 |
+
* **admin.E031**: The value of ``ordering`` must be a list or tuple.
|
| 674 |
+
* **admin.E032**: The value of ``ordering`` has the random ordering marker
|
| 675 |
+
``?``, but contains other fields as well.
|
| 676 |
+
* **admin.E033**: The value of ``ordering`` refers to ``<field name>``, which
|
| 677 |
+
is not a field of ``<model>``.
|
| 678 |
+
* **admin.E034**: The value of ``readonly_fields`` must be a list or tuple.
|
| 679 |
+
* **admin.E035**: The value of ``readonly_fields[n]`` refers to
|
| 680 |
+
``<field_name>``, which is not a callable, an attribute of
|
| 681 |
+
``<ModelAdmin class>``, or an attribute of ``<model>``.
|
| 682 |
+
* **admin.E036**: The value of ``autocomplete_fields`` must be a list or tuple.
|
| 683 |
+
* **admin.E037**: The value of ``autocomplete_fields[n]`` refers to
|
| 684 |
+
``<field name>``, which is not a field of ``<model>``.
|
| 685 |
+
* **admin.E038**: The value of ``autocomplete_fields[n]`` must be a foreign
|
| 686 |
+
key or a many-to-many field.
|
| 687 |
+
* **admin.E039**: An admin for model ``<model>`` has to be registered to be
|
| 688 |
+
referenced by ``<modeladmin>.autocomplete_fields``.
|
| 689 |
+
* **admin.E040**: ``<modeladmin>`` must define ``search_fields``, because
|
| 690 |
+
it's referenced by ``<other_modeladmin>.autocomplete_fields``.
|
| 691 |
+
|
| 692 |
+
``ModelAdmin``
|
| 693 |
+
~~~~~~~~~~~~~~
|
| 694 |
+
|
| 695 |
+
The following checks are performed on any
|
| 696 |
+
:class:`~django.contrib.admin.ModelAdmin` that is registered
|
| 697 |
+
with the admin site:
|
| 698 |
+
|
| 699 |
+
* **admin.E101**: The value of ``save_as`` must be a boolean.
|
| 700 |
+
* **admin.E102**: The value of ``save_on_top`` must be a boolean.
|
| 701 |
+
* **admin.E103**: The value of ``inlines`` must be a list or tuple.
|
| 702 |
+
* **admin.E104**: ``<InlineModelAdmin class>`` must inherit from
|
| 703 |
+
``InlineModelAdmin``.
|
| 704 |
+
* **admin.E105**: ``<InlineModelAdmin class>`` must have a ``model`` attribute.
|
| 705 |
+
* **admin.E106**: The value of ``<InlineModelAdmin class>.model`` must be a
|
| 706 |
+
``Model``.
|
| 707 |
+
* **admin.E107**: The value of ``list_display`` must be a list or tuple.
|
| 708 |
+
* **admin.E108**: The value of ``list_display[n]`` refers to ``<label>``,
|
| 709 |
+
which is not a callable, an attribute of ``<ModelAdmin class>``, or an
|
| 710 |
+
attribute or method on ``<model>``.
|
| 711 |
+
* **admin.E109**: The value of ``list_display[n]`` must not be a many-to-many
|
| 712 |
+
field or a reverse foreign key.
|
| 713 |
+
* **admin.E110**: The value of ``list_display_links`` must be a list, a tuple,
|
| 714 |
+
or ``None``.
|
| 715 |
+
* **admin.E111**: The value of ``list_display_links[n]`` refers to ``<label>``,
|
| 716 |
+
which is not defined in ``list_display``.
|
| 717 |
+
* **admin.E112**: The value of ``list_filter`` must be a list or tuple.
|
| 718 |
+
* **admin.E113**: The value of ``list_filter[n]`` must inherit from
|
| 719 |
+
``ListFilter``.
|
| 720 |
+
* **admin.E114**: The value of ``list_filter[n]`` must not inherit from
|
| 721 |
+
``FieldListFilter``.
|
| 722 |
+
* **admin.E115**: The value of ``list_filter[n][1]`` must inherit from
|
| 723 |
+
``FieldListFilter``.
|
| 724 |
+
* **admin.E116**: The value of ``list_filter[n]`` refers to ``<label>``,
|
| 725 |
+
which does not refer to a Field.
|
| 726 |
+
* **admin.E117**: The value of ``list_select_related`` must be a boolean,
|
| 727 |
+
tuple or list.
|
| 728 |
+
* **admin.E118**: The value of ``list_per_page`` must be an integer.
|
| 729 |
+
* **admin.E119**: The value of ``list_max_show_all`` must be an integer.
|
| 730 |
+
* **admin.E120**: The value of ``list_editable`` must be a list or tuple.
|
| 731 |
+
* **admin.E121**: The value of ``list_editable[n]`` refers to ``<label>``,
|
| 732 |
+
which is not a field of ``<model>``.
|
| 733 |
+
* **admin.E122**: The value of ``list_editable[n]`` refers to ``<label>``,
|
| 734 |
+
which is not contained in ``list_display``.
|
| 735 |
+
* **admin.E123**: The value of ``list_editable[n]`` cannot be in both
|
| 736 |
+
``list_editable`` and ``list_display_links``.
|
| 737 |
+
* **admin.E124**: The value of ``list_editable[n]`` refers to the first field
|
| 738 |
+
in ``list_display`` (``<label>``), which cannot be used unless
|
| 739 |
+
``list_display_links`` is set.
|
| 740 |
+
* **admin.E125**: The value of ``list_editable[n]`` refers to ``<field name>``,
|
| 741 |
+
which is not editable through the admin.
|
| 742 |
+
* **admin.E126**: The value of ``search_fields`` must be a list or tuple.
|
| 743 |
+
* **admin.E127**: The value of ``date_hierarchy`` refers to ``<field name>``,
|
| 744 |
+
which does not refer to a Field.
|
| 745 |
+
* **admin.E128**: The value of ``date_hierarchy`` must be a ``DateField`` or
|
| 746 |
+
``DateTimeField``.
|
| 747 |
+
* **admin.E129**: ``<modeladmin>`` must define a ``has_<foo>_permission()``
|
| 748 |
+
method for the ``<action>`` action.
|
| 749 |
+
* **admin.E130**: ``__name__`` attributes of actions defined in
|
| 750 |
+
``<modeladmin>`` must be unique. Name ``<name>`` is not unique.
|
| 751 |
+
|
| 752 |
+
``InlineModelAdmin``
|
| 753 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 754 |
+
|
| 755 |
+
The following checks are performed on any
|
| 756 |
+
:class:`~django.contrib.admin.InlineModelAdmin` that is registered as an
|
| 757 |
+
inline on a :class:`~django.contrib.admin.ModelAdmin`.
|
| 758 |
+
|
| 759 |
+
* **admin.E201**: Cannot exclude the field ``<field name>``, because it is the
|
| 760 |
+
foreign key to the parent model ``<app_label>.<model>``.
|
| 761 |
+
* **admin.E202**: ``<model>`` has no ``ForeignKey`` to ``<parent model>``./
|
| 762 |
+
``<model>`` has more than one ``ForeignKey`` to ``<parent model>``. You must
|
| 763 |
+
specify a ``fk_name`` attribute.
|
| 764 |
+
* **admin.E203**: The value of ``extra`` must be an integer.
|
| 765 |
+
* **admin.E204**: The value of ``max_num`` must be an integer.
|
| 766 |
+
* **admin.E205**: The value of ``min_num`` must be an integer.
|
| 767 |
+
* **admin.E206**: The value of ``formset`` must inherit from
|
| 768 |
+
``BaseModelFormSet``.
|
| 769 |
+
|
| 770 |
+
``GenericInlineModelAdmin``
|
| 771 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 772 |
+
|
| 773 |
+
The following checks are performed on any
|
| 774 |
+
:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin` that is
|
| 775 |
+
registered as an inline on a :class:`~django.contrib.admin.ModelAdmin`.
|
| 776 |
+
|
| 777 |
+
* **admin.E301**: ``'ct_field'`` references ``<label>``, which is not a field
|
| 778 |
+
on ``<model>``.
|
| 779 |
+
* **admin.E302**: ``'ct_fk_field'`` references ``<label>``, which is not a
|
| 780 |
+
field on ``<model>``.
|
| 781 |
+
* **admin.E303**: ``<model>`` has no ``GenericForeignKey``.
|
| 782 |
+
* **admin.E304**: ``<model>`` has no ``GenericForeignKey`` using content type
|
| 783 |
+
field ``<field name>`` and object ID field ``<field name>``.
|
| 784 |
+
|
| 785 |
+
``AdminSite``
|
| 786 |
+
~~~~~~~~~~~~~
|
| 787 |
+
|
| 788 |
+
The following checks are performed on the default
|
| 789 |
+
:class:`~django.contrib.admin.AdminSite`:
|
| 790 |
+
|
| 791 |
+
* **admin.E401**: :mod:`django.contrib.contenttypes` must be in
|
| 792 |
+
:setting:`INSTALLED_APPS` in order to use the admin application.
|
| 793 |
+
* **admin.E402**: :mod:`django.contrib.auth.context_processors.auth`
|
| 794 |
+
must be enabled in :class:`~django.template.backends.django.DjangoTemplates`
|
| 795 |
+
(:setting:`TEMPLATES`) if using the default auth backend in order to use the
|
| 796 |
+
admin application.
|
| 797 |
+
* **admin.E403**: A :class:`django.template.backends.django.DjangoTemplates`
|
| 798 |
+
instance must be configured in :setting:`TEMPLATES` in order to use the
|
| 799 |
+
admin application.
|
| 800 |
+
* **admin.E404**: ``django.contrib.messages.context_processors.messages``
|
| 801 |
+
must be enabled in :class:`~django.template.backends.django.DjangoTemplates`
|
| 802 |
+
(:setting:`TEMPLATES`) in order to use the admin application.
|
| 803 |
+
* **admin.E405**: :mod:`django.contrib.auth` must be in
|
| 804 |
+
:setting:`INSTALLED_APPS` in order to use the admin application.
|
| 805 |
+
* **admin.E406**: :mod:`django.contrib.messages` must be in
|
| 806 |
+
:setting:`INSTALLED_APPS` in order to use the admin application.
|
| 807 |
+
* **admin.E408**:
|
| 808 |
+
:class:`django.contrib.auth.middleware.AuthenticationMiddleware` must be in
|
| 809 |
+
:setting:`MIDDLEWARE` in order to use the admin application.
|
| 810 |
+
* **admin.E409**: :class:`django.contrib.messages.middleware.MessageMiddleware`
|
| 811 |
+
must be in :setting:`MIDDLEWARE` in order to use the admin application.
|
| 812 |
+
* **admin.E410**: :class:`django.contrib.sessions.middleware.SessionMiddleware`
|
| 813 |
+
must be in :setting:`MIDDLEWARE` in order to use the admin application.
|
| 814 |
+
* **admin.W411**: ``django.template.context_processors.request`` must be
|
| 815 |
+
enabled in :class:`~django.template.backends.django.DjangoTemplates`
|
| 816 |
+
(:setting:`TEMPLATES`) in order to use the admin navigation sidebar.
|
| 817 |
+
|
| 818 |
+
``auth``
|
| 819 |
+
--------
|
| 820 |
+
|
| 821 |
+
* **auth.E001**: ``REQUIRED_FIELDS`` must be a list or tuple.
|
| 822 |
+
* **auth.E002**: The field named as the ``USERNAME_FIELD`` for a custom user
|
| 823 |
+
model must not be included in ``REQUIRED_FIELDS``.
|
| 824 |
+
* **auth.E003**: ``<field>`` must be unique because it is named as the
|
| 825 |
+
``USERNAME_FIELD``.
|
| 826 |
+
* **auth.W004**: ``<field>`` is named as the ``USERNAME_FIELD``, but it is not
|
| 827 |
+
unique.
|
| 828 |
+
* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin
|
| 829 |
+
permission for model ``<model>``.
|
| 830 |
+
* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for model
|
| 831 |
+
``<model>``.
|
| 832 |
+
* **auth.E007**: The :attr:`verbose_name
|
| 833 |
+
<django.db.models.Options.verbose_name>` of model ``<model>`` must be at most
|
| 834 |
+
244 characters for its builtin permission names
|
| 835 |
+
to be at most 255 characters.
|
| 836 |
+
* **auth.E008**: The permission named ``<name>`` of model ``<model>`` is longer
|
| 837 |
+
than 255 characters.
|
| 838 |
+
* **auth.C009**: ``<User model>.is_anonymous`` must be an attribute or property
|
| 839 |
+
rather than a method. Ignoring this is a security issue as anonymous users
|
| 840 |
+
will be treated as authenticated!
|
| 841 |
+
* **auth.C010**: ``<User model>.is_authenticated`` must be an attribute or
|
| 842 |
+
property rather than a method. Ignoring this is a security issue as anonymous
|
| 843 |
+
users will be treated as authenticated!
|
| 844 |
+
* **auth.E011**: The name of model ``<model>`` must be at most 93 characters
|
| 845 |
+
for its builtin permission names to be at most 100 characters.
|
| 846 |
+
* **auth.E012**: The permission codenamed ``<codename>`` of model ``<model>``
|
| 847 |
+
is longer than 100 characters.
|
| 848 |
+
|
| 849 |
+
``contenttypes``
|
| 850 |
+
----------------
|
| 851 |
+
|
| 852 |
+
The following checks are performed when a model contains a
|
| 853 |
+
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` or
|
| 854 |
+
:class:`~django.contrib.contenttypes.fields.GenericRelation`:
|
| 855 |
+
|
| 856 |
+
* **contenttypes.E001**: The ``GenericForeignKey`` object ID references the
|
| 857 |
+
nonexistent field ``<field>``.
|
| 858 |
+
* **contenttypes.E002**: The ``GenericForeignKey`` content type references the
|
| 859 |
+
nonexistent field ``<field>``.
|
| 860 |
+
* **contenttypes.E003**: ``<field>`` is not a ``ForeignKey``.
|
| 861 |
+
* **contenttypes.E004**: ``<field>`` is not a ``ForeignKey`` to
|
| 862 |
+
``contenttypes.ContentType``.
|
| 863 |
+
* **contenttypes.E005**: Model names must be at most 100 characters.
|
| 864 |
+
|
| 865 |
+
``postgres``
|
| 866 |
+
------------
|
| 867 |
+
|
| 868 |
+
The following checks are performed on :mod:`django.contrib.postgres` model
|
| 869 |
+
fields:
|
| 870 |
+
|
| 871 |
+
* **postgres.E001**: Base field for array has errors: ...
|
| 872 |
+
* **postgres.E002**: Base field for array cannot be a related field.
|
| 873 |
+
* **postgres.E003**: ``<field>`` default should be a callable instead of an
|
| 874 |
+
instance so that it's not shared between all field instances. *This check was
|
| 875 |
+
changed to* ``fields.E010`` *in Django 3.1*.
|
| 876 |
+
* **postgres.W004**: Base field for array has warnings: ...
|
| 877 |
+
|
| 878 |
+
``sites``
|
| 879 |
+
---------
|
| 880 |
+
|
| 881 |
+
The following checks are performed on any model using a
|
| 882 |
+
:class:`~django.contrib.sites.managers.CurrentSiteManager`:
|
| 883 |
+
|
| 884 |
+
* **sites.E001**: ``CurrentSiteManager`` could not find a field named
|
| 885 |
+
``<field name>``.
|
| 886 |
+
* **sites.E002**: ``CurrentSiteManager`` cannot use ``<field>`` as it is not a
|
| 887 |
+
foreign key or a many-to-many field.
|
| 888 |
+
|
| 889 |
+
The following checks verify that :mod:`django.contrib.sites` is correctly
|
| 890 |
+
configured:
|
| 891 |
+
|
| 892 |
+
* **sites.E101**: The :setting:`SITE_ID` setting must be an integer.
|
| 893 |
+
|
| 894 |
+
``staticfiles``
|
| 895 |
+
---------------
|
| 896 |
+
|
| 897 |
+
The following checks verify that :mod:`django.contrib.staticfiles` is correctly
|
| 898 |
+
configured:
|
| 899 |
+
|
| 900 |
+
* **staticfiles.E001**: The :setting:`STATICFILES_DIRS` setting is not a tuple
|
| 901 |
+
or list.
|
| 902 |
+
* **staticfiles.E002**: The :setting:`STATICFILES_DIRS` setting should not
|
| 903 |
+
contain the :setting:`STATIC_ROOT` setting.
|
| 904 |
+
* **staticfiles.E003**: The prefix ``<prefix>`` in the
|
| 905 |
+
:setting:`STATICFILES_DIRS` setting must not end with a slash.
|
| 906 |
+
* **staticfiles.W004**: The directory ``<directory>`` in the
|
| 907 |
+
:setting:`STATICFILES_DIRS` does not exist.
|
testbed/django__django/docs/ref/clickjacking.txt
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
========================
|
| 2 |
+
Clickjacking Protection
|
| 3 |
+
========================
|
| 4 |
+
|
| 5 |
+
.. module:: django.middleware.clickjacking
|
| 6 |
+
:synopsis: Protects against Clickjacking
|
| 7 |
+
|
| 8 |
+
The clickjacking middleware and decorators provide easy-to-use protection
|
| 9 |
+
against `clickjacking`_. This type of attack occurs when a malicious site
|
| 10 |
+
tricks a user into clicking on a concealed element of another site which they
|
| 11 |
+
have loaded in a hidden frame or iframe.
|
| 12 |
+
|
| 13 |
+
.. _clickjacking: https://en.wikipedia.org/wiki/Clickjacking
|
| 14 |
+
|
| 15 |
+
An example of clickjacking
|
| 16 |
+
==========================
|
| 17 |
+
|
| 18 |
+
Suppose an online store has a page where a logged in user can click "Buy Now" to
|
| 19 |
+
purchase an item. A user has chosen to stay logged into the store all the time
|
| 20 |
+
for convenience. An attacker site might create an "I Like Ponies" button on one
|
| 21 |
+
of their own pages, and load the store's page in a transparent iframe such that
|
| 22 |
+
the "Buy Now" button is invisibly overlaid on the "I Like Ponies" button. If the
|
| 23 |
+
user visits the attacker's site, clicking "I Like Ponies" will cause an
|
| 24 |
+
inadvertent click on the "Buy Now" button and an unknowing purchase of the item.
|
| 25 |
+
|
| 26 |
+
.. _clickjacking-prevention:
|
| 27 |
+
|
| 28 |
+
Preventing clickjacking
|
| 29 |
+
=======================
|
| 30 |
+
|
| 31 |
+
Modern browsers honor the `X-Frame-Options`_ HTTP header that indicates whether
|
| 32 |
+
or not a resource is allowed to load within a frame or iframe. If the response
|
| 33 |
+
contains the header with a value of ``SAMEORIGIN`` then the browser will only
|
| 34 |
+
load the resource in a frame if the request originated from the same site. If
|
| 35 |
+
the header is set to ``DENY`` then the browser will block the resource from
|
| 36 |
+
loading in a frame no matter which site made the request.
|
| 37 |
+
|
| 38 |
+
.. _X-Frame-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
|
| 39 |
+
|
| 40 |
+
Django provides a few ways to include this header in responses from your site:
|
| 41 |
+
|
| 42 |
+
#. A middleware that sets the header in all responses.
|
| 43 |
+
|
| 44 |
+
#. A set of view decorators that can be used to override the middleware or to
|
| 45 |
+
only set the header for certain views.
|
| 46 |
+
|
| 47 |
+
The ``X-Frame-Options`` HTTP header will only be set by the middleware or view
|
| 48 |
+
decorators if it is not already present in the response.
|
| 49 |
+
|
| 50 |
+
How to use it
|
| 51 |
+
=============
|
| 52 |
+
|
| 53 |
+
Setting ``X-Frame-Options`` for all responses
|
| 54 |
+
---------------------------------------------
|
| 55 |
+
|
| 56 |
+
To set the same ``X-Frame-Options`` value for all responses in your site, put
|
| 57 |
+
``'django.middleware.clickjacking.XFrameOptionsMiddleware'`` to
|
| 58 |
+
:setting:`MIDDLEWARE`::
|
| 59 |
+
|
| 60 |
+
MIDDLEWARE = [
|
| 61 |
+
...,
|
| 62 |
+
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
| 63 |
+
...,
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
This middleware is enabled in the settings file generated by
|
| 67 |
+
:djadmin:`startproject`.
|
| 68 |
+
|
| 69 |
+
By default, the middleware will set the ``X-Frame-Options`` header to
|
| 70 |
+
``DENY`` for every outgoing ``HttpResponse``. If you want any other value for
|
| 71 |
+
this header instead, set the :setting:`X_FRAME_OPTIONS` setting::
|
| 72 |
+
|
| 73 |
+
X_FRAME_OPTIONS = "SAMEORIGIN"
|
| 74 |
+
|
| 75 |
+
When using the middleware there may be some views where you do **not** want the
|
| 76 |
+
``X-Frame-Options`` header set. For those cases, you can use a view decorator
|
| 77 |
+
that tells the middleware not to set the header::
|
| 78 |
+
|
| 79 |
+
from django.http import HttpResponse
|
| 80 |
+
from django.views.decorators.clickjacking import xframe_options_exempt
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@xframe_options_exempt
|
| 84 |
+
def ok_to_load_in_a_frame(request):
|
| 85 |
+
return HttpResponse("This page is safe to load in a frame on any site.")
|
| 86 |
+
|
| 87 |
+
.. note::
|
| 88 |
+
|
| 89 |
+
If you want to submit a form or access a session cookie within a frame or
|
| 90 |
+
iframe, you may need to modify the :setting:`CSRF_COOKIE_SAMESITE` or
|
| 91 |
+
:setting:`SESSION_COOKIE_SAMESITE` settings.
|
| 92 |
+
|
| 93 |
+
.. versionchanged:: 5.0
|
| 94 |
+
|
| 95 |
+
Support for wrapping asynchronous view functions was added to the
|
| 96 |
+
``@xframe_options_exempt`` decorator.
|
| 97 |
+
|
| 98 |
+
Setting ``X-Frame-Options`` per view
|
| 99 |
+
------------------------------------
|
| 100 |
+
|
| 101 |
+
To set the ``X-Frame-Options`` header on a per view basis, Django provides these
|
| 102 |
+
decorators::
|
| 103 |
+
|
| 104 |
+
from django.http import HttpResponse
|
| 105 |
+
from django.views.decorators.clickjacking import xframe_options_deny
|
| 106 |
+
from django.views.decorators.clickjacking import xframe_options_sameorigin
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@xframe_options_deny
|
| 110 |
+
def view_one(request):
|
| 111 |
+
return HttpResponse("I won't display in any frame!")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@xframe_options_sameorigin
|
| 115 |
+
def view_two(request):
|
| 116 |
+
return HttpResponse("Display in a frame if it's from the same origin as me.")
|
| 117 |
+
|
| 118 |
+
Note that you can use the decorators in conjunction with the middleware. Use of
|
| 119 |
+
a decorator overrides the middleware.
|
| 120 |
+
|
| 121 |
+
.. versionchanged:: 5.0
|
| 122 |
+
|
| 123 |
+
Support for wrapping asynchronous view functions was added to the
|
| 124 |
+
``@xframe_options_deny`` and ``@xframe_options_sameorigin`` decorators.
|
| 125 |
+
|
| 126 |
+
Limitations
|
| 127 |
+
===========
|
| 128 |
+
|
| 129 |
+
The ``X-Frame-Options`` header will only protect against clickjacking in a
|
| 130 |
+
modern browser. Older browsers will quietly ignore the header and need `other
|
| 131 |
+
clickjacking prevention techniques`_.
|
| 132 |
+
|
| 133 |
+
Browsers that support ``X-Frame-Options``
|
| 134 |
+
-----------------------------------------
|
| 135 |
+
|
| 136 |
+
* Internet Explorer 8+
|
| 137 |
+
* Edge
|
| 138 |
+
* Firefox 3.6.9+
|
| 139 |
+
* Opera 10.5+
|
| 140 |
+
* Safari 4+
|
| 141 |
+
* Chrome 4.1+
|
| 142 |
+
|
| 143 |
+
See also
|
| 144 |
+
--------
|
| 145 |
+
|
| 146 |
+
A `complete list`_ of browsers supporting ``X-Frame-Options``.
|
| 147 |
+
|
| 148 |
+
.. _complete list: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options#browser_compatibility
|
| 149 |
+
.. _other clickjacking prevention techniques: https://en.wikipedia.org/wiki/Clickjacking#Prevention
|
testbed/django__django/docs/ref/databases.txt
ADDED
|
@@ -0,0 +1,1193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=========
|
| 2 |
+
Databases
|
| 3 |
+
=========
|
| 4 |
+
|
| 5 |
+
Django officially supports the following databases:
|
| 6 |
+
|
| 7 |
+
* :ref:`PostgreSQL <postgresql-notes>`
|
| 8 |
+
* :ref:`MariaDB <mariadb-notes>`
|
| 9 |
+
* :ref:`MySQL <mysql-notes>`
|
| 10 |
+
* :ref:`Oracle <oracle-notes>`
|
| 11 |
+
* :ref:`SQLite <sqlite-notes>`
|
| 12 |
+
|
| 13 |
+
There are also a number of :ref:`database backends provided by third parties
|
| 14 |
+
<third-party-notes>`.
|
| 15 |
+
|
| 16 |
+
Django attempts to support as many features as possible on all database
|
| 17 |
+
backends. However, not all database backends are alike, and we've had to make
|
| 18 |
+
design decisions on which features to support and which assumptions we can make
|
| 19 |
+
safely.
|
| 20 |
+
|
| 21 |
+
This file describes some of the features that might be relevant to Django
|
| 22 |
+
usage. It is not intended as a replacement for server-specific documentation or
|
| 23 |
+
reference manuals.
|
| 24 |
+
|
| 25 |
+
General notes
|
| 26 |
+
=============
|
| 27 |
+
|
| 28 |
+
.. _persistent-database-connections:
|
| 29 |
+
|
| 30 |
+
Persistent connections
|
| 31 |
+
----------------------
|
| 32 |
+
|
| 33 |
+
Persistent connections avoid the overhead of reestablishing a connection to
|
| 34 |
+
the database in each HTTP request. They're controlled by the
|
| 35 |
+
:setting:`CONN_MAX_AGE` parameter which defines the maximum lifetime of a
|
| 36 |
+
connection. It can be set independently for each database.
|
| 37 |
+
|
| 38 |
+
The default value is ``0``, preserving the historical behavior of closing the
|
| 39 |
+
database connection at the end of each request. To enable persistent
|
| 40 |
+
connections, set :setting:`CONN_MAX_AGE` to a positive integer of seconds. For
|
| 41 |
+
unlimited persistent connections, set it to ``None``.
|
| 42 |
+
|
| 43 |
+
Connection management
|
| 44 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 45 |
+
|
| 46 |
+
Django opens a connection to the database when it first makes a database
|
| 47 |
+
query. It keeps this connection open and reuses it in subsequent requests.
|
| 48 |
+
Django closes the connection once it exceeds the maximum age defined by
|
| 49 |
+
:setting:`CONN_MAX_AGE` or when it isn't usable any longer.
|
| 50 |
+
|
| 51 |
+
In detail, Django automatically opens a connection to the database whenever it
|
| 52 |
+
needs one and doesn't have one already — either because this is the first
|
| 53 |
+
connection, or because the previous connection was closed.
|
| 54 |
+
|
| 55 |
+
At the beginning of each request, Django closes the connection if it has
|
| 56 |
+
reached its maximum age. If your database terminates idle connections after
|
| 57 |
+
some time, you should set :setting:`CONN_MAX_AGE` to a lower value, so that
|
| 58 |
+
Django doesn't attempt to use a connection that has been terminated by the
|
| 59 |
+
database server. (This problem may only affect very low traffic sites.)
|
| 60 |
+
|
| 61 |
+
At the end of each request, Django closes the connection if it has reached its
|
| 62 |
+
maximum age or if it is in an unrecoverable error state. If any database
|
| 63 |
+
errors have occurred while processing the requests, Django checks whether the
|
| 64 |
+
connection still works, and closes it if it doesn't. Thus, database errors
|
| 65 |
+
affect at most one request per each application's worker thread; if the
|
| 66 |
+
connection becomes unusable, the next request gets a fresh connection.
|
| 67 |
+
|
| 68 |
+
Setting :setting:`CONN_HEALTH_CHECKS` to ``True`` can be used to improve the
|
| 69 |
+
robustness of connection reuse and prevent errors when a connection has been
|
| 70 |
+
closed by the database server which is now ready to accept and serve new
|
| 71 |
+
connections, e.g. after database server restart. The health check is performed
|
| 72 |
+
only once per request and only if the database is being accessed during the
|
| 73 |
+
handling of the request.
|
| 74 |
+
|
| 75 |
+
Caveats
|
| 76 |
+
~~~~~~~
|
| 77 |
+
|
| 78 |
+
Since each thread maintains its own connection, your database must support at
|
| 79 |
+
least as many simultaneous connections as you have worker threads.
|
| 80 |
+
|
| 81 |
+
Sometimes a database won't be accessed by the majority of your views, for
|
| 82 |
+
example because it's the database of an external system, or thanks to caching.
|
| 83 |
+
In such cases, you should set :setting:`CONN_MAX_AGE` to a low value or even
|
| 84 |
+
``0``, because it doesn't make sense to maintain a connection that's unlikely
|
| 85 |
+
to be reused. This will help keep the number of simultaneous connections to
|
| 86 |
+
this database small.
|
| 87 |
+
|
| 88 |
+
The development server creates a new thread for each request it handles,
|
| 89 |
+
negating the effect of persistent connections. Don't enable them during
|
| 90 |
+
development.
|
| 91 |
+
|
| 92 |
+
When Django establishes a connection to the database, it sets up appropriate
|
| 93 |
+
parameters, depending on the backend being used. If you enable persistent
|
| 94 |
+
connections, this setup is no longer repeated every request. If you modify
|
| 95 |
+
parameters such as the connection's isolation level or time zone, you should
|
| 96 |
+
either restore Django's defaults at the end of each request, force an
|
| 97 |
+
appropriate value at the beginning of each request, or disable persistent
|
| 98 |
+
connections.
|
| 99 |
+
|
| 100 |
+
If a connection is created in a long-running process, outside of Django’s
|
| 101 |
+
request-response cycle, the connection will remain open until explicitly
|
| 102 |
+
closed, or timeout occurs.
|
| 103 |
+
|
| 104 |
+
Encoding
|
| 105 |
+
--------
|
| 106 |
+
|
| 107 |
+
Django assumes that all databases use UTF-8 encoding. Using other encodings may
|
| 108 |
+
result in unexpected behavior such as "value too long" errors from your
|
| 109 |
+
database for data that is valid in Django. See the database specific notes
|
| 110 |
+
below for information on how to set up your database correctly.
|
| 111 |
+
|
| 112 |
+
.. _postgresql-notes:
|
| 113 |
+
|
| 114 |
+
PostgreSQL notes
|
| 115 |
+
================
|
| 116 |
+
|
| 117 |
+
Django supports PostgreSQL 12 and higher. `psycopg`_ 3.1.8+ or `psycopg2`_
|
| 118 |
+
2.8.4+ is required, though the latest `psycopg`_ 3.1.8+ is recommended.
|
| 119 |
+
|
| 120 |
+
.. note::
|
| 121 |
+
|
| 122 |
+
Support for ``psycopg2`` is likely to be deprecated and removed at some
|
| 123 |
+
point in the future.
|
| 124 |
+
|
| 125 |
+
.. versionchanged:: 4.2
|
| 126 |
+
|
| 127 |
+
Support for ``psycopg`` 3.1.8+ was added.
|
| 128 |
+
|
| 129 |
+
.. _postgresql-connection-settings:
|
| 130 |
+
|
| 131 |
+
PostgreSQL connection settings
|
| 132 |
+
-------------------------------
|
| 133 |
+
|
| 134 |
+
See :setting:`HOST` for details.
|
| 135 |
+
|
| 136 |
+
To connect using a service name from the `connection service file`_ and a
|
| 137 |
+
password from the `password file`_, you must specify them in the
|
| 138 |
+
:setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`:
|
| 139 |
+
|
| 140 |
+
.. code-block:: python
|
| 141 |
+
:caption: ``settings.py``
|
| 142 |
+
|
| 143 |
+
DATABASES = {
|
| 144 |
+
"default": {
|
| 145 |
+
"ENGINE": "django.db.backends.postgresql",
|
| 146 |
+
"OPTIONS": {
|
| 147 |
+
"service": "my_service",
|
| 148 |
+
"passfile": ".my_pgpass",
|
| 149 |
+
},
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
.. code-block:: text
|
| 154 |
+
:caption: ``.pg_service.conf``
|
| 155 |
+
|
| 156 |
+
[my_service]
|
| 157 |
+
host=localhost
|
| 158 |
+
user=USER
|
| 159 |
+
dbname=NAME
|
| 160 |
+
port=5432
|
| 161 |
+
|
| 162 |
+
.. code-block:: text
|
| 163 |
+
:caption: ``.my_pgpass``
|
| 164 |
+
|
| 165 |
+
localhost:5432:NAME:USER:PASSWORD
|
| 166 |
+
|
| 167 |
+
.. _connection service file: https://www.postgresql.org/docs/current/libpq-pgservice.html
|
| 168 |
+
.. _password file: https://www.postgresql.org/docs/current/libpq-pgpass.html
|
| 169 |
+
|
| 170 |
+
.. warning::
|
| 171 |
+
|
| 172 |
+
Using a service name for testing purposes is not supported. This
|
| 173 |
+
:ticket:`may be implemented later <33685>`.
|
| 174 |
+
|
| 175 |
+
Optimizing PostgreSQL's configuration
|
| 176 |
+
-------------------------------------
|
| 177 |
+
|
| 178 |
+
Django needs the following parameters for its database connections:
|
| 179 |
+
|
| 180 |
+
- ``client_encoding``: ``'UTF8'``,
|
| 181 |
+
- ``default_transaction_isolation``: ``'read committed'`` by default,
|
| 182 |
+
or the value set in the connection options (see below),
|
| 183 |
+
- ``timezone``:
|
| 184 |
+
- when :setting:`USE_TZ` is ``True``, ``'UTC'`` by default, or the
|
| 185 |
+
:setting:`TIME_ZONE <DATABASE-TIME_ZONE>` value set for the connection,
|
| 186 |
+
- when :setting:`USE_TZ` is ``False``, the value of the global
|
| 187 |
+
:setting:`TIME_ZONE` setting.
|
| 188 |
+
|
| 189 |
+
If these parameters already have the correct values, Django won't set them for
|
| 190 |
+
every new connection, which improves performance slightly. You can configure
|
| 191 |
+
them directly in :file:`postgresql.conf` or more conveniently per database
|
| 192 |
+
user with `ALTER ROLE`_.
|
| 193 |
+
|
| 194 |
+
Django will work just fine without this optimization, but each new connection
|
| 195 |
+
will do some additional queries to set these parameters.
|
| 196 |
+
|
| 197 |
+
.. _ALTER ROLE: https://www.postgresql.org/docs/current/sql-alterrole.html
|
| 198 |
+
|
| 199 |
+
.. _database-isolation-level:
|
| 200 |
+
|
| 201 |
+
Isolation level
|
| 202 |
+
---------------
|
| 203 |
+
|
| 204 |
+
Like PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation
|
| 205 |
+
level`_. If you need a higher isolation level such as ``REPEATABLE READ`` or
|
| 206 |
+
``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database
|
| 207 |
+
configuration in :setting:`DATABASES`::
|
| 208 |
+
|
| 209 |
+
from django.db.backends.postgresql.psycopg_any import IsolationLevel
|
| 210 |
+
|
| 211 |
+
DATABASES = {
|
| 212 |
+
# ...
|
| 213 |
+
"OPTIONS": {
|
| 214 |
+
"isolation_level": IsolationLevel.SERIALIZABLE,
|
| 215 |
+
},
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
.. note::
|
| 219 |
+
|
| 220 |
+
Under higher isolation levels, your application should be prepared to
|
| 221 |
+
handle exceptions raised on serialization failures. This option is
|
| 222 |
+
designed for advanced uses.
|
| 223 |
+
|
| 224 |
+
.. _isolation level: https://www.postgresql.org/docs/current/transaction-iso.html
|
| 225 |
+
|
| 226 |
+
.. versionchanged:: 4.2
|
| 227 |
+
|
| 228 |
+
``IsolationLevel`` was added.
|
| 229 |
+
|
| 230 |
+
.. _database-role:
|
| 231 |
+
|
| 232 |
+
Role
|
| 233 |
+
----
|
| 234 |
+
|
| 235 |
+
.. versionadded:: 4.2
|
| 236 |
+
|
| 237 |
+
If you need to use a different role for database connections than the role use
|
| 238 |
+
to establish the connection, set it in the :setting:`OPTIONS` part of your
|
| 239 |
+
database configuration in :setting:`DATABASES`::
|
| 240 |
+
|
| 241 |
+
DATABASES = {
|
| 242 |
+
"default": {
|
| 243 |
+
"ENGINE": "django.db.backends.postgresql",
|
| 244 |
+
# ...
|
| 245 |
+
"OPTIONS": {
|
| 246 |
+
"assume_role": "my_application_role",
|
| 247 |
+
},
|
| 248 |
+
},
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
.. _database-server-side-parameters-binding:
|
| 252 |
+
|
| 253 |
+
Server-side parameters binding
|
| 254 |
+
------------------------------
|
| 255 |
+
|
| 256 |
+
.. versionadded:: 4.2
|
| 257 |
+
|
| 258 |
+
With `psycopg`_ 3.1.8+, Django defaults to the :ref:`client-side binding
|
| 259 |
+
cursors <psycopg:client-side-binding-cursors>`. If you want to use the
|
| 260 |
+
:ref:`server-side binding <psycopg:server-side-binding>` set it in the
|
| 261 |
+
:setting:`OPTIONS` part of your database configuration in
|
| 262 |
+
:setting:`DATABASES`::
|
| 263 |
+
|
| 264 |
+
DATABASES = {
|
| 265 |
+
"default": {
|
| 266 |
+
"ENGINE": "django.db.backends.postgresql",
|
| 267 |
+
# ...
|
| 268 |
+
"OPTIONS": {
|
| 269 |
+
"server_side_binding": True,
|
| 270 |
+
},
|
| 271 |
+
},
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
This option is ignored with ``psycopg2``.
|
| 275 |
+
|
| 276 |
+
Indexes for ``varchar`` and ``text`` columns
|
| 277 |
+
--------------------------------------------
|
| 278 |
+
|
| 279 |
+
When specifying ``db_index=True`` on your model fields, Django typically
|
| 280 |
+
outputs a single ``CREATE INDEX`` statement. However, if the database type
|
| 281 |
+
for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,
|
| 282 |
+
``FileField``, and ``TextField``), then Django will create
|
| 283 |
+
an additional index that uses an appropriate `PostgreSQL operator class`_
|
| 284 |
+
for the column. The extra index is necessary to correctly perform
|
| 285 |
+
lookups that use the ``LIKE`` operator in their SQL, as is done with the
|
| 286 |
+
``contains`` and ``startswith`` lookup types.
|
| 287 |
+
|
| 288 |
+
.. _PostgreSQL operator class: https://www.postgresql.org/docs/current/indexes-opclass.html
|
| 289 |
+
|
| 290 |
+
Migration operation for adding extensions
|
| 291 |
+
-----------------------------------------
|
| 292 |
+
|
| 293 |
+
If you need to add a PostgreSQL extension (like ``hstore``, ``postgis``, etc.)
|
| 294 |
+
using a migration, use the
|
| 295 |
+
:class:`~django.contrib.postgres.operations.CreateExtension` operation.
|
| 296 |
+
|
| 297 |
+
.. _postgresql-server-side-cursors:
|
| 298 |
+
|
| 299 |
+
Server-side cursors
|
| 300 |
+
-------------------
|
| 301 |
+
|
| 302 |
+
When using :meth:`QuerySet.iterator()
|
| 303 |
+
<django.db.models.query.QuerySet.iterator>`, Django opens a :ref:`server-side
|
| 304 |
+
cursor <psycopg:server-side-cursors>`. By default, PostgreSQL assumes that
|
| 305 |
+
only the first 10% of the results of cursor queries will be fetched. The query
|
| 306 |
+
planner spends less time planning the query and starts returning results
|
| 307 |
+
faster, but this could diminish performance if more than 10% of the results are
|
| 308 |
+
retrieved. PostgreSQL's assumptions on the number of rows retrieved for a
|
| 309 |
+
cursor query is controlled with the `cursor_tuple_fraction`_ option.
|
| 310 |
+
|
| 311 |
+
.. _cursor_tuple_fraction: https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-CURSOR-TUPLE-FRACTION
|
| 312 |
+
|
| 313 |
+
.. _transaction-pooling-server-side-cursors:
|
| 314 |
+
|
| 315 |
+
Transaction pooling and server-side cursors
|
| 316 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 317 |
+
|
| 318 |
+
Using a connection pooler in transaction pooling mode (e.g. `PgBouncer`_)
|
| 319 |
+
requires disabling server-side cursors for that connection.
|
| 320 |
+
|
| 321 |
+
Server-side cursors are local to a connection and remain open at the end of a
|
| 322 |
+
transaction when :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` is ``True``. A
|
| 323 |
+
subsequent transaction may attempt to fetch more results from a server-side
|
| 324 |
+
cursor. In transaction pooling mode, there's no guarantee that subsequent
|
| 325 |
+
transactions will use the same connection. If a different connection is used,
|
| 326 |
+
an error is raised when the transaction references the server-side cursor,
|
| 327 |
+
because server-side cursors are only accessible in the connection in which they
|
| 328 |
+
were created.
|
| 329 |
+
|
| 330 |
+
One solution is to disable server-side cursors for a connection in
|
| 331 |
+
:setting:`DATABASES` by setting :setting:`DISABLE_SERVER_SIDE_CURSORS
|
| 332 |
+
<DATABASE-DISABLE_SERVER_SIDE_CURSORS>` to ``True``.
|
| 333 |
+
|
| 334 |
+
To benefit from server-side cursors in transaction pooling mode, you could set
|
| 335 |
+
up :doc:`another connection to the database </topics/db/multi-db>` in order to
|
| 336 |
+
perform queries that use server-side cursors. This connection needs to either
|
| 337 |
+
be directly to the database or to a connection pooler in session pooling mode.
|
| 338 |
+
|
| 339 |
+
Another option is to wrap each ``QuerySet`` using server-side cursors in an
|
| 340 |
+
:func:`~django.db.transaction.atomic` block, because it disables ``autocommit``
|
| 341 |
+
for the duration of the transaction. This way, the server-side cursor will only
|
| 342 |
+
live for the duration of the transaction.
|
| 343 |
+
|
| 344 |
+
.. _PgBouncer: https://www.pgbouncer.org/
|
| 345 |
+
|
| 346 |
+
.. _manually-specified-autoincrement-pk:
|
| 347 |
+
|
| 348 |
+
Manually-specifying values of auto-incrementing primary keys
|
| 349 |
+
------------------------------------------------------------
|
| 350 |
+
|
| 351 |
+
Django uses PostgreSQL's identity columns to store auto-incrementing primary
|
| 352 |
+
keys. An identity column is populated with values from a `sequence`_ that keeps
|
| 353 |
+
track of the next available value. Manually assigning a value to an
|
| 354 |
+
auto-incrementing field doesn't update the field's sequence, which might later
|
| 355 |
+
cause a conflict. For example:
|
| 356 |
+
|
| 357 |
+
.. code-block:: pycon
|
| 358 |
+
|
| 359 |
+
>>> from django.contrib.auth.models import User
|
| 360 |
+
>>> User.objects.create(username="alice", pk=1)
|
| 361 |
+
<User: alice>
|
| 362 |
+
>>> # The sequence hasn't been updated; its next value is 1.
|
| 363 |
+
>>> User.objects.create(username="bob")
|
| 364 |
+
IntegrityError: duplicate key value violates unique constraint
|
| 365 |
+
"auth_user_pkey" DETAIL: Key (id)=(1) already exists.
|
| 366 |
+
|
| 367 |
+
If you need to specify such values, reset the sequence afterward to avoid
|
| 368 |
+
reusing a value that's already in the table. The :djadmin:`sqlsequencereset`
|
| 369 |
+
management command generates the SQL statements to do that.
|
| 370 |
+
|
| 371 |
+
.. _sequence: https://www.postgresql.org/docs/current/sql-createsequence.html
|
| 372 |
+
|
| 373 |
+
Test database templates
|
| 374 |
+
-----------------------
|
| 375 |
+
|
| 376 |
+
You can use the :setting:`TEST['TEMPLATE'] <TEST_TEMPLATE>` setting to specify
|
| 377 |
+
a `template`_ (e.g. ``'template0'``) from which to create a test database.
|
| 378 |
+
|
| 379 |
+
.. _template: https://www.postgresql.org/docs/current/sql-createdatabase.html
|
| 380 |
+
|
| 381 |
+
Speeding up test execution with non-durable settings
|
| 382 |
+
----------------------------------------------------
|
| 383 |
+
|
| 384 |
+
You can speed up test execution times by `configuring PostgreSQL to be
|
| 385 |
+
non-durable <https://www.postgresql.org/docs/current/non-durability.html>`_.
|
| 386 |
+
|
| 387 |
+
.. warning::
|
| 388 |
+
|
| 389 |
+
This is dangerous: it will make your database more susceptible to data loss
|
| 390 |
+
or corruption in the case of a server crash or power loss. Only use this on
|
| 391 |
+
a development machine where you can easily restore the entire contents of
|
| 392 |
+
all databases in the cluster.
|
| 393 |
+
|
| 394 |
+
.. _psycopg: https://www.psycopg.org/psycopg3/
|
| 395 |
+
.. _psycopg2: https://www.psycopg.org/
|
| 396 |
+
|
| 397 |
+
.. _mariadb-notes:
|
| 398 |
+
|
| 399 |
+
MariaDB notes
|
| 400 |
+
=============
|
| 401 |
+
|
| 402 |
+
Django supports MariaDB 10.4 and higher.
|
| 403 |
+
|
| 404 |
+
To use MariaDB, use the MySQL backend, which is shared between the two. See the
|
| 405 |
+
:ref:`MySQL notes <mysql-notes>` for more details.
|
| 406 |
+
|
| 407 |
+
.. _mysql-notes:
|
| 408 |
+
|
| 409 |
+
MySQL notes
|
| 410 |
+
===========
|
| 411 |
+
|
| 412 |
+
Version support
|
| 413 |
+
---------------
|
| 414 |
+
|
| 415 |
+
Django supports MySQL 8 and higher.
|
| 416 |
+
|
| 417 |
+
Django's ``inspectdb`` feature uses the ``information_schema`` database, which
|
| 418 |
+
contains detailed data on all database schemas.
|
| 419 |
+
|
| 420 |
+
Django expects the database to support Unicode (UTF-8 encoding) and delegates to
|
| 421 |
+
it the task of enforcing transactions and referential integrity. It is important
|
| 422 |
+
to be aware of the fact that the two latter ones aren't actually enforced by
|
| 423 |
+
MySQL when using the MyISAM storage engine, see the next section.
|
| 424 |
+
|
| 425 |
+
.. _mysql-storage-engines:
|
| 426 |
+
|
| 427 |
+
Storage engines
|
| 428 |
+
---------------
|
| 429 |
+
|
| 430 |
+
MySQL has several `storage engines`_. You can change the default storage engine
|
| 431 |
+
in the server configuration.
|
| 432 |
+
|
| 433 |
+
MySQL's default storage engine is InnoDB_. This engine is fully transactional
|
| 434 |
+
and supports foreign key references. It's the recommended choice. However, the
|
| 435 |
+
InnoDB autoincrement counter is lost on a MySQL restart because it does not
|
| 436 |
+
remember the ``AUTO_INCREMENT`` value, instead recreating it as "max(id)+1".
|
| 437 |
+
This may result in an inadvertent reuse of :class:`~django.db.models.AutoField`
|
| 438 |
+
values.
|
| 439 |
+
|
| 440 |
+
The main drawbacks of MyISAM_ are that it doesn't support transactions or
|
| 441 |
+
enforce foreign-key constraints.
|
| 442 |
+
|
| 443 |
+
.. _storage engines: https://dev.mysql.com/doc/refman/en/storage-engines.html
|
| 444 |
+
.. _MyISAM: https://dev.mysql.com/doc/refman/en/myisam-storage-engine.html
|
| 445 |
+
.. _InnoDB: https://dev.mysql.com/doc/refman/en/innodb-storage-engine.html
|
| 446 |
+
|
| 447 |
+
.. _mysql-db-api-drivers:
|
| 448 |
+
|
| 449 |
+
MySQL DB API Drivers
|
| 450 |
+
--------------------
|
| 451 |
+
|
| 452 |
+
MySQL has a couple drivers that implement the Python Database API described in
|
| 453 |
+
:pep:`249`:
|
| 454 |
+
|
| 455 |
+
- :pypi:`mysqlclient` is a native driver. It's **the recommended choice**.
|
| 456 |
+
- `MySQL Connector/Python`_ is a pure Python driver from Oracle that does not
|
| 457 |
+
require the MySQL client library or any Python modules outside the standard
|
| 458 |
+
library.
|
| 459 |
+
|
| 460 |
+
.. _MySQL Connector/Python: https://dev.mysql.com/downloads/connector/python/
|
| 461 |
+
|
| 462 |
+
These drivers are thread-safe and provide connection pooling.
|
| 463 |
+
|
| 464 |
+
In addition to a DB API driver, Django needs an adapter to access the database
|
| 465 |
+
drivers from its ORM. Django provides an adapter for mysqlclient while MySQL
|
| 466 |
+
Connector/Python includes `its own`_.
|
| 467 |
+
|
| 468 |
+
.. _its own: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html
|
| 469 |
+
|
| 470 |
+
mysqlclient
|
| 471 |
+
~~~~~~~~~~~
|
| 472 |
+
|
| 473 |
+
Django requires `mysqlclient`_ 1.4.3 or later.
|
| 474 |
+
|
| 475 |
+
MySQL Connector/Python
|
| 476 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 477 |
+
|
| 478 |
+
MySQL Connector/Python is available from the `download page`_.
|
| 479 |
+
The Django adapter is available in versions 1.1.X and later. It may not
|
| 480 |
+
support the most recent releases of Django.
|
| 481 |
+
|
| 482 |
+
.. _download page: https://dev.mysql.com/downloads/connector/python/
|
| 483 |
+
|
| 484 |
+
.. _mysql-time-zone-definitions:
|
| 485 |
+
|
| 486 |
+
Time zone definitions
|
| 487 |
+
---------------------
|
| 488 |
+
|
| 489 |
+
If you plan on using Django's :doc:`timezone support </topics/i18n/timezones>`,
|
| 490 |
+
use `mysql_tzinfo_to_sql`_ to load time zone tables into the MySQL database.
|
| 491 |
+
This needs to be done just once for your MySQL server, not per database.
|
| 492 |
+
|
| 493 |
+
.. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html
|
| 494 |
+
|
| 495 |
+
Creating your database
|
| 496 |
+
----------------------
|
| 497 |
+
|
| 498 |
+
You can `create your database`_ using the command-line tools and this SQL:
|
| 499 |
+
|
| 500 |
+
.. code-block:: sql
|
| 501 |
+
|
| 502 |
+
CREATE DATABASE <dbname> CHARACTER SET utf8;
|
| 503 |
+
|
| 504 |
+
This ensures all tables and columns will use UTF-8 by default.
|
| 505 |
+
|
| 506 |
+
.. _create your database: https://dev.mysql.com/doc/refman/en/create-database.html
|
| 507 |
+
|
| 508 |
+
.. _mysql-collation:
|
| 509 |
+
|
| 510 |
+
Collation settings
|
| 511 |
+
~~~~~~~~~~~~~~~~~~
|
| 512 |
+
|
| 513 |
+
The collation setting for a column controls the order in which data is sorted
|
| 514 |
+
as well as what strings compare as equal. You can specify the ``db_collation``
|
| 515 |
+
parameter to set the collation name of the column for
|
| 516 |
+
:attr:`CharField <django.db.models.CharField.db_collation>` and
|
| 517 |
+
:attr:`TextField <django.db.models.TextField.db_collation>`.
|
| 518 |
+
|
| 519 |
+
The collation can also be set on a database-wide level and per-table. This is
|
| 520 |
+
`documented thoroughly`_ in the MySQL documentation. In such cases, you must
|
| 521 |
+
set the collation by directly manipulating the database settings or tables.
|
| 522 |
+
Django doesn't provide an API to change them.
|
| 523 |
+
|
| 524 |
+
.. _documented thoroughly: https://dev.mysql.com/doc/refman/en/charset.html
|
| 525 |
+
|
| 526 |
+
By default, with a UTF-8 database, MySQL will use the
|
| 527 |
+
``utf8_general_ci`` collation. This results in all string equality
|
| 528 |
+
comparisons being done in a *case-insensitive* manner. That is, ``"Fred"`` and
|
| 529 |
+
``"freD"`` are considered equal at the database level. If you have a unique
|
| 530 |
+
constraint on a field, it would be illegal to try to insert both ``"aa"`` and
|
| 531 |
+
``"AA"`` into the same column, since they compare as equal (and, hence,
|
| 532 |
+
non-unique) with the default collation. If you want case-sensitive comparisons
|
| 533 |
+
on a particular column or table, change the column or table to use the
|
| 534 |
+
``utf8_bin`` collation.
|
| 535 |
+
|
| 536 |
+
Please note that according to `MySQL Unicode Character Sets`_, comparisons for
|
| 537 |
+
the ``utf8_general_ci`` collation are faster, but slightly less correct, than
|
| 538 |
+
comparisons for ``utf8_unicode_ci``. If this is acceptable for your application,
|
| 539 |
+
you should use ``utf8_general_ci`` because it is faster. If this is not acceptable
|
| 540 |
+
(for example, if you require German dictionary order), use ``utf8_unicode_ci``
|
| 541 |
+
because it is more accurate.
|
| 542 |
+
|
| 543 |
+
.. _MySQL Unicode Character Sets: https://dev.mysql.com/doc/refman/en/charset-unicode-sets.html
|
| 544 |
+
|
| 545 |
+
.. warning::
|
| 546 |
+
|
| 547 |
+
Model formsets validate unique fields in a case-sensitive manner. Thus when
|
| 548 |
+
using a case-insensitive collation, a formset with unique field values that
|
| 549 |
+
differ only by case will pass validation, but upon calling ``save()``, an
|
| 550 |
+
``IntegrityError`` will be raised.
|
| 551 |
+
|
| 552 |
+
Connecting to the database
|
| 553 |
+
--------------------------
|
| 554 |
+
|
| 555 |
+
Refer to the :doc:`settings documentation </ref/settings>`.
|
| 556 |
+
|
| 557 |
+
Connection settings are used in this order:
|
| 558 |
+
|
| 559 |
+
#. :setting:`OPTIONS`.
|
| 560 |
+
#. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`, :setting:`HOST`,
|
| 561 |
+
:setting:`PORT`
|
| 562 |
+
#. MySQL option files.
|
| 563 |
+
|
| 564 |
+
In other words, if you set the name of the database in :setting:`OPTIONS`,
|
| 565 |
+
this will take precedence over :setting:`NAME`, which would override
|
| 566 |
+
anything in a `MySQL option file`_.
|
| 567 |
+
|
| 568 |
+
Here's a sample configuration which uses a MySQL option file::
|
| 569 |
+
|
| 570 |
+
# settings.py
|
| 571 |
+
DATABASES = {
|
| 572 |
+
"default": {
|
| 573 |
+
"ENGINE": "django.db.backends.mysql",
|
| 574 |
+
"OPTIONS": {
|
| 575 |
+
"read_default_file": "/path/to/my.cnf",
|
| 576 |
+
},
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
.. code-block:: ini
|
| 581 |
+
|
| 582 |
+
# my.cnf
|
| 583 |
+
[client]
|
| 584 |
+
database = NAME
|
| 585 |
+
user = USER
|
| 586 |
+
password = PASSWORD
|
| 587 |
+
default-character-set = utf8
|
| 588 |
+
|
| 589 |
+
Several other `MySQLdb connection options`_ may be useful, such as ``ssl``,
|
| 590 |
+
``init_command``, and ``sql_mode``.
|
| 591 |
+
|
| 592 |
+
.. _MySQL option file: https://dev.mysql.com/doc/refman/en/option-files.html
|
| 593 |
+
.. _MySQLdb connection options: https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes
|
| 594 |
+
|
| 595 |
+
.. _mysql-sql-mode:
|
| 596 |
+
|
| 597 |
+
Setting ``sql_mode``
|
| 598 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 599 |
+
|
| 600 |
+
The default value of the ``sql_mode`` option contains ``STRICT_TRANS_TABLES``.
|
| 601 |
+
That option escalates warnings into errors when data are truncated upon
|
| 602 |
+
insertion, so Django highly recommends activating a `strict mode`_ for MySQL to
|
| 603 |
+
prevent data loss (either ``STRICT_TRANS_TABLES`` or ``STRICT_ALL_TABLES``).
|
| 604 |
+
|
| 605 |
+
.. _strict mode: https://dev.mysql.com/doc/refman/en/sql-mode.html#sql-mode-strict
|
| 606 |
+
|
| 607 |
+
If you need to customize the SQL mode, you can set the ``sql_mode`` variable
|
| 608 |
+
like other MySQL options: either in a config file or with the entry
|
| 609 |
+
``'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"`` in the
|
| 610 |
+
:setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`.
|
| 611 |
+
|
| 612 |
+
.. _mysql-isolation-level:
|
| 613 |
+
|
| 614 |
+
Isolation level
|
| 615 |
+
~~~~~~~~~~~~~~~
|
| 616 |
+
|
| 617 |
+
When running concurrent loads, database transactions from different sessions
|
| 618 |
+
(say, separate threads handling different requests) may interact with each
|
| 619 |
+
other. These interactions are affected by each session's `transaction isolation
|
| 620 |
+
level`_. You can set a connection's isolation level with an
|
| 621 |
+
``'isolation_level'`` entry in the :setting:`OPTIONS` part of your database
|
| 622 |
+
configuration in :setting:`DATABASES`. Valid values for
|
| 623 |
+
this entry are the four standard isolation levels:
|
| 624 |
+
|
| 625 |
+
* ``'read uncommitted'``
|
| 626 |
+
* ``'read committed'``
|
| 627 |
+
* ``'repeatable read'``
|
| 628 |
+
* ``'serializable'``
|
| 629 |
+
|
| 630 |
+
or ``None`` to use the server's configured isolation level. However, Django
|
| 631 |
+
works best with and defaults to read committed rather than MySQL's default,
|
| 632 |
+
repeatable read. Data loss is possible with repeatable read. In particular,
|
| 633 |
+
you may see cases where :meth:`~django.db.models.query.QuerySet.get_or_create`
|
| 634 |
+
will raise an :exc:`~django.db.IntegrityError` but the object won't appear in
|
| 635 |
+
a subsequent :meth:`~django.db.models.query.QuerySet.get` call.
|
| 636 |
+
|
| 637 |
+
.. _transaction isolation level: https://dev.mysql.com/doc/refman/en/innodb-transaction-isolation-levels.html
|
| 638 |
+
|
| 639 |
+
Creating your tables
|
| 640 |
+
--------------------
|
| 641 |
+
|
| 642 |
+
When Django generates the schema, it doesn't specify a storage engine, so
|
| 643 |
+
tables will be created with whatever default storage engine your database
|
| 644 |
+
server is configured for. The easiest solution is to set your database server's
|
| 645 |
+
default storage engine to the desired engine.
|
| 646 |
+
|
| 647 |
+
If you're using a hosting service and can't change your server's default
|
| 648 |
+
storage engine, you have a couple of options.
|
| 649 |
+
|
| 650 |
+
* After the tables are created, execute an ``ALTER TABLE`` statement to
|
| 651 |
+
convert a table to a new storage engine (such as InnoDB):
|
| 652 |
+
|
| 653 |
+
.. code-block:: sql
|
| 654 |
+
|
| 655 |
+
ALTER TABLE <tablename> ENGINE=INNODB;
|
| 656 |
+
|
| 657 |
+
This can be tedious if you have a lot of tables.
|
| 658 |
+
|
| 659 |
+
* Another option is to use the ``init_command`` option for MySQLdb prior to
|
| 660 |
+
creating your tables::
|
| 661 |
+
|
| 662 |
+
"OPTIONS": {
|
| 663 |
+
"init_command": "SET default_storage_engine=INNODB",
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
This sets the default storage engine upon connecting to the database.
|
| 667 |
+
After your tables have been created, you should remove this option as it
|
| 668 |
+
adds a query that is only needed during table creation to each database
|
| 669 |
+
connection.
|
| 670 |
+
|
| 671 |
+
Table names
|
| 672 |
+
-----------
|
| 673 |
+
|
| 674 |
+
There are `known issues`_ in even the latest versions of MySQL that can cause the
|
| 675 |
+
case of a table name to be altered when certain SQL statements are executed
|
| 676 |
+
under certain conditions. It is recommended that you use lowercase table
|
| 677 |
+
names, if possible, to avoid any problems that might arise from this behavior.
|
| 678 |
+
Django uses lowercase table names when it auto-generates table names from
|
| 679 |
+
models, so this is mainly a consideration if you are overriding the table name
|
| 680 |
+
via the :class:`~django.db.models.Options.db_table` parameter.
|
| 681 |
+
|
| 682 |
+
.. _known issues: https://bugs.mysql.com/bug.php?id=48875
|
| 683 |
+
|
| 684 |
+
Savepoints
|
| 685 |
+
----------
|
| 686 |
+
|
| 687 |
+
Both the Django ORM and MySQL (when using the InnoDB :ref:`storage engine
|
| 688 |
+
<mysql-storage-engines>`) support database :ref:`savepoints
|
| 689 |
+
<topics-db-transactions-savepoints>`.
|
| 690 |
+
|
| 691 |
+
If you use the MyISAM storage engine please be aware of the fact that you will
|
| 692 |
+
receive database-generated errors if you try to use the :ref:`savepoint-related
|
| 693 |
+
methods of the transactions API <topics-db-transactions-savepoints>`. The reason
|
| 694 |
+
for this is that detecting the storage engine of a MySQL database/table is an
|
| 695 |
+
expensive operation so it was decided it isn't worth to dynamically convert
|
| 696 |
+
these methods in no-op's based in the results of such detection.
|
| 697 |
+
|
| 698 |
+
Notes on specific fields
|
| 699 |
+
------------------------
|
| 700 |
+
|
| 701 |
+
.. _mysql-character-fields:
|
| 702 |
+
|
| 703 |
+
Character fields
|
| 704 |
+
~~~~~~~~~~~~~~~~
|
| 705 |
+
|
| 706 |
+
Any fields that are stored with ``VARCHAR`` column types may have their
|
| 707 |
+
``max_length`` restricted to 255 characters if you are using ``unique=True``
|
| 708 |
+
for the field. This affects :class:`~django.db.models.CharField`,
|
| 709 |
+
:class:`~django.db.models.SlugField`. See `the MySQL documentation`_ for more
|
| 710 |
+
details.
|
| 711 |
+
|
| 712 |
+
.. _the MySQL documentation: https://dev.mysql.com/doc/refman/en/create-index.html#create-index-column-prefixes
|
| 713 |
+
|
| 714 |
+
``TextField`` limitations
|
| 715 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 716 |
+
|
| 717 |
+
MySQL can index only the first N chars of a ``BLOB`` or ``TEXT`` column. Since
|
| 718 |
+
``TextField`` doesn't have a defined length, you can't mark it as
|
| 719 |
+
``unique=True``. MySQL will report: "BLOB/TEXT column '<db_column>' used in key
|
| 720 |
+
specification without a key length".
|
| 721 |
+
|
| 722 |
+
.. _mysql-fractional-seconds:
|
| 723 |
+
|
| 724 |
+
Fractional seconds support for Time and DateTime fields
|
| 725 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 726 |
+
|
| 727 |
+
MySQL can store fractional seconds, provided that the column definition
|
| 728 |
+
includes a fractional indication (e.g. ``DATETIME(6)``).
|
| 729 |
+
|
| 730 |
+
Django will not upgrade existing columns to include fractional seconds if the
|
| 731 |
+
database server supports it. If you want to enable them on an existing database,
|
| 732 |
+
it's up to you to either manually update the column on the target database, by
|
| 733 |
+
executing a command like:
|
| 734 |
+
|
| 735 |
+
.. code-block:: sql
|
| 736 |
+
|
| 737 |
+
ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)
|
| 738 |
+
|
| 739 |
+
or using a :class:`~django.db.migrations.operations.RunSQL` operation in a
|
| 740 |
+
:ref:`data migration <data-migrations>`.
|
| 741 |
+
|
| 742 |
+
``TIMESTAMP`` columns
|
| 743 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 744 |
+
|
| 745 |
+
If you are using a legacy database that contains ``TIMESTAMP`` columns, you must
|
| 746 |
+
set :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.
|
| 747 |
+
:djadmin:`inspectdb` maps these columns to
|
| 748 |
+
:class:`~django.db.models.DateTimeField` and if you enable timezone support,
|
| 749 |
+
both MySQL and Django will attempt to convert the values from UTC to local time.
|
| 750 |
+
|
| 751 |
+
Row locking with ``QuerySet.select_for_update()``
|
| 752 |
+
-------------------------------------------------
|
| 753 |
+
|
| 754 |
+
MySQL and MariaDB do not support some options to the ``SELECT ... FOR UPDATE``
|
| 755 |
+
statement. If ``select_for_update()`` is used with an unsupported option, then
|
| 756 |
+
a :exc:`~django.db.NotSupportedError` is raised.
|
| 757 |
+
|
| 758 |
+
=============== ========= ==========
|
| 759 |
+
Option MariaDB MySQL
|
| 760 |
+
=============== ========= ==========
|
| 761 |
+
``SKIP LOCKED`` X (≥10.6) X (≥8.0.1)
|
| 762 |
+
``NOWAIT`` X X (≥8.0.1)
|
| 763 |
+
``OF`` X (≥8.0.1)
|
| 764 |
+
``NO KEY``
|
| 765 |
+
=============== ========= ==========
|
| 766 |
+
|
| 767 |
+
When using ``select_for_update()`` on MySQL, make sure you filter a queryset
|
| 768 |
+
against at least a set of fields contained in unique constraints or only
|
| 769 |
+
against fields covered by indexes. Otherwise, an exclusive write lock will be
|
| 770 |
+
acquired over the full table for the duration of the transaction.
|
| 771 |
+
|
| 772 |
+
Automatic typecasting can cause unexpected results
|
| 773 |
+
--------------------------------------------------
|
| 774 |
+
|
| 775 |
+
When performing a query on a string type, but with an integer value, MySQL will
|
| 776 |
+
coerce the types of all values in the table to an integer before performing the
|
| 777 |
+
comparison. If your table contains the values ``'abc'``, ``'def'`` and you
|
| 778 |
+
query for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``
|
| 779 |
+
will match the value ``'abc1'``. Therefore, string type fields included in Django
|
| 780 |
+
will always cast the value to a string before using it in a query.
|
| 781 |
+
|
| 782 |
+
If you implement custom model fields that inherit from
|
| 783 |
+
:class:`~django.db.models.Field` directly, are overriding
|
| 784 |
+
:meth:`~django.db.models.Field.get_prep_value`, or use
|
| 785 |
+
:class:`~django.db.models.expressions.RawSQL`,
|
| 786 |
+
:meth:`~django.db.models.query.QuerySet.extra`, or
|
| 787 |
+
:meth:`~django.db.models.Manager.raw`, you should ensure that you perform
|
| 788 |
+
appropriate typecasting.
|
| 789 |
+
|
| 790 |
+
.. _sqlite-notes:
|
| 791 |
+
|
| 792 |
+
SQLite notes
|
| 793 |
+
============
|
| 794 |
+
|
| 795 |
+
Django supports SQLite 3.21.0 and later.
|
| 796 |
+
|
| 797 |
+
SQLite_ provides an excellent development alternative for applications that
|
| 798 |
+
are predominantly read-only or require a smaller installation footprint. As
|
| 799 |
+
with all database servers, though, there are some differences that are
|
| 800 |
+
specific to SQLite that you should be aware of.
|
| 801 |
+
|
| 802 |
+
.. _SQLite: https://www.sqlite.org/
|
| 803 |
+
|
| 804 |
+
.. _sqlite-string-matching:
|
| 805 |
+
|
| 806 |
+
Substring matching and case sensitivity
|
| 807 |
+
---------------------------------------
|
| 808 |
+
|
| 809 |
+
For all SQLite versions, there is some slightly counter-intuitive behavior when
|
| 810 |
+
attempting to match some types of strings. These are triggered when using the
|
| 811 |
+
:lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior
|
| 812 |
+
splits into two cases:
|
| 813 |
+
|
| 814 |
+
1. For substring matching, all matches are done case-insensitively. That is a
|
| 815 |
+
filter such as ``filter(name__contains="aa")`` will match a name of ``"Aabb"``.
|
| 816 |
+
|
| 817 |
+
2. For strings containing characters outside the ASCII range, all exact string
|
| 818 |
+
matches are performed case-sensitively, even when the case-insensitive options
|
| 819 |
+
are passed into the query. So the :lookup:`iexact` filter will behave exactly
|
| 820 |
+
the same as the :lookup:`exact` filter in these cases.
|
| 821 |
+
|
| 822 |
+
Some possible workarounds for this are `documented at sqlite.org`_, but they
|
| 823 |
+
aren't utilized by the default SQLite backend in Django, as incorporating them
|
| 824 |
+
would be fairly difficult to do robustly. Thus, Django exposes the default
|
| 825 |
+
SQLite behavior and you should be aware of this when doing case-insensitive or
|
| 826 |
+
substring filtering.
|
| 827 |
+
|
| 828 |
+
.. _documented at sqlite.org: https://www.sqlite.org/faq.html#q18
|
| 829 |
+
|
| 830 |
+
.. _sqlite-decimal-handling:
|
| 831 |
+
|
| 832 |
+
Decimal handling
|
| 833 |
+
----------------
|
| 834 |
+
|
| 835 |
+
SQLite has no real decimal internal type. Decimal values are internally
|
| 836 |
+
converted to the ``REAL`` data type (8-byte IEEE floating point number), as
|
| 837 |
+
explained in the `SQLite datatypes documentation`__, so they don't support
|
| 838 |
+
correctly-rounded decimal floating point arithmetic.
|
| 839 |
+
|
| 840 |
+
__ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes
|
| 841 |
+
|
| 842 |
+
"Database is locked" errors
|
| 843 |
+
---------------------------
|
| 844 |
+
|
| 845 |
+
SQLite is meant to be a lightweight database, and thus can't support a high
|
| 846 |
+
level of concurrency. ``OperationalError: database is locked`` errors indicate
|
| 847 |
+
that your application is experiencing more concurrency than ``sqlite`` can
|
| 848 |
+
handle in default configuration. This error means that one thread or process has
|
| 849 |
+
an exclusive lock on the database connection and another thread timed out
|
| 850 |
+
waiting for the lock the be released.
|
| 851 |
+
|
| 852 |
+
Python's SQLite wrapper has
|
| 853 |
+
a default timeout value that determines how long the second thread is allowed to
|
| 854 |
+
wait on the lock before it times out and raises the ``OperationalError: database
|
| 855 |
+
is locked`` error.
|
| 856 |
+
|
| 857 |
+
If you're getting this error, you can solve it by:
|
| 858 |
+
|
| 859 |
+
* Switching to another database backend. At a certain point SQLite becomes
|
| 860 |
+
too "lite" for real-world applications, and these sorts of concurrency
|
| 861 |
+
errors indicate you've reached that point.
|
| 862 |
+
|
| 863 |
+
* Rewriting your code to reduce concurrency and ensure that database
|
| 864 |
+
transactions are short-lived.
|
| 865 |
+
|
| 866 |
+
* Increase the default timeout value by setting the ``timeout`` database
|
| 867 |
+
option::
|
| 868 |
+
|
| 869 |
+
"OPTIONS": {
|
| 870 |
+
# ...
|
| 871 |
+
"timeout": 20,
|
| 872 |
+
# ...
|
| 873 |
+
}
|
| 874 |
+
|
| 875 |
+
This will make SQLite wait a bit longer before throwing "database is locked"
|
| 876 |
+
errors; it won't really do anything to solve them.
|
| 877 |
+
|
| 878 |
+
``QuerySet.select_for_update()`` not supported
|
| 879 |
+
----------------------------------------------
|
| 880 |
+
|
| 881 |
+
SQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will
|
| 882 |
+
have no effect.
|
| 883 |
+
|
| 884 |
+
.. _sqlite-isolation:
|
| 885 |
+
|
| 886 |
+
Isolation when using ``QuerySet.iterator()``
|
| 887 |
+
--------------------------------------------
|
| 888 |
+
|
| 889 |
+
There are special considerations described in `Isolation In SQLite`_ when
|
| 890 |
+
modifying a table while iterating over it using :meth:`.QuerySet.iterator`. If
|
| 891 |
+
a row is added, changed, or deleted within the loop, then that row may or may
|
| 892 |
+
not appear, or may appear twice, in subsequent results fetched from the
|
| 893 |
+
iterator. Your code must handle this.
|
| 894 |
+
|
| 895 |
+
.. _`Isolation in SQLite`: https://www.sqlite.org/isolation.html
|
| 896 |
+
|
| 897 |
+
.. _sqlite-json1:
|
| 898 |
+
|
| 899 |
+
Enabling JSON1 extension on SQLite
|
| 900 |
+
----------------------------------
|
| 901 |
+
|
| 902 |
+
To use :class:`~django.db.models.JSONField` on SQLite, you need to enable the
|
| 903 |
+
`JSON1 extension`_ on Python's :py:mod:`sqlite3` library. If the extension is
|
| 904 |
+
not enabled on your installation, a system error (``fields.E180``) will be
|
| 905 |
+
raised.
|
| 906 |
+
|
| 907 |
+
To enable the JSON1 extension you can follow the instruction on
|
| 908 |
+
`the wiki page`_.
|
| 909 |
+
|
| 910 |
+
.. note::
|
| 911 |
+
|
| 912 |
+
The JSON1 extension is enabled by default on SQLite 3.38+.
|
| 913 |
+
|
| 914 |
+
.. _JSON1 extension: https://www.sqlite.org/json1.html
|
| 915 |
+
.. _the wiki page: https://code.djangoproject.com/wiki/JSON1Extension
|
| 916 |
+
|
| 917 |
+
.. _oracle-notes:
|
| 918 |
+
|
| 919 |
+
Oracle notes
|
| 920 |
+
============
|
| 921 |
+
|
| 922 |
+
Django supports `Oracle Database Server`_ versions 19c and higher. Version 7.0
|
| 923 |
+
or higher of the `cx_Oracle`_ Python driver is required.
|
| 924 |
+
|
| 925 |
+
.. _`Oracle Database Server`: https://www.oracle.com/
|
| 926 |
+
.. _`cx_Oracle`: https://oracle.github.io/python-cx_Oracle/
|
| 927 |
+
|
| 928 |
+
In order for the ``python manage.py migrate`` command to work, your Oracle
|
| 929 |
+
database user must have privileges to run the following commands:
|
| 930 |
+
|
| 931 |
+
* CREATE TABLE
|
| 932 |
+
* CREATE SEQUENCE
|
| 933 |
+
* CREATE PROCEDURE
|
| 934 |
+
* CREATE TRIGGER
|
| 935 |
+
|
| 936 |
+
To run a project's test suite, the user usually needs these *additional*
|
| 937 |
+
privileges:
|
| 938 |
+
|
| 939 |
+
* CREATE USER
|
| 940 |
+
* ALTER USER
|
| 941 |
+
* DROP USER
|
| 942 |
+
* CREATE TABLESPACE
|
| 943 |
+
* DROP TABLESPACE
|
| 944 |
+
* CREATE SESSION WITH ADMIN OPTION
|
| 945 |
+
* CREATE TABLE WITH ADMIN OPTION
|
| 946 |
+
* CREATE SEQUENCE WITH ADMIN OPTION
|
| 947 |
+
* CREATE PROCEDURE WITH ADMIN OPTION
|
| 948 |
+
* CREATE TRIGGER WITH ADMIN OPTION
|
| 949 |
+
|
| 950 |
+
While the ``RESOURCE`` role has the required ``CREATE TABLE``,
|
| 951 |
+
``CREATE SEQUENCE``, ``CREATE PROCEDURE``, and ``CREATE TRIGGER`` privileges,
|
| 952 |
+
and a user granted ``RESOURCE WITH ADMIN OPTION`` can grant ``RESOURCE``, such
|
| 953 |
+
a user cannot grant the individual privileges (e.g. ``CREATE TABLE``), and thus
|
| 954 |
+
``RESOURCE WITH ADMIN OPTION`` is not usually sufficient for running tests.
|
| 955 |
+
|
| 956 |
+
Some test suites also create views or materialized views; to run these, the
|
| 957 |
+
user also needs ``CREATE VIEW WITH ADMIN OPTION`` and
|
| 958 |
+
``CREATE MATERIALIZED VIEW WITH ADMIN OPTION`` privileges. In particular, this
|
| 959 |
+
is needed for Django's own test suite.
|
| 960 |
+
|
| 961 |
+
All of these privileges are included in the DBA role, which is appropriate
|
| 962 |
+
for use on a private developer's database.
|
| 963 |
+
|
| 964 |
+
The Oracle database backend uses the ``SYS.DBMS_LOB`` and ``SYS.DBMS_RANDOM``
|
| 965 |
+
packages, so your user will require execute permissions on it. It's normally
|
| 966 |
+
accessible to all users by default, but in case it is not, you'll need to grant
|
| 967 |
+
permissions like so:
|
| 968 |
+
|
| 969 |
+
.. code-block:: sql
|
| 970 |
+
|
| 971 |
+
GRANT EXECUTE ON SYS.DBMS_LOB TO user;
|
| 972 |
+
GRANT EXECUTE ON SYS.DBMS_RANDOM TO user;
|
| 973 |
+
|
| 974 |
+
Connecting to the database
|
| 975 |
+
--------------------------
|
| 976 |
+
|
| 977 |
+
To connect using the service name of your Oracle database, your ``settings.py``
|
| 978 |
+
file should look something like this::
|
| 979 |
+
|
| 980 |
+
DATABASES = {
|
| 981 |
+
"default": {
|
| 982 |
+
"ENGINE": "django.db.backends.oracle",
|
| 983 |
+
"NAME": "xe",
|
| 984 |
+
"USER": "a_user",
|
| 985 |
+
"PASSWORD": "a_password",
|
| 986 |
+
"HOST": "",
|
| 987 |
+
"PORT": "",
|
| 988 |
+
}
|
| 989 |
+
}
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
In this case, you should leave both :setting:`HOST` and :setting:`PORT` empty.
|
| 993 |
+
However, if you don't use a ``tnsnames.ora`` file or a similar naming method
|
| 994 |
+
and want to connect using the SID ("xe" in this example), then fill in both
|
| 995 |
+
:setting:`HOST` and :setting:`PORT` like so::
|
| 996 |
+
|
| 997 |
+
DATABASES = {
|
| 998 |
+
"default": {
|
| 999 |
+
"ENGINE": "django.db.backends.oracle",
|
| 1000 |
+
"NAME": "xe",
|
| 1001 |
+
"USER": "a_user",
|
| 1002 |
+
"PASSWORD": "a_password",
|
| 1003 |
+
"HOST": "dbprod01ned.mycompany.com",
|
| 1004 |
+
"PORT": "1540",
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
You should either supply both :setting:`HOST` and :setting:`PORT`, or leave
|
| 1009 |
+
both as empty strings. Django will use a different connect descriptor depending
|
| 1010 |
+
on that choice.
|
| 1011 |
+
|
| 1012 |
+
Full DSN and Easy Connect
|
| 1013 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1014 |
+
|
| 1015 |
+
A Full DSN or Easy Connect string can be used in :setting:`NAME` if both
|
| 1016 |
+
:setting:`HOST` and :setting:`PORT` are empty. This format is required when
|
| 1017 |
+
using RAC or pluggable databases without ``tnsnames.ora``, for example.
|
| 1018 |
+
|
| 1019 |
+
Example of an Easy Connect string::
|
| 1020 |
+
|
| 1021 |
+
"NAME": "localhost:1521/orclpdb1"
|
| 1022 |
+
|
| 1023 |
+
Example of a full DSN string::
|
| 1024 |
+
|
| 1025 |
+
"NAME": (
|
| 1026 |
+
"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))"
|
| 1027 |
+
"(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))"
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
Threaded option
|
| 1031 |
+
---------------
|
| 1032 |
+
|
| 1033 |
+
If you plan to run Django in a multithreaded environment (e.g. Apache using the
|
| 1034 |
+
default MPM module on any modern operating system), then you **must** set
|
| 1035 |
+
the ``threaded`` option of your Oracle database configuration to ``True``::
|
| 1036 |
+
|
| 1037 |
+
"OPTIONS": {
|
| 1038 |
+
"threaded": True,
|
| 1039 |
+
}
|
| 1040 |
+
|
| 1041 |
+
Failure to do this may result in crashes and other odd behavior.
|
| 1042 |
+
|
| 1043 |
+
INSERT ... RETURNING INTO
|
| 1044 |
+
-------------------------
|
| 1045 |
+
|
| 1046 |
+
By default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently
|
| 1047 |
+
retrieve the value of an ``AutoField`` when inserting new rows. This behavior
|
| 1048 |
+
may result in a ``DatabaseError`` in certain unusual setups, such as when
|
| 1049 |
+
inserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.
|
| 1050 |
+
The ``RETURNING INTO`` clause can be disabled by setting the
|
| 1051 |
+
``use_returning_into`` option of the database configuration to ``False``::
|
| 1052 |
+
|
| 1053 |
+
"OPTIONS": {
|
| 1054 |
+
"use_returning_into": False,
|
| 1055 |
+
}
|
| 1056 |
+
|
| 1057 |
+
In this case, the Oracle backend will use a separate ``SELECT`` query to
|
| 1058 |
+
retrieve ``AutoField`` values.
|
| 1059 |
+
|
| 1060 |
+
Naming issues
|
| 1061 |
+
-------------
|
| 1062 |
+
|
| 1063 |
+
Oracle imposes a name length limit of 30 characters. To accommodate this, the
|
| 1064 |
+
backend truncates database identifiers to fit, replacing the final four
|
| 1065 |
+
characters of the truncated name with a repeatable MD5 hash value.
|
| 1066 |
+
Additionally, the backend turns database identifiers to all-uppercase.
|
| 1067 |
+
|
| 1068 |
+
To prevent these transformations (this is usually required only when dealing
|
| 1069 |
+
with legacy databases or accessing tables which belong to other users), use
|
| 1070 |
+
a quoted name as the value for ``db_table``::
|
| 1071 |
+
|
| 1072 |
+
class LegacyModel(models.Model):
|
| 1073 |
+
class Meta:
|
| 1074 |
+
db_table = '"name_left_in_lowercase"'
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
class ForeignModel(models.Model):
|
| 1078 |
+
class Meta:
|
| 1079 |
+
db_table = '"OTHER_USER"."NAME_ONLY_SEEMS_OVER_30"'
|
| 1080 |
+
|
| 1081 |
+
Quoted names can also be used with Django's other supported database
|
| 1082 |
+
backends; except for Oracle, however, the quotes have no effect.
|
| 1083 |
+
|
| 1084 |
+
When running ``migrate``, an ``ORA-06552`` error may be encountered if
|
| 1085 |
+
certain Oracle keywords are used as the name of a model field or the
|
| 1086 |
+
value of a ``db_column`` option. Django quotes all identifiers used
|
| 1087 |
+
in queries to prevent most such problems, but this error can still
|
| 1088 |
+
occur when an Oracle datatype is used as a column name. In
|
| 1089 |
+
particular, take care to avoid using the names ``date``,
|
| 1090 |
+
``timestamp``, ``number`` or ``float`` as a field name.
|
| 1091 |
+
|
| 1092 |
+
.. _oracle-null-empty-strings:
|
| 1093 |
+
|
| 1094 |
+
NULL and empty strings
|
| 1095 |
+
----------------------
|
| 1096 |
+
|
| 1097 |
+
Django generally prefers to use the empty string (``''``) rather than
|
| 1098 |
+
``NULL``, but Oracle treats both identically. To get around this, the
|
| 1099 |
+
Oracle backend ignores an explicit ``null`` option on fields that
|
| 1100 |
+
have the empty string as a possible value and generates DDL as if
|
| 1101 |
+
``null=True``. When fetching from the database, it is assumed that
|
| 1102 |
+
a ``NULL`` value in one of these fields really means the empty
|
| 1103 |
+
string, and the data is silently converted to reflect this assumption.
|
| 1104 |
+
|
| 1105 |
+
``TextField`` limitations
|
| 1106 |
+
-------------------------
|
| 1107 |
+
|
| 1108 |
+
The Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes
|
| 1109 |
+
some limitations on the usage of such LOB columns in general:
|
| 1110 |
+
|
| 1111 |
+
* LOB columns may not be used as primary keys.
|
| 1112 |
+
|
| 1113 |
+
* LOB columns may not be used in indexes.
|
| 1114 |
+
|
| 1115 |
+
* LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that
|
| 1116 |
+
attempting to use the ``QuerySet.distinct`` method on a model that
|
| 1117 |
+
includes ``TextField`` columns will result in an ``ORA-00932`` error when
|
| 1118 |
+
run against Oracle. As a workaround, use the ``QuerySet.defer`` method in
|
| 1119 |
+
conjunction with ``distinct()`` to prevent ``TextField`` columns from being
|
| 1120 |
+
included in the ``SELECT DISTINCT`` list.
|
| 1121 |
+
|
| 1122 |
+
.. _subclassing-database-backends:
|
| 1123 |
+
|
| 1124 |
+
Subclassing the built-in database backends
|
| 1125 |
+
==========================================
|
| 1126 |
+
|
| 1127 |
+
Django comes with built-in database backends. You may subclass an existing
|
| 1128 |
+
database backends to modify its behavior, features, or configuration.
|
| 1129 |
+
|
| 1130 |
+
Consider, for example, that you need to change a single database feature.
|
| 1131 |
+
First, you have to create a new directory with a ``base`` module in it. For
|
| 1132 |
+
example:
|
| 1133 |
+
|
| 1134 |
+
.. code-block:: text
|
| 1135 |
+
|
| 1136 |
+
mysite/
|
| 1137 |
+
...
|
| 1138 |
+
mydbengine/
|
| 1139 |
+
__init__.py
|
| 1140 |
+
base.py
|
| 1141 |
+
|
| 1142 |
+
The ``base.py`` module must contain a class named ``DatabaseWrapper`` that
|
| 1143 |
+
subclasses an existing engine from the ``django.db.backends`` module. Here's an
|
| 1144 |
+
example of subclassing the PostgreSQL engine to change a feature class
|
| 1145 |
+
``allows_group_by_selected_pks_on_model``:
|
| 1146 |
+
|
| 1147 |
+
.. code-block:: python
|
| 1148 |
+
:caption: ``mysite/mydbengine/base.py``
|
| 1149 |
+
|
| 1150 |
+
from django.db.backends.postgresql import base, features
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
class DatabaseFeatures(features.DatabaseFeatures):
|
| 1154 |
+
def allows_group_by_selected_pks_on_model(self, model):
|
| 1155 |
+
return True
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
class DatabaseWrapper(base.DatabaseWrapper):
|
| 1159 |
+
features_class = DatabaseFeatures
|
| 1160 |
+
|
| 1161 |
+
Finally, you must specify a :setting:`DATABASE-ENGINE` in your ``settings.py``
|
| 1162 |
+
file::
|
| 1163 |
+
|
| 1164 |
+
DATABASES = {
|
| 1165 |
+
"default": {
|
| 1166 |
+
"ENGINE": "mydbengine",
|
| 1167 |
+
# ...
|
| 1168 |
+
},
|
| 1169 |
+
}
|
| 1170 |
+
|
| 1171 |
+
You can see the current list of database engines by looking in
|
| 1172 |
+
:source:`django/db/backends`.
|
| 1173 |
+
|
| 1174 |
+
.. _third-party-notes:
|
| 1175 |
+
|
| 1176 |
+
Using a 3rd-party database backend
|
| 1177 |
+
==================================
|
| 1178 |
+
|
| 1179 |
+
In addition to the officially supported databases, there are backends provided
|
| 1180 |
+
by 3rd parties that allow you to use other databases with Django:
|
| 1181 |
+
|
| 1182 |
+
* :pypi:`CockroachDB <django-cockroachdb>`
|
| 1183 |
+
* :pypi:`Firebird <django-firebird>`
|
| 1184 |
+
* :pypi:`Google Cloud Spanner <django-google-spanner>`
|
| 1185 |
+
* :pypi:`Microsoft SQL Server <mssql-django>`
|
| 1186 |
+
* :pypi:`Snowflake <django-snowflake>`
|
| 1187 |
+
* :pypi:`TiDB <django-tidb>`
|
| 1188 |
+
* :pypi:`YugabyteDB <django-yugabytedb>`
|
| 1189 |
+
|
| 1190 |
+
The Django versions and ORM features supported by these unofficial backends
|
| 1191 |
+
vary considerably. Queries regarding the specific capabilities of these
|
| 1192 |
+
unofficial backends, along with any support queries, should be directed to
|
| 1193 |
+
the support channels provided by each 3rd party project.
|
testbed/django__django/docs/ref/exceptions.txt
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=================
|
| 2 |
+
Django Exceptions
|
| 3 |
+
=================
|
| 4 |
+
|
| 5 |
+
Django raises some of its own exceptions as well as standard Python exceptions.
|
| 6 |
+
|
| 7 |
+
Django Core Exceptions
|
| 8 |
+
======================
|
| 9 |
+
|
| 10 |
+
.. module:: django.core.exceptions
|
| 11 |
+
:synopsis: Django core exceptions
|
| 12 |
+
|
| 13 |
+
Django core exception classes are defined in ``django.core.exceptions``.
|
| 14 |
+
|
| 15 |
+
``AppRegistryNotReady``
|
| 16 |
+
-----------------------
|
| 17 |
+
|
| 18 |
+
.. exception:: AppRegistryNotReady
|
| 19 |
+
|
| 20 |
+
This exception is raised when attempting to use models before the :ref:`app
|
| 21 |
+
loading process <app-loading-process>`, which initializes the ORM, is
|
| 22 |
+
complete.
|
| 23 |
+
|
| 24 |
+
``ObjectDoesNotExist``
|
| 25 |
+
----------------------
|
| 26 |
+
|
| 27 |
+
.. exception:: ObjectDoesNotExist
|
| 28 |
+
|
| 29 |
+
The base class for :exc:`Model.DoesNotExist
|
| 30 |
+
<django.db.models.Model.DoesNotExist>` exceptions. A ``try/except`` for
|
| 31 |
+
``ObjectDoesNotExist`` will catch
|
| 32 |
+
:exc:`~django.db.models.Model.DoesNotExist` exceptions for all models.
|
| 33 |
+
|
| 34 |
+
See :meth:`~django.db.models.query.QuerySet.get()`.
|
| 35 |
+
|
| 36 |
+
``EmptyResultSet``
|
| 37 |
+
------------------
|
| 38 |
+
|
| 39 |
+
.. exception:: EmptyResultSet
|
| 40 |
+
|
| 41 |
+
``EmptyResultSet`` may be raised during query generation if a query won't
|
| 42 |
+
return any results. Most Django projects won't encounter this exception,
|
| 43 |
+
but it might be useful for implementing custom lookups and expressions.
|
| 44 |
+
|
| 45 |
+
``FullResultSet``
|
| 46 |
+
-----------------
|
| 47 |
+
|
| 48 |
+
.. exception:: FullResultSet
|
| 49 |
+
|
| 50 |
+
.. versionadded:: 4.2
|
| 51 |
+
|
| 52 |
+
``FullResultSet`` may be raised during query generation if a query will
|
| 53 |
+
match everything. Most Django projects won't encounter this exception, but
|
| 54 |
+
it might be useful for implementing custom lookups and expressions.
|
| 55 |
+
|
| 56 |
+
``FieldDoesNotExist``
|
| 57 |
+
---------------------
|
| 58 |
+
|
| 59 |
+
.. exception:: FieldDoesNotExist
|
| 60 |
+
|
| 61 |
+
The ``FieldDoesNotExist`` exception is raised by a model's
|
| 62 |
+
``_meta.get_field()`` method when the requested field does not exist on the
|
| 63 |
+
model or on the model's parents.
|
| 64 |
+
|
| 65 |
+
``MultipleObjectsReturned``
|
| 66 |
+
---------------------------
|
| 67 |
+
|
| 68 |
+
.. exception:: MultipleObjectsReturned
|
| 69 |
+
|
| 70 |
+
The base class for :exc:`Model.MultipleObjectsReturned
|
| 71 |
+
<django.db.models.Model.MultipleObjectsReturned>` exceptions. A
|
| 72 |
+
``try/except`` for ``MultipleObjectsReturned`` will catch
|
| 73 |
+
:exc:`~django.db.models.Model.MultipleObjectsReturned` exceptions for all
|
| 74 |
+
models.
|
| 75 |
+
|
| 76 |
+
See :meth:`~django.db.models.query.QuerySet.get()`.
|
| 77 |
+
|
| 78 |
+
``SuspiciousOperation``
|
| 79 |
+
-----------------------
|
| 80 |
+
|
| 81 |
+
.. exception:: SuspiciousOperation
|
| 82 |
+
|
| 83 |
+
The :exc:`SuspiciousOperation` exception is raised when a user has
|
| 84 |
+
performed an operation that should be considered suspicious from a security
|
| 85 |
+
perspective, such as tampering with a session cookie. Subclasses of
|
| 86 |
+
``SuspiciousOperation`` include:
|
| 87 |
+
|
| 88 |
+
* ``DisallowedHost``
|
| 89 |
+
* ``DisallowedModelAdminLookup``
|
| 90 |
+
* ``DisallowedModelAdminToField``
|
| 91 |
+
* ``DisallowedRedirect``
|
| 92 |
+
* ``InvalidSessionKey``
|
| 93 |
+
* ``RequestDataTooBig``
|
| 94 |
+
* ``SuspiciousFileOperation``
|
| 95 |
+
* ``SuspiciousMultipartForm``
|
| 96 |
+
* ``SuspiciousSession``
|
| 97 |
+
* ``TooManyFieldsSent``
|
| 98 |
+
* ``TooManyFilesSent``
|
| 99 |
+
|
| 100 |
+
If a ``SuspiciousOperation`` exception reaches the ASGI/WSGI handler level
|
| 101 |
+
it is logged at the ``Error`` level and results in
|
| 102 |
+
a :class:`~django.http.HttpResponseBadRequest`. See the :doc:`logging
|
| 103 |
+
documentation </topics/logging/>` for more information.
|
| 104 |
+
|
| 105 |
+
.. versionchanged:: 3.2.18
|
| 106 |
+
|
| 107 |
+
``SuspiciousOperation`` is raised when too many files are submitted.
|
| 108 |
+
|
| 109 |
+
``PermissionDenied``
|
| 110 |
+
--------------------
|
| 111 |
+
|
| 112 |
+
.. exception:: PermissionDenied
|
| 113 |
+
|
| 114 |
+
The :exc:`PermissionDenied` exception is raised when a user does not have
|
| 115 |
+
permission to perform the action requested.
|
| 116 |
+
|
| 117 |
+
``ViewDoesNotExist``
|
| 118 |
+
--------------------
|
| 119 |
+
|
| 120 |
+
.. exception:: ViewDoesNotExist
|
| 121 |
+
|
| 122 |
+
The :exc:`ViewDoesNotExist` exception is raised by
|
| 123 |
+
:mod:`django.urls` when a requested view does not exist.
|
| 124 |
+
|
| 125 |
+
``MiddlewareNotUsed``
|
| 126 |
+
---------------------
|
| 127 |
+
|
| 128 |
+
.. exception:: MiddlewareNotUsed
|
| 129 |
+
|
| 130 |
+
The :exc:`MiddlewareNotUsed` exception is raised when a middleware is not
|
| 131 |
+
used in the server configuration.
|
| 132 |
+
|
| 133 |
+
``ImproperlyConfigured``
|
| 134 |
+
------------------------
|
| 135 |
+
|
| 136 |
+
.. exception:: ImproperlyConfigured
|
| 137 |
+
|
| 138 |
+
The :exc:`ImproperlyConfigured` exception is raised when Django is
|
| 139 |
+
somehow improperly configured -- for example, if a value in ``settings.py``
|
| 140 |
+
is incorrect or unparseable.
|
| 141 |
+
|
| 142 |
+
``FieldError``
|
| 143 |
+
--------------
|
| 144 |
+
|
| 145 |
+
.. exception:: FieldError
|
| 146 |
+
|
| 147 |
+
The :exc:`FieldError` exception is raised when there is a problem with a
|
| 148 |
+
model field. This can happen for several reasons:
|
| 149 |
+
|
| 150 |
+
- A field in a model clashes with a field of the same name from an
|
| 151 |
+
abstract base class
|
| 152 |
+
- An infinite loop is caused by ordering
|
| 153 |
+
- A keyword cannot be parsed from the filter parameters
|
| 154 |
+
- A field cannot be determined from a keyword in the query
|
| 155 |
+
parameters
|
| 156 |
+
- A join is not permitted on the specified field
|
| 157 |
+
- A field name is invalid
|
| 158 |
+
- A query contains invalid order_by arguments
|
| 159 |
+
|
| 160 |
+
``ValidationError``
|
| 161 |
+
-------------------
|
| 162 |
+
|
| 163 |
+
.. exception:: ValidationError
|
| 164 |
+
|
| 165 |
+
The :exc:`ValidationError` exception is raised when data fails form or
|
| 166 |
+
model field validation. For more information about validation, see
|
| 167 |
+
:doc:`Form and Field Validation </ref/forms/validation>`,
|
| 168 |
+
:ref:`Model Field Validation <validating-objects>` and the
|
| 169 |
+
:doc:`Validator Reference </ref/validators>`.
|
| 170 |
+
|
| 171 |
+
``NON_FIELD_ERRORS``
|
| 172 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 173 |
+
|
| 174 |
+
.. data:: NON_FIELD_ERRORS
|
| 175 |
+
|
| 176 |
+
``ValidationError``\s that don't belong to a particular field in a form
|
| 177 |
+
or model are classified as ``NON_FIELD_ERRORS``. This constant is used
|
| 178 |
+
as a key in dictionaries that otherwise map fields to their respective
|
| 179 |
+
list of errors.
|
| 180 |
+
|
| 181 |
+
``BadRequest``
|
| 182 |
+
--------------
|
| 183 |
+
|
| 184 |
+
.. exception:: BadRequest
|
| 185 |
+
|
| 186 |
+
The :exc:`BadRequest` exception is raised when the request cannot be
|
| 187 |
+
processed due to a client error. If a ``BadRequest`` exception reaches the
|
| 188 |
+
ASGI/WSGI handler level it results in a
|
| 189 |
+
:class:`~django.http.HttpResponseBadRequest`.
|
| 190 |
+
|
| 191 |
+
``RequestAborted``
|
| 192 |
+
------------------
|
| 193 |
+
|
| 194 |
+
.. exception:: RequestAborted
|
| 195 |
+
|
| 196 |
+
The :exc:`RequestAborted` exception is raised when an HTTP body being read
|
| 197 |
+
in by the handler is cut off midstream and the client connection closes,
|
| 198 |
+
or when the client does not send data and hits a timeout where the server
|
| 199 |
+
closes the connection.
|
| 200 |
+
|
| 201 |
+
It is internal to the HTTP handler modules and you are unlikely to see
|
| 202 |
+
it elsewhere. If you are modifying HTTP handling code, you should raise
|
| 203 |
+
this when you encounter an aborted request to make sure the socket is
|
| 204 |
+
closed cleanly.
|
| 205 |
+
|
| 206 |
+
``SynchronousOnlyOperation``
|
| 207 |
+
----------------------------
|
| 208 |
+
|
| 209 |
+
.. exception:: SynchronousOnlyOperation
|
| 210 |
+
|
| 211 |
+
The :exc:`SynchronousOnlyOperation` exception is raised when code that
|
| 212 |
+
is only allowed in synchronous Python code is called from an asynchronous
|
| 213 |
+
context (a thread with a running asynchronous event loop). These parts of
|
| 214 |
+
Django are generally heavily reliant on thread-safety to function and don't
|
| 215 |
+
work correctly under coroutines sharing the same thread.
|
| 216 |
+
|
| 217 |
+
If you are trying to call code that is synchronous-only from an
|
| 218 |
+
asynchronous thread, then create a synchronous thread and call it in that.
|
| 219 |
+
You can accomplish this is with :func:`asgiref.sync.sync_to_async`.
|
| 220 |
+
|
| 221 |
+
.. currentmodule:: django.urls
|
| 222 |
+
|
| 223 |
+
URL Resolver exceptions
|
| 224 |
+
=======================
|
| 225 |
+
|
| 226 |
+
URL Resolver exceptions are defined in ``django.urls``.
|
| 227 |
+
|
| 228 |
+
``Resolver404``
|
| 229 |
+
---------------
|
| 230 |
+
|
| 231 |
+
.. exception:: Resolver404
|
| 232 |
+
|
| 233 |
+
The :exc:`Resolver404` exception is raised by
|
| 234 |
+
:func:`~django.urls.resolve()` if the path passed to ``resolve()`` doesn't
|
| 235 |
+
map to a view. It's a subclass of :class:`django.http.Http404`.
|
| 236 |
+
|
| 237 |
+
``NoReverseMatch``
|
| 238 |
+
------------------
|
| 239 |
+
|
| 240 |
+
.. exception:: NoReverseMatch
|
| 241 |
+
|
| 242 |
+
The :exc:`NoReverseMatch` exception is raised by :mod:`django.urls` when a
|
| 243 |
+
matching URL in your URLconf cannot be identified based on the parameters
|
| 244 |
+
supplied.
|
| 245 |
+
|
| 246 |
+
.. currentmodule:: django.db
|
| 247 |
+
|
| 248 |
+
Database Exceptions
|
| 249 |
+
===================
|
| 250 |
+
|
| 251 |
+
Database exceptions may be imported from ``django.db``.
|
| 252 |
+
|
| 253 |
+
Django wraps the standard database exceptions so that your Django code has a
|
| 254 |
+
guaranteed common implementation of these classes.
|
| 255 |
+
|
| 256 |
+
.. exception:: Error
|
| 257 |
+
.. exception:: InterfaceError
|
| 258 |
+
.. exception:: DatabaseError
|
| 259 |
+
.. exception:: DataError
|
| 260 |
+
.. exception:: OperationalError
|
| 261 |
+
.. exception:: IntegrityError
|
| 262 |
+
.. exception:: InternalError
|
| 263 |
+
.. exception:: ProgrammingError
|
| 264 |
+
.. exception:: NotSupportedError
|
| 265 |
+
|
| 266 |
+
The Django wrappers for database exceptions behave exactly the same as
|
| 267 |
+
the underlying database exceptions. See :pep:`249`, the Python Database API
|
| 268 |
+
Specification v2.0, for further information.
|
| 269 |
+
|
| 270 |
+
As per :pep:`3134`, a ``__cause__`` attribute is set with the original
|
| 271 |
+
(underlying) database exception, allowing access to any additional
|
| 272 |
+
information provided.
|
| 273 |
+
|
| 274 |
+
.. exception:: models.ProtectedError
|
| 275 |
+
|
| 276 |
+
Raised to prevent deletion of referenced objects when using
|
| 277 |
+
:attr:`django.db.models.PROTECT`. :exc:`models.ProtectedError` is a subclass
|
| 278 |
+
of :exc:`IntegrityError`.
|
| 279 |
+
|
| 280 |
+
.. exception:: models.RestrictedError
|
| 281 |
+
|
| 282 |
+
Raised to prevent deletion of referenced objects when using
|
| 283 |
+
:attr:`django.db.models.RESTRICT`. :exc:`models.RestrictedError` is a subclass
|
| 284 |
+
of :exc:`IntegrityError`.
|
| 285 |
+
|
| 286 |
+
.. currentmodule:: django.http
|
| 287 |
+
|
| 288 |
+
HTTP Exceptions
|
| 289 |
+
===============
|
| 290 |
+
|
| 291 |
+
HTTP exceptions may be imported from ``django.http``.
|
| 292 |
+
|
| 293 |
+
``UnreadablePostError``
|
| 294 |
+
-----------------------
|
| 295 |
+
|
| 296 |
+
.. exception:: UnreadablePostError
|
| 297 |
+
|
| 298 |
+
:exc:`UnreadablePostError` is raised when a user cancels an upload.
|
| 299 |
+
|
| 300 |
+
.. currentmodule:: django.contrib.sessions.exceptions
|
| 301 |
+
|
| 302 |
+
Sessions Exceptions
|
| 303 |
+
===================
|
| 304 |
+
|
| 305 |
+
Sessions exceptions are defined in ``django.contrib.sessions.exceptions``.
|
| 306 |
+
|
| 307 |
+
``SessionInterrupted``
|
| 308 |
+
----------------------
|
| 309 |
+
|
| 310 |
+
.. exception:: SessionInterrupted
|
| 311 |
+
|
| 312 |
+
:exc:`SessionInterrupted` is raised when a session is destroyed in a
|
| 313 |
+
concurrent request. It's a subclass of
|
| 314 |
+
:exc:`~django.core.exceptions.BadRequest`.
|
| 315 |
+
|
| 316 |
+
Transaction Exceptions
|
| 317 |
+
======================
|
| 318 |
+
|
| 319 |
+
.. currentmodule:: django.db.transaction
|
| 320 |
+
|
| 321 |
+
Transaction exceptions are defined in ``django.db.transaction``.
|
| 322 |
+
|
| 323 |
+
``TransactionManagementError``
|
| 324 |
+
------------------------------
|
| 325 |
+
|
| 326 |
+
.. exception:: TransactionManagementError
|
| 327 |
+
|
| 328 |
+
:exc:`TransactionManagementError` is raised for any and all problems
|
| 329 |
+
related to database transactions.
|
| 330 |
+
|
| 331 |
+
.. currentmodule:: django.test
|
| 332 |
+
|
| 333 |
+
Testing Framework Exceptions
|
| 334 |
+
============================
|
| 335 |
+
|
| 336 |
+
Exceptions provided by the ``django.test`` package.
|
| 337 |
+
|
| 338 |
+
``RedirectCycleError``
|
| 339 |
+
----------------------
|
| 340 |
+
|
| 341 |
+
.. exception:: client.RedirectCycleError
|
| 342 |
+
|
| 343 |
+
:exc:`~client.RedirectCycleError` is raised when the test client detects a
|
| 344 |
+
loop or an overly long chain of redirects.
|
| 345 |
+
|
| 346 |
+
Python Exceptions
|
| 347 |
+
=================
|
| 348 |
+
|
| 349 |
+
Django raises built-in Python exceptions when appropriate as well. See the
|
| 350 |
+
Python documentation for further information on the :ref:`bltin-exceptions`.
|
testbed/django__django/docs/ref/index.txt
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=============
|
| 2 |
+
API Reference
|
| 3 |
+
=============
|
| 4 |
+
|
| 5 |
+
.. toctree::
|
| 6 |
+
:maxdepth: 1
|
| 7 |
+
|
| 8 |
+
applications
|
| 9 |
+
checks
|
| 10 |
+
class-based-views/index
|
| 11 |
+
clickjacking
|
| 12 |
+
contrib/index
|
| 13 |
+
csrf
|
| 14 |
+
databases
|
| 15 |
+
django-admin
|
| 16 |
+
exceptions
|
| 17 |
+
files/index
|
| 18 |
+
forms/index
|
| 19 |
+
logging
|
| 20 |
+
middleware
|
| 21 |
+
migration-operations
|
| 22 |
+
models/index
|
| 23 |
+
paginator
|
| 24 |
+
request-response
|
| 25 |
+
schema-editor
|
| 26 |
+
settings
|
| 27 |
+
signals
|
| 28 |
+
templates/index
|
| 29 |
+
template-response
|
| 30 |
+
unicode
|
| 31 |
+
urlresolvers
|
| 32 |
+
urls
|
| 33 |
+
utils
|
| 34 |
+
validators
|
| 35 |
+
views
|
testbed/django__django/docs/ref/logging.txt
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
=======
|
| 6 |
+
|
| 7 |
+
.. seealso::
|
| 8 |
+
|
| 9 |
+
* :ref:`logging-how-to`
|
| 10 |
+
* :ref:`Django logging overview <logging-explanation>`
|
| 11 |
+
|
| 12 |
+
.. module:: django.utils.log
|
| 13 |
+
:synopsis: Logging tools for Django applications
|
| 14 |
+
|
| 15 |
+
Django's logging module extends Python's builtin :mod:`logging`.
|
| 16 |
+
|
| 17 |
+
Logging is configured as part of the general Django :func:`django.setup`
|
| 18 |
+
function, so it's always available unless explicitly disabled.
|
| 19 |
+
|
| 20 |
+
.. _default-logging-configuration:
|
| 21 |
+
|
| 22 |
+
Django's default logging configuration
|
| 23 |
+
======================================
|
| 24 |
+
|
| 25 |
+
By default, Django uses Python's :ref:`logging.config.dictConfig format
|
| 26 |
+
<logging-config-dictschema>`.
|
| 27 |
+
|
| 28 |
+
Default logging conditions
|
| 29 |
+
--------------------------
|
| 30 |
+
|
| 31 |
+
The full set of default logging conditions are:
|
| 32 |
+
|
| 33 |
+
When :setting:`DEBUG` is ``True``:
|
| 34 |
+
|
| 35 |
+
* The ``django`` logger sends messages in the ``django`` hierarchy (except
|
| 36 |
+
``django.server``) at the ``INFO`` level or higher to the console.
|
| 37 |
+
|
| 38 |
+
When :setting:`DEBUG` is ``False``:
|
| 39 |
+
|
| 40 |
+
* The ``django`` logger sends messages in the ``django`` hierarchy (except
|
| 41 |
+
``django.server``) with ``ERROR`` or ``CRITICAL`` level to
|
| 42 |
+
:class:`AdminEmailHandler`.
|
| 43 |
+
|
| 44 |
+
Independently of the value of :setting:`DEBUG`:
|
| 45 |
+
|
| 46 |
+
* The :ref:`django-server-logger` logger sends messages at the ``INFO`` level
|
| 47 |
+
or higher to the console.
|
| 48 |
+
|
| 49 |
+
All loggers except :ref:`django-server-logger` propagate logging to their
|
| 50 |
+
parents, up to the root ``django`` logger. The ``console`` and ``mail_admins``
|
| 51 |
+
handlers are attached to the root logger to provide the behavior described
|
| 52 |
+
above.
|
| 53 |
+
|
| 54 |
+
Python's own defaults send records of level ``WARNING`` and higher
|
| 55 |
+
to the console.
|
| 56 |
+
|
| 57 |
+
.. _default-logging-definition:
|
| 58 |
+
|
| 59 |
+
Default logging definition
|
| 60 |
+
--------------------------
|
| 61 |
+
|
| 62 |
+
Django's default logging configuration inherits Python's defaults. It's
|
| 63 |
+
available as ``django.utils.log.DEFAULT_LOGGING`` and defined in
|
| 64 |
+
:source:`django/utils/log.py`::
|
| 65 |
+
|
| 66 |
+
{
|
| 67 |
+
"version": 1,
|
| 68 |
+
"disable_existing_loggers": False,
|
| 69 |
+
"filters": {
|
| 70 |
+
"require_debug_false": {
|
| 71 |
+
"()": "django.utils.log.RequireDebugFalse",
|
| 72 |
+
},
|
| 73 |
+
"require_debug_true": {
|
| 74 |
+
"()": "django.utils.log.RequireDebugTrue",
|
| 75 |
+
},
|
| 76 |
+
},
|
| 77 |
+
"formatters": {
|
| 78 |
+
"django.server": {
|
| 79 |
+
"()": "django.utils.log.ServerFormatter",
|
| 80 |
+
"format": "[{server_time}] {message}",
|
| 81 |
+
"style": "{",
|
| 82 |
+
}
|
| 83 |
+
},
|
| 84 |
+
"handlers": {
|
| 85 |
+
"console": {
|
| 86 |
+
"level": "INFO",
|
| 87 |
+
"filters": ["require_debug_true"],
|
| 88 |
+
"class": "logging.StreamHandler",
|
| 89 |
+
},
|
| 90 |
+
"django.server": {
|
| 91 |
+
"level": "INFO",
|
| 92 |
+
"class": "logging.StreamHandler",
|
| 93 |
+
"formatter": "django.server",
|
| 94 |
+
},
|
| 95 |
+
"mail_admins": {
|
| 96 |
+
"level": "ERROR",
|
| 97 |
+
"filters": ["require_debug_false"],
|
| 98 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 99 |
+
},
|
| 100 |
+
},
|
| 101 |
+
"loggers": {
|
| 102 |
+
"django": {
|
| 103 |
+
"handlers": ["console", "mail_admins"],
|
| 104 |
+
"level": "INFO",
|
| 105 |
+
},
|
| 106 |
+
"django.server": {
|
| 107 |
+
"handlers": ["django.server"],
|
| 108 |
+
"level": "INFO",
|
| 109 |
+
"propagate": False,
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
See :ref:`configuring-logging` on how to complement or replace this default
|
| 115 |
+
logging configuration.
|
| 116 |
+
|
| 117 |
+
Django logging extensions
|
| 118 |
+
=========================
|
| 119 |
+
|
| 120 |
+
Django provides a number of utilities to handle the particular requirements of
|
| 121 |
+
logging in a web server environment.
|
| 122 |
+
|
| 123 |
+
Loggers
|
| 124 |
+
-------
|
| 125 |
+
|
| 126 |
+
Django provides several built-in loggers.
|
| 127 |
+
|
| 128 |
+
.. _django-logger:
|
| 129 |
+
|
| 130 |
+
``django``
|
| 131 |
+
~~~~~~~~~~
|
| 132 |
+
|
| 133 |
+
The parent logger for messages in the ``django`` :ref:`named logger hierarchy
|
| 134 |
+
<naming-loggers-hierarchy>`. Django does not post messages using this name.
|
| 135 |
+
Instead, it uses one of the loggers below.
|
| 136 |
+
|
| 137 |
+
.. _django-request-logger:
|
| 138 |
+
|
| 139 |
+
``django.request``
|
| 140 |
+
~~~~~~~~~~~~~~~~~~
|
| 141 |
+
|
| 142 |
+
Log messages related to the handling of requests. 5XX responses are
|
| 143 |
+
raised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``
|
| 144 |
+
messages. Requests that are logged to the ``django.security`` logger aren't
|
| 145 |
+
logged to ``django.request``.
|
| 146 |
+
|
| 147 |
+
Messages to this logger have the following extra context:
|
| 148 |
+
|
| 149 |
+
* ``status_code``: The HTTP response code associated with the request.
|
| 150 |
+
|
| 151 |
+
* ``request``: The request object that generated the logging message.
|
| 152 |
+
|
| 153 |
+
.. _django-server-logger:
|
| 154 |
+
|
| 155 |
+
``django.server``
|
| 156 |
+
~~~~~~~~~~~~~~~~~
|
| 157 |
+
|
| 158 |
+
Log messages related to the handling of requests received by the server invoked
|
| 159 |
+
by the :djadmin:`runserver` command. HTTP 5XX responses are logged as ``ERROR``
|
| 160 |
+
messages, 4XX responses are logged as ``WARNING`` messages, and everything else
|
| 161 |
+
is logged as ``INFO``.
|
| 162 |
+
|
| 163 |
+
Messages to this logger have the following extra context:
|
| 164 |
+
|
| 165 |
+
* ``status_code``: The HTTP response code associated with the request.
|
| 166 |
+
|
| 167 |
+
* ``request``: The request object that generated the logging message.
|
| 168 |
+
|
| 169 |
+
.. _django-template-logger:
|
| 170 |
+
|
| 171 |
+
``django.template``
|
| 172 |
+
~~~~~~~~~~~~~~~~~~~
|
| 173 |
+
|
| 174 |
+
Log messages related to the rendering of templates.
|
| 175 |
+
|
| 176 |
+
* Missing context variables are logged as ``DEBUG`` messages.
|
| 177 |
+
|
| 178 |
+
.. _django-db-logger:
|
| 179 |
+
|
| 180 |
+
``django.db.backends``
|
| 181 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 182 |
+
|
| 183 |
+
Messages relating to the interaction of code with the database. For example,
|
| 184 |
+
every application-level SQL statement executed by a request is logged at the
|
| 185 |
+
``DEBUG`` level to this logger.
|
| 186 |
+
|
| 187 |
+
Messages to this logger have the following extra context:
|
| 188 |
+
|
| 189 |
+
* ``duration``: The time taken to execute the SQL statement.
|
| 190 |
+
* ``sql``: The SQL statement that was executed.
|
| 191 |
+
* ``params``: The parameters that were used in the SQL call.
|
| 192 |
+
* ``alias``: The alias of the database used in the SQL call.
|
| 193 |
+
|
| 194 |
+
For performance reasons, SQL logging is only enabled when
|
| 195 |
+
``settings.DEBUG`` is set to ``True``, regardless of the logging
|
| 196 |
+
level or handlers that are installed.
|
| 197 |
+
|
| 198 |
+
This logging does not include framework-level initialization (e.g.
|
| 199 |
+
``SET TIMEZONE``). Turn on query logging in your database if you wish to view
|
| 200 |
+
all database queries.
|
| 201 |
+
|
| 202 |
+
.. versionchanged:: 4.2
|
| 203 |
+
|
| 204 |
+
Support for logging transaction management queries (``BEGIN``, ``COMMIT``,
|
| 205 |
+
and ``ROLLBACK``) was added.
|
| 206 |
+
|
| 207 |
+
.. _django-security-logger:
|
| 208 |
+
|
| 209 |
+
``django.security.*``
|
| 210 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 211 |
+
|
| 212 |
+
The security loggers will receive messages on any occurrence of
|
| 213 |
+
:exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
|
| 214 |
+
errors. There is a sub-logger for each subtype of security error, including all
|
| 215 |
+
``SuspiciousOperation``\s. The level of the log event depends on where the
|
| 216 |
+
exception is handled. Most occurrences are logged as a warning, while
|
| 217 |
+
any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
|
| 218 |
+
error. For example, when an HTTP ``Host`` header is included in a request from
|
| 219 |
+
a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
|
| 220 |
+
response, and an error message will be logged to the
|
| 221 |
+
``django.security.DisallowedHost`` logger.
|
| 222 |
+
|
| 223 |
+
These log events will reach the ``django`` logger by default, which mails error
|
| 224 |
+
events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
|
| 225 |
+
to a ``SuspiciousOperation`` will not be logged to the ``django.request``
|
| 226 |
+
logger, but only to the ``django.security`` logger.
|
| 227 |
+
|
| 228 |
+
To silence a particular type of ``SuspiciousOperation``, you can override that
|
| 229 |
+
specific logger following this example::
|
| 230 |
+
|
| 231 |
+
LOGGING = {
|
| 232 |
+
# ...
|
| 233 |
+
"handlers": {
|
| 234 |
+
"null": {
|
| 235 |
+
"class": "logging.NullHandler",
|
| 236 |
+
},
|
| 237 |
+
},
|
| 238 |
+
"loggers": {
|
| 239 |
+
"django.security.DisallowedHost": {
|
| 240 |
+
"handlers": ["null"],
|
| 241 |
+
"propagate": False,
|
| 242 |
+
},
|
| 243 |
+
},
|
| 244 |
+
# ...
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
Other ``django.security`` loggers not based on ``SuspiciousOperation`` are:
|
| 248 |
+
|
| 249 |
+
* ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.
|
| 250 |
+
|
| 251 |
+
``django.db.backends.schema``
|
| 252 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 253 |
+
|
| 254 |
+
Logs the SQL queries that are executed during schema changes to the database by
|
| 255 |
+
the :doc:`migrations framework </topics/migrations>`. Note that it won't log the
|
| 256 |
+
queries executed by :class:`~django.db.migrations.operations.RunPython`.
|
| 257 |
+
Messages to this logger have ``params`` and ``sql`` in their extra context (but
|
| 258 |
+
unlike ``django.db.backends``, not duration). The values have the same meaning
|
| 259 |
+
as explained in :ref:`django-db-logger`.
|
| 260 |
+
|
| 261 |
+
Handlers
|
| 262 |
+
--------
|
| 263 |
+
|
| 264 |
+
Django provides one log handler in addition to :mod:`those provided by the
|
| 265 |
+
Python logging module <python:logging.handlers>`.
|
| 266 |
+
|
| 267 |
+
.. class:: AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)
|
| 268 |
+
|
| 269 |
+
This handler sends an email to the site :setting:`ADMINS` for each log
|
| 270 |
+
message it receives.
|
| 271 |
+
|
| 272 |
+
If the log record contains a ``request`` attribute, the full details
|
| 273 |
+
of the request will be included in the email. The email subject will
|
| 274 |
+
include the phrase "internal IP" if the client's IP address is in the
|
| 275 |
+
:setting:`INTERNAL_IPS` setting; if not, it will include "EXTERNAL IP".
|
| 276 |
+
|
| 277 |
+
If the log record contains stack trace information, that stack
|
| 278 |
+
trace will be included in the email.
|
| 279 |
+
|
| 280 |
+
The ``include_html`` argument of ``AdminEmailHandler`` is used to
|
| 281 |
+
control whether the traceback email includes an HTML attachment
|
| 282 |
+
containing the full content of the debug web page that would have been
|
| 283 |
+
produced if :setting:`DEBUG` were ``True``. To set this value in your
|
| 284 |
+
configuration, include it in the handler definition for
|
| 285 |
+
``django.utils.log.AdminEmailHandler``, like this::
|
| 286 |
+
|
| 287 |
+
"handlers": {
|
| 288 |
+
"mail_admins": {
|
| 289 |
+
"level": "ERROR",
|
| 290 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 291 |
+
"include_html": True,
|
| 292 |
+
},
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
Be aware of the :ref:`security implications of logging
|
| 296 |
+
<logging-security-implications>` when using the ``AdminEmailHandler``.
|
| 297 |
+
|
| 298 |
+
By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
|
| 299 |
+
:ref:`email backend <topic-email-backends>` that is being used by the
|
| 300 |
+
handler can be overridden, like this::
|
| 301 |
+
|
| 302 |
+
"handlers": {
|
| 303 |
+
"mail_admins": {
|
| 304 |
+
"level": "ERROR",
|
| 305 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 306 |
+
"email_backend": "django.core.mail.backends.filebased.EmailBackend",
|
| 307 |
+
},
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
By default, an instance of the email backend specified in
|
| 311 |
+
:setting:`EMAIL_BACKEND` will be used.
|
| 312 |
+
|
| 313 |
+
The ``reporter_class`` argument of ``AdminEmailHandler`` allows providing
|
| 314 |
+
an ``django.views.debug.ExceptionReporter`` subclass to customize the
|
| 315 |
+
traceback text sent in the email body. You provide a string import path to
|
| 316 |
+
the class you wish to use, like this::
|
| 317 |
+
|
| 318 |
+
"handlers": {
|
| 319 |
+
"mail_admins": {
|
| 320 |
+
"level": "ERROR",
|
| 321 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 322 |
+
"include_html": True,
|
| 323 |
+
"reporter_class": "somepackage.error_reporter.CustomErrorReporter",
|
| 324 |
+
},
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
.. method:: send_mail(subject, message, *args, **kwargs)
|
| 328 |
+
|
| 329 |
+
Sends emails to admin users. To customize this behavior, you can
|
| 330 |
+
subclass the :class:`~django.utils.log.AdminEmailHandler` class and
|
| 331 |
+
override this method.
|
| 332 |
+
|
| 333 |
+
Filters
|
| 334 |
+
-------
|
| 335 |
+
|
| 336 |
+
Django provides some log filters in addition to those provided by the Python
|
| 337 |
+
logging module.
|
| 338 |
+
|
| 339 |
+
.. class:: CallbackFilter(callback)
|
| 340 |
+
|
| 341 |
+
This filter accepts a callback function (which should accept a single
|
| 342 |
+
argument, the record to be logged), and calls it for each record that
|
| 343 |
+
passes through the filter. Handling of that record will not proceed if the
|
| 344 |
+
callback returns False.
|
| 345 |
+
|
| 346 |
+
For instance, to filter out :exc:`~django.http.UnreadablePostError`
|
| 347 |
+
(raised when a user cancels an upload) from the admin emails, you would
|
| 348 |
+
create a filter function::
|
| 349 |
+
|
| 350 |
+
from django.http import UnreadablePostError
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def skip_unreadable_post(record):
|
| 354 |
+
if record.exc_info:
|
| 355 |
+
exc_type, exc_value = record.exc_info[:2]
|
| 356 |
+
if isinstance(exc_value, UnreadablePostError):
|
| 357 |
+
return False
|
| 358 |
+
return True
|
| 359 |
+
|
| 360 |
+
and then add it to your logging config::
|
| 361 |
+
|
| 362 |
+
LOGGING = {
|
| 363 |
+
# ...
|
| 364 |
+
"filters": {
|
| 365 |
+
"skip_unreadable_posts": {
|
| 366 |
+
"()": "django.utils.log.CallbackFilter",
|
| 367 |
+
"callback": skip_unreadable_post,
|
| 368 |
+
},
|
| 369 |
+
},
|
| 370 |
+
"handlers": {
|
| 371 |
+
"mail_admins": {
|
| 372 |
+
"level": "ERROR",
|
| 373 |
+
"filters": ["skip_unreadable_posts"],
|
| 374 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 375 |
+
},
|
| 376 |
+
},
|
| 377 |
+
# ...
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
.. class:: RequireDebugFalse()
|
| 381 |
+
|
| 382 |
+
This filter will only pass on records when settings.DEBUG is False.
|
| 383 |
+
|
| 384 |
+
This filter is used as follows in the default :setting:`LOGGING`
|
| 385 |
+
configuration to ensure that the :class:`AdminEmailHandler` only sends
|
| 386 |
+
error emails to admins when :setting:`DEBUG` is ``False``::
|
| 387 |
+
|
| 388 |
+
LOGGING = {
|
| 389 |
+
# ...
|
| 390 |
+
"filters": {
|
| 391 |
+
"require_debug_false": {
|
| 392 |
+
"()": "django.utils.log.RequireDebugFalse",
|
| 393 |
+
},
|
| 394 |
+
},
|
| 395 |
+
"handlers": {
|
| 396 |
+
"mail_admins": {
|
| 397 |
+
"level": "ERROR",
|
| 398 |
+
"filters": ["require_debug_false"],
|
| 399 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 400 |
+
},
|
| 401 |
+
},
|
| 402 |
+
# ...
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
.. class:: RequireDebugTrue()
|
| 406 |
+
|
| 407 |
+
This filter is similar to :class:`RequireDebugFalse`, except that records are
|
| 408 |
+
passed only when :setting:`DEBUG` is ``True``.
|
testbed/django__django/docs/ref/middleware.txt
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
Middleware
|
| 3 |
+
==========
|
| 4 |
+
|
| 5 |
+
.. module:: django.middleware
|
| 6 |
+
:synopsis: Django's built-in middleware classes.
|
| 7 |
+
|
| 8 |
+
This document explains all middleware components that come with Django. For
|
| 9 |
+
information on how to use them and how to write your own middleware, see
|
| 10 |
+
the :doc:`middleware usage guide </topics/http/middleware>`.
|
| 11 |
+
|
| 12 |
+
Available middleware
|
| 13 |
+
====================
|
| 14 |
+
|
| 15 |
+
Cache middleware
|
| 16 |
+
----------------
|
| 17 |
+
|
| 18 |
+
.. module:: django.middleware.cache
|
| 19 |
+
:synopsis: Middleware for the site-wide cache.
|
| 20 |
+
|
| 21 |
+
.. class:: UpdateCacheMiddleware
|
| 22 |
+
|
| 23 |
+
.. class:: FetchFromCacheMiddleware
|
| 24 |
+
|
| 25 |
+
Enable the site-wide cache. If these are enabled, each Django-powered page will
|
| 26 |
+
be cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting
|
| 27 |
+
defines. See the :doc:`cache documentation </topics/cache>`.
|
| 28 |
+
|
| 29 |
+
"Common" middleware
|
| 30 |
+
-------------------
|
| 31 |
+
|
| 32 |
+
.. module:: django.middleware.common
|
| 33 |
+
:synopsis: Middleware adding "common" conveniences for perfectionists.
|
| 34 |
+
|
| 35 |
+
.. class:: CommonMiddleware
|
| 36 |
+
|
| 37 |
+
Adds a few conveniences for perfectionists:
|
| 38 |
+
|
| 39 |
+
* Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`
|
| 40 |
+
setting, which should be a list of compiled regular expression objects.
|
| 41 |
+
|
| 42 |
+
* Performs URL rewriting based on the :setting:`APPEND_SLASH` and
|
| 43 |
+
:setting:`PREPEND_WWW` settings.
|
| 44 |
+
|
| 45 |
+
If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end
|
| 46 |
+
with a slash, and it is not found in the URLconf, then a new URL is
|
| 47 |
+
formed by appending a slash at the end. If this new URL is found in the
|
| 48 |
+
URLconf, then Django redirects the request to this new URL. Otherwise,
|
| 49 |
+
the initial URL is processed as usual.
|
| 50 |
+
|
| 51 |
+
For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if
|
| 52 |
+
you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a
|
| 53 |
+
valid pattern for ``foo.com/bar/``.
|
| 54 |
+
|
| 55 |
+
If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading "www."
|
| 56 |
+
will be redirected to the same URL with a leading "www."
|
| 57 |
+
|
| 58 |
+
Both of these options are meant to normalize URLs. The philosophy is that
|
| 59 |
+
each URL should exist in one, and only one, place. Technically a URL
|
| 60 |
+
``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine
|
| 61 |
+
indexer would treat them as separate URLs -- so it's best practice to
|
| 62 |
+
normalize URLs.
|
| 63 |
+
|
| 64 |
+
If necessary, individual views may be excluded from the ``APPEND_SLASH``
|
| 65 |
+
behavior using the :func:`~django.views.decorators.common.no_append_slash`
|
| 66 |
+
decorator::
|
| 67 |
+
|
| 68 |
+
from django.views.decorators.common import no_append_slash
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@no_append_slash
|
| 72 |
+
def sensitive_fbv(request, *args, **kwargs):
|
| 73 |
+
"""View to be excluded from APPEND_SLASH."""
|
| 74 |
+
return HttpResponse()
|
| 75 |
+
|
| 76 |
+
* Sets the ``Content-Length`` header for non-streaming responses.
|
| 77 |
+
|
| 78 |
+
.. attribute:: CommonMiddleware.response_redirect_class
|
| 79 |
+
|
| 80 |
+
Defaults to :class:`~django.http.HttpResponsePermanentRedirect`. Subclass
|
| 81 |
+
``CommonMiddleware`` and override the attribute to customize the redirects
|
| 82 |
+
issued by the middleware.
|
| 83 |
+
|
| 84 |
+
.. class:: BrokenLinkEmailsMiddleware
|
| 85 |
+
|
| 86 |
+
* Sends broken link notification emails to :setting:`MANAGERS` (see
|
| 87 |
+
:doc:`/howto/error-reporting`).
|
| 88 |
+
|
| 89 |
+
GZip middleware
|
| 90 |
+
---------------
|
| 91 |
+
|
| 92 |
+
.. module:: django.middleware.gzip
|
| 93 |
+
:synopsis: Middleware to serve GZipped content for performance.
|
| 94 |
+
|
| 95 |
+
.. class:: GZipMiddleware
|
| 96 |
+
|
| 97 |
+
.. attribute:: max_random_bytes
|
| 98 |
+
|
| 99 |
+
Defaults to 100. Subclass ``GZipMiddleware`` and override the attribute
|
| 100 |
+
to change the maximum number of random bytes that is included with
|
| 101 |
+
compressed responses.
|
| 102 |
+
|
| 103 |
+
.. note::
|
| 104 |
+
|
| 105 |
+
Security researchers revealed that when compression techniques (including
|
| 106 |
+
``GZipMiddleware``) are used on a website, the site may become exposed to a
|
| 107 |
+
number of possible attacks.
|
| 108 |
+
|
| 109 |
+
To mitigate attacks, Django implements a technique called *Heal The Breach
|
| 110 |
+
(HTB)*. It adds up to 100 bytes (see
|
| 111 |
+
:attr:`.max_random_bytes`) of random bytes to each response
|
| 112 |
+
to make the attacks less effective.
|
| 113 |
+
|
| 114 |
+
For more details, see the `BREACH paper (PDF)`_, `breachattack.com`_, and
|
| 115 |
+
the `Heal The Breach (HTB) paper`_.
|
| 116 |
+
|
| 117 |
+
.. _BREACH paper (PDF): https://www.breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf
|
| 118 |
+
.. _breachattack.com: https://www.breachattack.com/
|
| 119 |
+
.. _Heal The Breach (HTB) paper: https://ieeexplore.ieee.org/document/9754554
|
| 120 |
+
|
| 121 |
+
.. versionchanged:: 4.2
|
| 122 |
+
|
| 123 |
+
Mitigation for the BREACH attack was added.
|
| 124 |
+
|
| 125 |
+
The ``django.middleware.gzip.GZipMiddleware`` compresses content for browsers
|
| 126 |
+
that understand GZip compression (all modern browsers).
|
| 127 |
+
|
| 128 |
+
This middleware should be placed before any other middleware that need to
|
| 129 |
+
read or write the response body so that compression happens afterward.
|
| 130 |
+
|
| 131 |
+
It will NOT compress content if any of the following are true:
|
| 132 |
+
|
| 133 |
+
* The content body is less than 200 bytes long.
|
| 134 |
+
|
| 135 |
+
* The response has already set the ``Content-Encoding`` header.
|
| 136 |
+
|
| 137 |
+
* The request (the browser) hasn't sent an ``Accept-Encoding`` header
|
| 138 |
+
containing ``gzip``.
|
| 139 |
+
|
| 140 |
+
If the response has an ``ETag`` header, the ETag is made weak to comply with
|
| 141 |
+
:rfc:`9110#section-8.8.1`.
|
| 142 |
+
|
| 143 |
+
You can apply GZip compression to individual views using the
|
| 144 |
+
:func:`~django.views.decorators.gzip.gzip_page()` decorator.
|
| 145 |
+
|
| 146 |
+
Conditional GET middleware
|
| 147 |
+
--------------------------
|
| 148 |
+
|
| 149 |
+
.. module:: django.middleware.http
|
| 150 |
+
:synopsis: Middleware handling advanced HTTP features.
|
| 151 |
+
|
| 152 |
+
.. class:: ConditionalGetMiddleware
|
| 153 |
+
|
| 154 |
+
Handles conditional GET operations. If the response doesn't have an ``ETag``
|
| 155 |
+
header, the middleware adds one if needed. If the response has an ``ETag`` or
|
| 156 |
+
``Last-Modified`` header, and the request has ``If-None-Match`` or
|
| 157 |
+
``If-Modified-Since``, the response is replaced by an
|
| 158 |
+
:class:`~django.http.HttpResponseNotModified`.
|
| 159 |
+
|
| 160 |
+
Locale middleware
|
| 161 |
+
-----------------
|
| 162 |
+
|
| 163 |
+
.. module:: django.middleware.locale
|
| 164 |
+
:synopsis: Middleware to enable language selection based on the request.
|
| 165 |
+
|
| 166 |
+
.. class:: LocaleMiddleware
|
| 167 |
+
|
| 168 |
+
Enables language selection based on data from the request. It customizes
|
| 169 |
+
content for each user. See the :doc:`internationalization documentation
|
| 170 |
+
</topics/i18n/translation>`.
|
| 171 |
+
|
| 172 |
+
.. attribute:: LocaleMiddleware.response_redirect_class
|
| 173 |
+
|
| 174 |
+
Defaults to :class:`~django.http.HttpResponseRedirect`. Subclass
|
| 175 |
+
``LocaleMiddleware`` and override the attribute to customize the redirects
|
| 176 |
+
issued by the middleware.
|
| 177 |
+
|
| 178 |
+
Message middleware
|
| 179 |
+
------------------
|
| 180 |
+
|
| 181 |
+
.. module:: django.contrib.messages.middleware
|
| 182 |
+
:synopsis: Message middleware.
|
| 183 |
+
|
| 184 |
+
.. class:: MessageMiddleware
|
| 185 |
+
|
| 186 |
+
Enables cookie- and session-based message support. See the
|
| 187 |
+
:doc:`messages documentation </ref/contrib/messages>`.
|
| 188 |
+
|
| 189 |
+
.. _security-middleware:
|
| 190 |
+
|
| 191 |
+
Security middleware
|
| 192 |
+
-------------------
|
| 193 |
+
|
| 194 |
+
.. module:: django.middleware.security
|
| 195 |
+
:synopsis: Security middleware.
|
| 196 |
+
|
| 197 |
+
.. warning::
|
| 198 |
+
If your deployment situation allows, it's usually a good idea to have your
|
| 199 |
+
front-end web server perform the functionality provided by the
|
| 200 |
+
``SecurityMiddleware``. That way, if there are requests that aren't served
|
| 201 |
+
by Django (such as static media or user-uploaded files), they will have
|
| 202 |
+
the same protections as requests to your Django application.
|
| 203 |
+
|
| 204 |
+
.. class:: SecurityMiddleware
|
| 205 |
+
|
| 206 |
+
The ``django.middleware.security.SecurityMiddleware`` provides several security
|
| 207 |
+
enhancements to the request/response cycle. Each one can be independently
|
| 208 |
+
enabled or disabled with a setting.
|
| 209 |
+
|
| 210 |
+
* :setting:`SECURE_CONTENT_TYPE_NOSNIFF`
|
| 211 |
+
* :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY`
|
| 212 |
+
* :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`
|
| 213 |
+
* :setting:`SECURE_HSTS_PRELOAD`
|
| 214 |
+
* :setting:`SECURE_HSTS_SECONDS`
|
| 215 |
+
* :setting:`SECURE_REDIRECT_EXEMPT`
|
| 216 |
+
* :setting:`SECURE_REFERRER_POLICY`
|
| 217 |
+
* :setting:`SECURE_SSL_HOST`
|
| 218 |
+
* :setting:`SECURE_SSL_REDIRECT`
|
| 219 |
+
|
| 220 |
+
.. _http-strict-transport-security:
|
| 221 |
+
|
| 222 |
+
HTTP Strict Transport Security
|
| 223 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 224 |
+
|
| 225 |
+
For sites that should only be accessed over HTTPS, you can instruct modern
|
| 226 |
+
browsers to refuse to connect to your domain name via an insecure connection
|
| 227 |
+
(for a given period of time) by setting the `"Strict-Transport-Security"
|
| 228 |
+
header`__. This reduces your exposure to some SSL-stripping man-in-the-middle
|
| 229 |
+
(MITM) attacks.
|
| 230 |
+
|
| 231 |
+
``SecurityMiddleware`` will set this header for you on all HTTPS responses if
|
| 232 |
+
you set the :setting:`SECURE_HSTS_SECONDS` setting to a non-zero integer value.
|
| 233 |
+
|
| 234 |
+
When enabling HSTS, it's a good idea to first use a small value for testing,
|
| 235 |
+
for example, :setting:`SECURE_HSTS_SECONDS = 3600<SECURE_HSTS_SECONDS>` for one
|
| 236 |
+
hour. Each time a web browser sees the HSTS header from your site, it will
|
| 237 |
+
refuse to communicate non-securely (using HTTP) with your domain for the given
|
| 238 |
+
period of time. Once you confirm that all assets are served securely on your
|
| 239 |
+
site (i.e. HSTS didn't break anything), it's a good idea to increase this value
|
| 240 |
+
so that infrequent visitors will be protected (31536000 seconds, i.e. 1 year,
|
| 241 |
+
is common).
|
| 242 |
+
|
| 243 |
+
Additionally, if you set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting
|
| 244 |
+
to ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` directive
|
| 245 |
+
to the ``Strict-Transport-Security`` header. This is recommended (assuming all
|
| 246 |
+
subdomains are served exclusively using HTTPS), otherwise your site may still
|
| 247 |
+
be vulnerable via an insecure connection to a subdomain.
|
| 248 |
+
|
| 249 |
+
If you wish to submit your site to the `browser preload list`_, set the
|
| 250 |
+
:setting:`SECURE_HSTS_PRELOAD` setting to ``True``. That appends the
|
| 251 |
+
``preload`` directive to the ``Strict-Transport-Security`` header.
|
| 252 |
+
|
| 253 |
+
.. warning::
|
| 254 |
+
The HSTS policy applies to your entire domain, not just the URL of the
|
| 255 |
+
response that you set the header on. Therefore, you should only use it if
|
| 256 |
+
your entire domain is served via HTTPS only.
|
| 257 |
+
|
| 258 |
+
Browsers properly respecting the HSTS header will refuse to allow users to
|
| 259 |
+
bypass warnings and connect to a site with an expired, self-signed, or
|
| 260 |
+
otherwise invalid SSL certificate. If you use HSTS, make sure your
|
| 261 |
+
certificates are in good shape and stay that way!
|
| 262 |
+
|
| 263 |
+
.. note::
|
| 264 |
+
If you are deployed behind a load-balancer or reverse-proxy server, and the
|
| 265 |
+
``Strict-Transport-Security`` header is not being added to your responses,
|
| 266 |
+
it may be because Django doesn't realize that it's on a secure connection;
|
| 267 |
+
you may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.
|
| 268 |
+
|
| 269 |
+
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
|
| 270 |
+
.. _browser preload list: https://hstspreload.org/
|
| 271 |
+
|
| 272 |
+
.. _referrer-policy:
|
| 273 |
+
|
| 274 |
+
Referrer Policy
|
| 275 |
+
~~~~~~~~~~~~~~~
|
| 276 |
+
|
| 277 |
+
Browsers use `the Referer header`__ as a way to send information to a site
|
| 278 |
+
about how users got there. When a user clicks a link, the browser will send the
|
| 279 |
+
full URL of the linking page as the referrer. While this can be useful for some
|
| 280 |
+
purposes -- like figuring out who's linking to your site -- it also can cause
|
| 281 |
+
privacy concerns by informing one site that a user was visiting another site.
|
| 282 |
+
|
| 283 |
+
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer
|
| 284 |
+
|
| 285 |
+
Some browsers have the ability to accept hints about whether they should send
|
| 286 |
+
the HTTP ``Referer`` header when a user clicks a link; this hint is provided
|
| 287 |
+
via `the Referrer-Policy header`__. This header can suggest any of three
|
| 288 |
+
behaviors to browsers:
|
| 289 |
+
|
| 290 |
+
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
|
| 291 |
+
|
| 292 |
+
* Full URL: send the entire URL in the ``Referer`` header. For example, if the
|
| 293 |
+
user is visiting ``https://example.com/page.html``, the ``Referer`` header
|
| 294 |
+
would contain ``"https://example.com/page.html"``.
|
| 295 |
+
|
| 296 |
+
* Origin only: send only the "origin" in the referrer. The origin consists of
|
| 297 |
+
the scheme, host and (optionally) port number. For example, if the user is
|
| 298 |
+
visiting ``https://example.com/page.html``, the origin would be
|
| 299 |
+
``https://example.com/``.
|
| 300 |
+
|
| 301 |
+
* No referrer: do not send a ``Referer`` header at all.
|
| 302 |
+
|
| 303 |
+
There are two types of conditions this header can tell a browser to watch out
|
| 304 |
+
for:
|
| 305 |
+
|
| 306 |
+
* Same-origin versus cross-origin: a link from ``https://example.com/1.html``
|
| 307 |
+
to ``https://example.com/2.html`` is same-origin. A link from
|
| 308 |
+
``https://example.com/page.html`` to ``https://not.example.com/page.html`` is
|
| 309 |
+
cross-origin.
|
| 310 |
+
|
| 311 |
+
* Protocol downgrade: a downgrade occurs if the page containing the link is
|
| 312 |
+
served via HTTPS, but the page being linked to is not served via HTTPS.
|
| 313 |
+
|
| 314 |
+
.. warning::
|
| 315 |
+
When your site is served via HTTPS, :ref:`Django's CSRF protection system
|
| 316 |
+
<how-csrf-works>` requires the ``Referer`` header to be present, so
|
| 317 |
+
completely disabling the ``Referer`` header will interfere with CSRF
|
| 318 |
+
protection. To gain most of the benefits of disabling ``Referer`` headers
|
| 319 |
+
while also keeping CSRF protection, consider enabling only same-origin
|
| 320 |
+
referrers.
|
| 321 |
+
|
| 322 |
+
``SecurityMiddleware`` can set the ``Referrer-Policy`` header for you, based on
|
| 323 |
+
the :setting:`SECURE_REFERRER_POLICY` setting (note spelling: browsers send a
|
| 324 |
+
``Referer`` header when a user clicks a link, but the header instructing a
|
| 325 |
+
browser whether to do so is spelled ``Referrer-Policy``). The valid values for
|
| 326 |
+
this setting are:
|
| 327 |
+
|
| 328 |
+
``no-referrer``
|
| 329 |
+
Instructs the browser to send no referrer for links clicked on this site.
|
| 330 |
+
|
| 331 |
+
``no-referrer-when-downgrade``
|
| 332 |
+
Instructs the browser to send a full URL as the referrer, but only when no
|
| 333 |
+
protocol downgrade occurs.
|
| 334 |
+
|
| 335 |
+
``origin``
|
| 336 |
+
Instructs the browser to send only the origin, not the full URL, as the
|
| 337 |
+
referrer.
|
| 338 |
+
|
| 339 |
+
``origin-when-cross-origin``
|
| 340 |
+
Instructs the browser to send the full URL as the referrer for same-origin
|
| 341 |
+
links, and only the origin for cross-origin links.
|
| 342 |
+
|
| 343 |
+
``same-origin``
|
| 344 |
+
Instructs the browser to send a full URL, but only for same-origin links. No
|
| 345 |
+
referrer will be sent for cross-origin links.
|
| 346 |
+
|
| 347 |
+
``strict-origin``
|
| 348 |
+
Instructs the browser to send only the origin, not the full URL, and to send
|
| 349 |
+
no referrer when a protocol downgrade occurs.
|
| 350 |
+
|
| 351 |
+
``strict-origin-when-cross-origin``
|
| 352 |
+
Instructs the browser to send the full URL when the link is same-origin and
|
| 353 |
+
no protocol downgrade occurs; send only the origin when the link is
|
| 354 |
+
cross-origin and no protocol downgrade occurs; and no referrer when a
|
| 355 |
+
protocol downgrade occurs.
|
| 356 |
+
|
| 357 |
+
``unsafe-url``
|
| 358 |
+
Instructs the browser to always send the full URL as the referrer.
|
| 359 |
+
|
| 360 |
+
.. admonition:: Unknown Policy Values
|
| 361 |
+
|
| 362 |
+
Where a policy value is `unknown`__ by a user agent, it is possible to
|
| 363 |
+
specify multiple policy values to provide a fallback. The last specified
|
| 364 |
+
value that is understood takes precedence. To support this, an iterable or
|
| 365 |
+
comma-separated string can be used with :setting:`SECURE_REFERRER_POLICY`.
|
| 366 |
+
|
| 367 |
+
__ https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
|
| 368 |
+
|
| 369 |
+
.. _cross-origin-opener-policy:
|
| 370 |
+
|
| 371 |
+
Cross-Origin Opener Policy
|
| 372 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 373 |
+
|
| 374 |
+
Some browsers have the ability to isolate top-level windows from other
|
| 375 |
+
documents by putting them in a separate browsing context group based on the
|
| 376 |
+
value of the `Cross-Origin Opener Policy`__ (COOP) header. If a document that
|
| 377 |
+
is isolated in this way opens a cross-origin popup window, the popup’s
|
| 378 |
+
``window.opener`` property will be ``null``. Isolating windows using COOP is a
|
| 379 |
+
defense-in-depth protection against cross-origin attacks, especially those like
|
| 380 |
+
Spectre which allowed exfiltration of data loaded into a shared browsing
|
| 381 |
+
context.
|
| 382 |
+
|
| 383 |
+
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
|
| 384 |
+
|
| 385 |
+
``SecurityMiddleware`` can set the ``Cross-Origin-Opener-Policy`` header for
|
| 386 |
+
you, based on the :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` setting. The
|
| 387 |
+
valid values for this setting are:
|
| 388 |
+
|
| 389 |
+
``same-origin``
|
| 390 |
+
Isolates the browsing context exclusively to same-origin documents.
|
| 391 |
+
Cross-origin documents are not loaded in the same browsing context. This
|
| 392 |
+
is the default and most secure option.
|
| 393 |
+
|
| 394 |
+
``same-origin-allow-popups``
|
| 395 |
+
Isolates the browsing context to same-origin documents or those which
|
| 396 |
+
either don't set COOP or which opt out of isolation by setting a COOP of
|
| 397 |
+
``unsafe-none``.
|
| 398 |
+
|
| 399 |
+
``unsafe-none``
|
| 400 |
+
Allows the document to be added to its opener's browsing context group
|
| 401 |
+
unless the opener itself has a COOP of ``same-origin`` or
|
| 402 |
+
``same-origin-allow-popups``.
|
| 403 |
+
|
| 404 |
+
.. _x-content-type-options:
|
| 405 |
+
|
| 406 |
+
``X-Content-Type-Options: nosniff``
|
| 407 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 408 |
+
|
| 409 |
+
Some browsers will try to guess the content types of the assets that they
|
| 410 |
+
fetch, overriding the ``Content-Type`` header. While this can help display
|
| 411 |
+
sites with improperly configured servers, it can also pose a security
|
| 412 |
+
risk.
|
| 413 |
+
|
| 414 |
+
If your site serves user-uploaded files, a malicious user could upload a
|
| 415 |
+
specially-crafted file that would be interpreted as HTML or JavaScript by
|
| 416 |
+
the browser when you expected it to be something harmless.
|
| 417 |
+
|
| 418 |
+
To prevent the browser from guessing the content type and force it to
|
| 419 |
+
always use the type provided in the ``Content-Type`` header, you can pass
|
| 420 |
+
the `X-Content-Type-Options: nosniff`__ header. ``SecurityMiddleware`` will
|
| 421 |
+
do this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting
|
| 422 |
+
is ``True``.
|
| 423 |
+
|
| 424 |
+
Note that in most deployment situations where Django isn't involved in serving
|
| 425 |
+
user-uploaded files, this setting won't help you. For example, if your
|
| 426 |
+
:setting:`MEDIA_URL` is served directly by your front-end web server (nginx,
|
| 427 |
+
Apache, etc.) then you'd want to set this header there. On the other hand, if
|
| 428 |
+
you are using Django to do something like require authorization in order to
|
| 429 |
+
download files and you cannot set the header using your web server, this
|
| 430 |
+
setting will be useful.
|
| 431 |
+
|
| 432 |
+
__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
|
| 433 |
+
|
| 434 |
+
.. _ssl-redirect:
|
| 435 |
+
|
| 436 |
+
SSL Redirect
|
| 437 |
+
~~~~~~~~~~~~
|
| 438 |
+
|
| 439 |
+
If your site offers both HTTP and HTTPS connections, most users will end up
|
| 440 |
+
with an unsecured connection by default. For best security, you should redirect
|
| 441 |
+
all HTTP connections to HTTPS.
|
| 442 |
+
|
| 443 |
+
If you set the :setting:`SECURE_SSL_REDIRECT` setting to True,
|
| 444 |
+
``SecurityMiddleware`` will permanently (HTTP 301) redirect all HTTP
|
| 445 |
+
connections to HTTPS.
|
| 446 |
+
|
| 447 |
+
.. note::
|
| 448 |
+
|
| 449 |
+
For performance reasons, it's preferable to do these redirects outside of
|
| 450 |
+
Django, in a front-end load balancer or reverse-proxy server such as
|
| 451 |
+
`nginx`_. :setting:`SECURE_SSL_REDIRECT` is intended for the deployment
|
| 452 |
+
situations where this isn't an option.
|
| 453 |
+
|
| 454 |
+
If the :setting:`SECURE_SSL_HOST` setting has a value, all redirects will be
|
| 455 |
+
sent to that host instead of the originally-requested host.
|
| 456 |
+
|
| 457 |
+
If there are a few pages on your site that should be available over HTTP, and
|
| 458 |
+
not redirected to HTTPS, you can list regular expressions to match those URLs
|
| 459 |
+
in the :setting:`SECURE_REDIRECT_EXEMPT` setting.
|
| 460 |
+
|
| 461 |
+
.. note::
|
| 462 |
+
If you are deployed behind a load-balancer or reverse-proxy server and
|
| 463 |
+
Django can't seem to tell when a request actually is already secure, you
|
| 464 |
+
may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.
|
| 465 |
+
|
| 466 |
+
.. _nginx: https://nginx.org/
|
| 467 |
+
|
| 468 |
+
Session middleware
|
| 469 |
+
------------------
|
| 470 |
+
|
| 471 |
+
.. module:: django.contrib.sessions.middleware
|
| 472 |
+
:synopsis: Session middleware.
|
| 473 |
+
|
| 474 |
+
.. class:: SessionMiddleware
|
| 475 |
+
|
| 476 |
+
Enables session support. See the :doc:`session documentation
|
| 477 |
+
</topics/http/sessions>`.
|
| 478 |
+
|
| 479 |
+
Site middleware
|
| 480 |
+
---------------
|
| 481 |
+
|
| 482 |
+
.. module:: django.contrib.sites.middleware
|
| 483 |
+
:synopsis: Site middleware.
|
| 484 |
+
|
| 485 |
+
.. class:: CurrentSiteMiddleware
|
| 486 |
+
|
| 487 |
+
Adds the ``site`` attribute representing the current site to every incoming
|
| 488 |
+
``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`.
|
| 489 |
+
|
| 490 |
+
Authentication middleware
|
| 491 |
+
-------------------------
|
| 492 |
+
|
| 493 |
+
.. module:: django.contrib.auth.middleware
|
| 494 |
+
:synopsis: Authentication middleware.
|
| 495 |
+
|
| 496 |
+
.. class:: AuthenticationMiddleware
|
| 497 |
+
|
| 498 |
+
Adds the ``user`` attribute, representing the currently-logged-in user, to
|
| 499 |
+
every incoming ``HttpRequest`` object. See :ref:`Authentication in web requests
|
| 500 |
+
<auth-web-requests>`.
|
| 501 |
+
|
| 502 |
+
.. class:: RemoteUserMiddleware
|
| 503 |
+
|
| 504 |
+
Middleware for utilizing web server provided authentication. See
|
| 505 |
+
:doc:`/howto/auth-remote-user` for usage details.
|
| 506 |
+
|
| 507 |
+
.. class:: PersistentRemoteUserMiddleware
|
| 508 |
+
|
| 509 |
+
Middleware for utilizing web server provided authentication when enabled only
|
| 510 |
+
on the login page. See :ref:`persistent-remote-user-middleware-howto` for usage
|
| 511 |
+
details.
|
| 512 |
+
|
| 513 |
+
CSRF protection middleware
|
| 514 |
+
--------------------------
|
| 515 |
+
|
| 516 |
+
.. currentmodule:: django.middleware.csrf
|
| 517 |
+
|
| 518 |
+
.. class:: CsrfViewMiddleware
|
| 519 |
+
|
| 520 |
+
Adds protection against Cross Site Request Forgeries by adding hidden form
|
| 521 |
+
fields to POST forms and checking requests for the correct value. See the
|
| 522 |
+
:doc:`Cross Site Request Forgery protection documentation </ref/csrf>`.
|
| 523 |
+
|
| 524 |
+
``X-Frame-Options`` middleware
|
| 525 |
+
------------------------------
|
| 526 |
+
|
| 527 |
+
.. currentmodule:: django.middleware.clickjacking
|
| 528 |
+
|
| 529 |
+
.. class:: XFrameOptionsMiddleware
|
| 530 |
+
|
| 531 |
+
Simple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`.
|
| 532 |
+
|
| 533 |
+
.. _middleware-ordering:
|
| 534 |
+
|
| 535 |
+
Middleware ordering
|
| 536 |
+
===================
|
| 537 |
+
|
| 538 |
+
Here are some hints about the ordering of various Django middleware classes:
|
| 539 |
+
|
| 540 |
+
#. :class:`~django.middleware.security.SecurityMiddleware`
|
| 541 |
+
|
| 542 |
+
It should go near the top of the list if you're going to turn on the SSL
|
| 543 |
+
redirect as that avoids running through a bunch of other unnecessary
|
| 544 |
+
middleware.
|
| 545 |
+
|
| 546 |
+
#. :class:`~django.middleware.cache.UpdateCacheMiddleware`
|
| 547 |
+
|
| 548 |
+
Before those that modify the ``Vary`` header (``SessionMiddleware``,
|
| 549 |
+
``GZipMiddleware``, ``LocaleMiddleware``).
|
| 550 |
+
|
| 551 |
+
#. :class:`~django.middleware.gzip.GZipMiddleware`
|
| 552 |
+
|
| 553 |
+
Before any middleware that may change or use the response body.
|
| 554 |
+
|
| 555 |
+
After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
|
| 556 |
+
|
| 557 |
+
#. :class:`~django.contrib.sessions.middleware.SessionMiddleware`
|
| 558 |
+
|
| 559 |
+
Before any middleware that may raise an exception to trigger an error
|
| 560 |
+
view (such as :exc:`~django.core.exceptions.PermissionDenied`) if you're
|
| 561 |
+
using :setting:`CSRF_USE_SESSIONS`.
|
| 562 |
+
|
| 563 |
+
After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.
|
| 564 |
+
|
| 565 |
+
#. :class:`~django.middleware.http.ConditionalGetMiddleware`
|
| 566 |
+
|
| 567 |
+
Before any middleware that may change the response (it sets the ``ETag``
|
| 568 |
+
header).
|
| 569 |
+
|
| 570 |
+
After ``GZipMiddleware`` so it won't calculate an ``ETag`` header on gzipped
|
| 571 |
+
contents.
|
| 572 |
+
|
| 573 |
+
#. :class:`~django.middleware.locale.LocaleMiddleware`
|
| 574 |
+
|
| 575 |
+
One of the topmost, after ``SessionMiddleware`` (uses session data) and
|
| 576 |
+
``UpdateCacheMiddleware`` (modifies ``Vary`` header).
|
| 577 |
+
|
| 578 |
+
#. :class:`~django.middleware.common.CommonMiddleware`
|
| 579 |
+
|
| 580 |
+
Before any middleware that may change the response (it sets the
|
| 581 |
+
``Content-Length`` header). A middleware that appears before
|
| 582 |
+
``CommonMiddleware`` and changes the response must reset ``Content-Length``.
|
| 583 |
+
|
| 584 |
+
Close to the top: it redirects when :setting:`APPEND_SLASH` or
|
| 585 |
+
:setting:`PREPEND_WWW` are set to ``True``.
|
| 586 |
+
|
| 587 |
+
After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`.
|
| 588 |
+
|
| 589 |
+
#. :class:`~django.middleware.csrf.CsrfViewMiddleware`
|
| 590 |
+
|
| 591 |
+
Before any view middleware that assumes that CSRF attacks have been dealt
|
| 592 |
+
with.
|
| 593 |
+
|
| 594 |
+
Before :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`, or any
|
| 595 |
+
other authentication middleware that may perform a login, and hence rotate
|
| 596 |
+
the CSRF token, before calling down the middleware chain.
|
| 597 |
+
|
| 598 |
+
After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`.
|
| 599 |
+
|
| 600 |
+
#. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
|
| 601 |
+
|
| 602 |
+
After ``SessionMiddleware``: uses session storage.
|
| 603 |
+
|
| 604 |
+
#. :class:`~django.contrib.messages.middleware.MessageMiddleware`
|
| 605 |
+
|
| 606 |
+
After ``SessionMiddleware``: can use session-based storage.
|
| 607 |
+
|
| 608 |
+
#. :class:`~django.middleware.cache.FetchFromCacheMiddleware`
|
| 609 |
+
|
| 610 |
+
After any middleware that modifies the ``Vary`` header: that header is used
|
| 611 |
+
to pick a value for the cache hash-key.
|
| 612 |
+
|
| 613 |
+
#. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`
|
| 614 |
+
|
| 615 |
+
Should be near the bottom as it's a last-resort type of middleware.
|
| 616 |
+
|
| 617 |
+
#. :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
|
| 618 |
+
|
| 619 |
+
Should be near the bottom as it's a last-resort type of middleware.
|
testbed/django__django/docs/ref/models/lookups.txt
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
====================
|
| 2 |
+
Lookup API reference
|
| 3 |
+
====================
|
| 4 |
+
|
| 5 |
+
.. module:: django.db.models.lookups
|
| 6 |
+
:synopsis: Lookups API
|
| 7 |
+
|
| 8 |
+
.. currentmodule:: django.db.models
|
| 9 |
+
|
| 10 |
+
This document has the API references of lookups, the Django API for building
|
| 11 |
+
the ``WHERE`` clause of a database query. To learn how to *use* lookups, see
|
| 12 |
+
:doc:`/topics/db/queries`; to learn how to *create* new lookups, see
|
| 13 |
+
:doc:`/howto/custom-lookups`.
|
| 14 |
+
|
| 15 |
+
The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class
|
| 16 |
+
that registers lookups, and the :ref:`Query Expression API <query-expression>`, a
|
| 17 |
+
set of methods that a class has to implement to be registrable as a lookup.
|
| 18 |
+
|
| 19 |
+
Django has two base classes that follow the query expression API and from where
|
| 20 |
+
all Django builtin lookups are derived:
|
| 21 |
+
|
| 22 |
+
* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``)
|
| 23 |
+
* :class:`Transform`: to transform a field
|
| 24 |
+
|
| 25 |
+
A lookup expression consists of three parts:
|
| 26 |
+
|
| 27 |
+
* Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``);
|
| 28 |
+
* Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``);
|
| 29 |
+
* A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``.
|
| 30 |
+
|
| 31 |
+
.. _lookup-registration-api:
|
| 32 |
+
|
| 33 |
+
Registration API
|
| 34 |
+
================
|
| 35 |
+
|
| 36 |
+
Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to
|
| 37 |
+
register lookups on itself or its instances. The two prominent examples are
|
| 38 |
+
:class:`~django.db.models.Field`, the base class of all model fields, and
|
| 39 |
+
:class:`Transform`, the base class of all Django transforms.
|
| 40 |
+
|
| 41 |
+
.. class:: lookups.RegisterLookupMixin
|
| 42 |
+
|
| 43 |
+
A mixin that implements the lookup API on a class.
|
| 44 |
+
|
| 45 |
+
.. classmethod:: register_lookup(lookup, lookup_name=None)
|
| 46 |
+
|
| 47 |
+
Registers a new lookup in the class or class instance. For example::
|
| 48 |
+
|
| 49 |
+
DateField.register_lookup(YearExact)
|
| 50 |
+
User._meta.get_field("date_joined").register_lookup(MonthExact)
|
| 51 |
+
|
| 52 |
+
will register ``YearExact`` lookup on ``DateField`` and ``MonthExact``
|
| 53 |
+
lookup on the ``User.date_joined`` (you can use :ref:`Field Access API
|
| 54 |
+
<model-meta-field-api>` to retrieve a single field instance). It
|
| 55 |
+
overrides a lookup that already exists with the same name. Lookups
|
| 56 |
+
registered on field instances take precedence over the lookups
|
| 57 |
+
registered on classes. ``lookup_name`` will be used for this lookup if
|
| 58 |
+
provided, otherwise ``lookup.lookup_name`` will be used.
|
| 59 |
+
|
| 60 |
+
.. method:: get_lookup(lookup_name)
|
| 61 |
+
|
| 62 |
+
Returns the :class:`Lookup` named ``lookup_name`` registered in the
|
| 63 |
+
class or class instance depending on what calls it. The default
|
| 64 |
+
implementation looks recursively on all parent classes and checks if
|
| 65 |
+
any has a registered lookup named ``lookup_name``, returning the first
|
| 66 |
+
match. Instance lookups would override any class lookups with the same
|
| 67 |
+
``lookup_name``.
|
| 68 |
+
|
| 69 |
+
.. method:: get_lookups()
|
| 70 |
+
|
| 71 |
+
Returns a dictionary of each lookup name registered in the class or
|
| 72 |
+
class instance mapped to the :class:`Lookup` class.
|
| 73 |
+
|
| 74 |
+
.. method:: get_transform(transform_name)
|
| 75 |
+
|
| 76 |
+
Returns a :class:`Transform` named ``transform_name`` registered in the
|
| 77 |
+
class or class instance. The default implementation looks recursively
|
| 78 |
+
on all parent classes to check if any has the registered transform
|
| 79 |
+
named ``transform_name``, returning the first match.
|
| 80 |
+
|
| 81 |
+
For a class to be a lookup, it must follow the :ref:`Query Expression API
|
| 82 |
+
<query-expression>`. :class:`~Lookup` and :class:`~Transform` naturally
|
| 83 |
+
follow this API.
|
| 84 |
+
|
| 85 |
+
.. versionchanged:: 4.2
|
| 86 |
+
|
| 87 |
+
Support for registering lookups on :class:`~django.db.models.Field`
|
| 88 |
+
instances was added.
|
| 89 |
+
|
| 90 |
+
.. _query-expression:
|
| 91 |
+
|
| 92 |
+
The Query Expression API
|
| 93 |
+
========================
|
| 94 |
+
|
| 95 |
+
The query expression API is a common set of methods that classes define to be
|
| 96 |
+
usable in query expressions to translate themselves into SQL expressions. Direct
|
| 97 |
+
field references, aggregates, and ``Transform`` are examples that follow this
|
| 98 |
+
API. A class is said to follow the query expression API when it implements the
|
| 99 |
+
following methods:
|
| 100 |
+
|
| 101 |
+
.. method:: as_sql(compiler, connection)
|
| 102 |
+
|
| 103 |
+
Generates the SQL fragment for the expression. Returns a tuple
|
| 104 |
+
``(sql, params)``, where ``sql`` is the SQL string, and ``params`` is the
|
| 105 |
+
list or tuple of query parameters. The ``compiler`` is an ``SQLCompiler``
|
| 106 |
+
object, which has a ``compile()`` method that can be used to compile other
|
| 107 |
+
expressions. The ``connection`` is the connection used to execute the
|
| 108 |
+
query.
|
| 109 |
+
|
| 110 |
+
Calling ``expression.as_sql()`` is usually incorrect - instead
|
| 111 |
+
``compiler.compile(expression)`` should be used. The ``compiler.compile()``
|
| 112 |
+
method will take care of calling vendor-specific methods of the expression.
|
| 113 |
+
|
| 114 |
+
Custom keyword arguments may be defined on this method if it's likely that
|
| 115 |
+
``as_vendorname()`` methods or subclasses will need to supply data to
|
| 116 |
+
override the generation of the SQL string. See :meth:`Func.as_sql` for
|
| 117 |
+
example usage.
|
| 118 |
+
|
| 119 |
+
.. method:: as_vendorname(compiler, connection)
|
| 120 |
+
|
| 121 |
+
Works like ``as_sql()`` method. When an expression is compiled by
|
| 122 |
+
``compiler.compile()``, Django will first try to call ``as_vendorname()``,
|
| 123 |
+
where ``vendorname`` is the vendor name of the backend used for executing
|
| 124 |
+
the query. The ``vendorname`` is one of ``postgresql``, ``oracle``,
|
| 125 |
+
``sqlite``, or ``mysql`` for Django's built-in backends.
|
| 126 |
+
|
| 127 |
+
.. method:: get_lookup(lookup_name)
|
| 128 |
+
|
| 129 |
+
Must return the lookup named ``lookup_name``. For instance, by returning
|
| 130 |
+
``self.output_field.get_lookup(lookup_name)``.
|
| 131 |
+
|
| 132 |
+
.. method:: get_transform(transform_name)
|
| 133 |
+
|
| 134 |
+
Must return the lookup named ``transform_name``. For instance, by returning
|
| 135 |
+
``self.output_field.get_transform(transform_name)``.
|
| 136 |
+
|
| 137 |
+
.. attribute:: output_field
|
| 138 |
+
|
| 139 |
+
Defines the type of class returned by the ``get_lookup()`` method. It must
|
| 140 |
+
be a :class:`~django.db.models.Field` instance.
|
| 141 |
+
|
| 142 |
+
``Transform`` reference
|
| 143 |
+
=======================
|
| 144 |
+
|
| 145 |
+
.. class:: Transform
|
| 146 |
+
|
| 147 |
+
A ``Transform`` is a generic class to implement field transformations. A
|
| 148 |
+
prominent example is ``__year`` that transforms a ``DateField`` into a
|
| 149 |
+
``IntegerField``.
|
| 150 |
+
|
| 151 |
+
The notation to use a ``Transform`` in a lookup expression is
|
| 152 |
+
``<expression>__<transformation>`` (e.g. ``date__year``).
|
| 153 |
+
|
| 154 |
+
This class follows the :ref:`Query Expression API <query-expression>`, which
|
| 155 |
+
implies that you can use ``<expression>__<transform1>__<transform2>``. It's
|
| 156 |
+
a specialized :ref:`Func() expression <func-expressions>` that only accepts
|
| 157 |
+
one argument. It can also be used on the right hand side of a filter or
|
| 158 |
+
directly as an annotation.
|
| 159 |
+
|
| 160 |
+
.. attribute:: bilateral
|
| 161 |
+
|
| 162 |
+
A boolean indicating whether this transformation should apply to both
|
| 163 |
+
``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in
|
| 164 |
+
the same order as they appear in the lookup expression. By default it is set
|
| 165 |
+
to ``False``. For example usage, see :doc:`/howto/custom-lookups`.
|
| 166 |
+
|
| 167 |
+
.. attribute:: lhs
|
| 168 |
+
|
| 169 |
+
The left-hand side - what is being transformed. It must follow the
|
| 170 |
+
:ref:`Query Expression API <query-expression>`.
|
| 171 |
+
|
| 172 |
+
.. attribute:: lookup_name
|
| 173 |
+
|
| 174 |
+
The name of the lookup, used for identifying it on parsing query
|
| 175 |
+
expressions. It cannot contain the string ``"__"``.
|
| 176 |
+
|
| 177 |
+
.. attribute:: output_field
|
| 178 |
+
|
| 179 |
+
Defines the class this transformation outputs. It must be a
|
| 180 |
+
:class:`~django.db.models.Field` instance. By default is the same as
|
| 181 |
+
its ``lhs.output_field``.
|
| 182 |
+
|
| 183 |
+
``Lookup`` reference
|
| 184 |
+
====================
|
| 185 |
+
|
| 186 |
+
.. class:: Lookup
|
| 187 |
+
|
| 188 |
+
A ``Lookup`` is a generic class to implement lookups. A lookup is a query
|
| 189 |
+
expression with a left-hand side, :attr:`lhs`; a right-hand side,
|
| 190 |
+
:attr:`rhs`; and a ``lookup_name`` that is used to produce a boolean
|
| 191 |
+
comparison between ``lhs`` and ``rhs`` such as ``lhs in rhs`` or
|
| 192 |
+
``lhs > rhs``.
|
| 193 |
+
|
| 194 |
+
The primary notation to use a lookup in an expression is
|
| 195 |
+
``<lhs>__<lookup_name>=<rhs>``. Lookups can also be used directly in
|
| 196 |
+
``QuerySet`` filters::
|
| 197 |
+
|
| 198 |
+
Book.objects.filter(LessThan(F("word_count"), 7500))
|
| 199 |
+
|
| 200 |
+
…or annotations::
|
| 201 |
+
|
| 202 |
+
Book.objects.annotate(is_short_story=LessThan(F("word_count"), 7500))
|
| 203 |
+
|
| 204 |
+
.. attribute:: lhs
|
| 205 |
+
|
| 206 |
+
The left-hand side - what is being looked up. The object typically
|
| 207 |
+
follows the :ref:`Query Expression API <query-expression>`. It may also
|
| 208 |
+
be a plain value.
|
| 209 |
+
|
| 210 |
+
.. attribute:: rhs
|
| 211 |
+
|
| 212 |
+
The right-hand side - what ``lhs`` is being compared against. It can be
|
| 213 |
+
a plain value, or something that compiles into SQL, typically an
|
| 214 |
+
``F()`` object or a ``QuerySet``.
|
| 215 |
+
|
| 216 |
+
.. attribute:: lookup_name
|
| 217 |
+
|
| 218 |
+
The name of this lookup, used to identify it on parsing query
|
| 219 |
+
expressions. It cannot contain the string ``"__"``.
|
| 220 |
+
|
| 221 |
+
.. method:: process_lhs(compiler, connection, lhs=None)
|
| 222 |
+
|
| 223 |
+
Returns a tuple ``(lhs_string, lhs_params)``, as returned by
|
| 224 |
+
``compiler.compile(lhs)``. This method can be overridden to tune how
|
| 225 |
+
the ``lhs`` is processed.
|
| 226 |
+
|
| 227 |
+
``compiler`` is an ``SQLCompiler`` object, to be used like
|
| 228 |
+
``compiler.compile(lhs)`` for compiling ``lhs``. The ``connection``
|
| 229 |
+
can be used for compiling vendor specific SQL. If ``lhs`` is not
|
| 230 |
+
``None``, use it as the processed ``lhs`` instead of ``self.lhs``.
|
| 231 |
+
|
| 232 |
+
.. method:: process_rhs(compiler, connection)
|
| 233 |
+
|
| 234 |
+
Behaves the same way as :meth:`process_lhs`, for the right-hand side.
|
testbed/django__django/docs/ref/models/meta.txt
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===================
|
| 2 |
+
Model ``_meta`` API
|
| 3 |
+
===================
|
| 4 |
+
|
| 5 |
+
.. module:: django.db.models.options
|
| 6 |
+
:synopsis: Model meta-class layer
|
| 7 |
+
|
| 8 |
+
.. class:: Options
|
| 9 |
+
|
| 10 |
+
The model ``_meta`` API is at the core of the Django ORM. It enables other
|
| 11 |
+
parts of the system such as lookups, queries, forms, and the admin to
|
| 12 |
+
understand the capabilities of each model. The API is accessible through
|
| 13 |
+
the ``_meta`` attribute of each model class, which is an instance of an
|
| 14 |
+
``django.db.models.options.Options`` object.
|
| 15 |
+
|
| 16 |
+
Methods that it provides can be used to:
|
| 17 |
+
|
| 18 |
+
* Retrieve all field instances of a model
|
| 19 |
+
* Retrieve a single field instance of a model by name
|
| 20 |
+
|
| 21 |
+
.. _model-meta-field-api:
|
| 22 |
+
|
| 23 |
+
Field access API
|
| 24 |
+
================
|
| 25 |
+
|
| 26 |
+
Retrieving a single field instance of a model by name
|
| 27 |
+
-----------------------------------------------------
|
| 28 |
+
|
| 29 |
+
.. method:: Options.get_field(field_name)
|
| 30 |
+
|
| 31 |
+
Returns the field instance given a name of a field.
|
| 32 |
+
|
| 33 |
+
``field_name`` can be the name of a field on the model, a field
|
| 34 |
+
on an abstract or inherited model, or a field defined on another
|
| 35 |
+
model that points to the model. In the latter case, the ``field_name``
|
| 36 |
+
will be (in order of preference) the :attr:`~.ForeignKey.related_query_name`
|
| 37 |
+
set by the user, the :attr:`~.ForeignKey.related_name` set by the user, or
|
| 38 |
+
the name automatically generated by Django.
|
| 39 |
+
|
| 40 |
+
:attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved
|
| 41 |
+
by name.
|
| 42 |
+
|
| 43 |
+
If a field with the given name is not found a
|
| 44 |
+
:class:`~django.core.exceptions.FieldDoesNotExist` exception will be
|
| 45 |
+
raised.
|
| 46 |
+
|
| 47 |
+
.. code-block:: pycon
|
| 48 |
+
|
| 49 |
+
>>> from django.contrib.auth.models import User
|
| 50 |
+
|
| 51 |
+
# A field on the model
|
| 52 |
+
>>> User._meta.get_field("username")
|
| 53 |
+
<django.db.models.fields.CharField: username>
|
| 54 |
+
|
| 55 |
+
# A field from another model that has a relation with the current model
|
| 56 |
+
>>> User._meta.get_field("logentry")
|
| 57 |
+
<ManyToOneRel: admin.logentry>
|
| 58 |
+
|
| 59 |
+
# A non existent field
|
| 60 |
+
>>> User._meta.get_field("does_not_exist")
|
| 61 |
+
Traceback (most recent call last):
|
| 62 |
+
...
|
| 63 |
+
FieldDoesNotExist: User has no field named 'does_not_exist'
|
| 64 |
+
|
| 65 |
+
Retrieving all field instances of a model
|
| 66 |
+
-----------------------------------------
|
| 67 |
+
|
| 68 |
+
.. method:: Options.get_fields(include_parents=True, include_hidden=False)
|
| 69 |
+
|
| 70 |
+
Returns a tuple of fields associated with a model. ``get_fields()`` accepts
|
| 71 |
+
two parameters that can be used to control which fields are returned:
|
| 72 |
+
|
| 73 |
+
``include_parents``
|
| 74 |
+
``True`` by default. Recursively includes fields defined on parent
|
| 75 |
+
classes. If set to ``False``, ``get_fields()`` will only search for
|
| 76 |
+
fields declared directly on the current model. Fields from models that
|
| 77 |
+
directly inherit from abstract models or proxy classes are considered
|
| 78 |
+
to be local, not on the parent.
|
| 79 |
+
|
| 80 |
+
``include_hidden``
|
| 81 |
+
``False`` by default. If set to ``True``, ``get_fields()`` will include
|
| 82 |
+
fields that are used to back other field's functionality. This will
|
| 83 |
+
also include any fields that have a ``related_name`` (such
|
| 84 |
+
as :class:`~django.db.models.ManyToManyField`, or
|
| 85 |
+
:class:`~django.db.models.ForeignKey`) that start with a "+".
|
| 86 |
+
|
| 87 |
+
.. code-block:: pycon
|
| 88 |
+
|
| 89 |
+
>>> from django.contrib.auth.models import User
|
| 90 |
+
>>> User._meta.get_fields()
|
| 91 |
+
(<ManyToOneRel: admin.logentry>,
|
| 92 |
+
<django.db.models.fields.AutoField: id>,
|
| 93 |
+
<django.db.models.fields.CharField: password>,
|
| 94 |
+
<django.db.models.fields.DateTimeField: last_login>,
|
| 95 |
+
<django.db.models.fields.BooleanField: is_superuser>,
|
| 96 |
+
<django.db.models.fields.CharField: username>,
|
| 97 |
+
<django.db.models.fields.CharField: first_name>,
|
| 98 |
+
<django.db.models.fields.CharField: last_name>,
|
| 99 |
+
<django.db.models.fields.EmailField: email>,
|
| 100 |
+
<django.db.models.fields.BooleanField: is_staff>,
|
| 101 |
+
<django.db.models.fields.BooleanField: is_active>,
|
| 102 |
+
<django.db.models.fields.DateTimeField: date_joined>,
|
| 103 |
+
<django.db.models.fields.related.ManyToManyField: groups>,
|
| 104 |
+
<django.db.models.fields.related.ManyToManyField: user_permissions>)
|
| 105 |
+
|
| 106 |
+
# Also include hidden fields.
|
| 107 |
+
>>> User._meta.get_fields(include_hidden=True)
|
| 108 |
+
(<ManyToOneRel: auth.user_groups>,
|
| 109 |
+
<ManyToOneRel: auth.user_user_permissions>,
|
| 110 |
+
<ManyToOneRel: admin.logentry>,
|
| 111 |
+
<django.db.models.fields.AutoField: id>,
|
| 112 |
+
<django.db.models.fields.CharField: password>,
|
| 113 |
+
<django.db.models.fields.DateTimeField: last_login>,
|
| 114 |
+
<django.db.models.fields.BooleanField: is_superuser>,
|
| 115 |
+
<django.db.models.fields.CharField: username>,
|
| 116 |
+
<django.db.models.fields.CharField: first_name>,
|
| 117 |
+
<django.db.models.fields.CharField: last_name>,
|
| 118 |
+
<django.db.models.fields.EmailField: email>,
|
| 119 |
+
<django.db.models.fields.BooleanField: is_staff>,
|
| 120 |
+
<django.db.models.fields.BooleanField: is_active>,
|
| 121 |
+
<django.db.models.fields.DateTimeField: date_joined>,
|
| 122 |
+
<django.db.models.fields.related.ManyToManyField: groups>,
|
| 123 |
+
<django.db.models.fields.related.ManyToManyField: user_permissions>)
|
testbed/django__django/docs/ref/request-response.txt
ADDED
|
@@ -0,0 +1,1347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Request and response objects
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
.. module:: django.http
|
| 6 |
+
:synopsis: Classes dealing with HTTP requests and responses.
|
| 7 |
+
|
| 8 |
+
Quick overview
|
| 9 |
+
==============
|
| 10 |
+
|
| 11 |
+
Django uses request and response objects to pass state through the system.
|
| 12 |
+
|
| 13 |
+
When a page is requested, Django creates an :class:`HttpRequest` object that
|
| 14 |
+
contains metadata about the request. Then Django loads the appropriate view,
|
| 15 |
+
passing the :class:`HttpRequest` as the first argument to the view function.
|
| 16 |
+
Each view is responsible for returning an :class:`HttpResponse` object.
|
| 17 |
+
|
| 18 |
+
This document explains the APIs for :class:`HttpRequest` and
|
| 19 |
+
:class:`HttpResponse` objects, which are defined in the :mod:`django.http`
|
| 20 |
+
module.
|
| 21 |
+
|
| 22 |
+
``HttpRequest`` objects
|
| 23 |
+
=======================
|
| 24 |
+
|
| 25 |
+
.. class:: HttpRequest
|
| 26 |
+
|
| 27 |
+
.. _httprequest-attributes:
|
| 28 |
+
|
| 29 |
+
Attributes
|
| 30 |
+
----------
|
| 31 |
+
|
| 32 |
+
All attributes should be considered read-only, unless stated otherwise.
|
| 33 |
+
|
| 34 |
+
.. attribute:: HttpRequest.scheme
|
| 35 |
+
|
| 36 |
+
A string representing the scheme of the request (``http`` or ``https``
|
| 37 |
+
usually).
|
| 38 |
+
|
| 39 |
+
.. attribute:: HttpRequest.body
|
| 40 |
+
|
| 41 |
+
The raw HTTP request body as a bytestring. This is useful for processing
|
| 42 |
+
data in different ways than conventional HTML forms: binary images,
|
| 43 |
+
XML payload etc. For processing conventional form data, use
|
| 44 |
+
:attr:`HttpRequest.POST`.
|
| 45 |
+
|
| 46 |
+
You can also read from an ``HttpRequest`` using a file-like interface with
|
| 47 |
+
:meth:`HttpRequest.read` or :meth:`HttpRequest.readline`. Accessing
|
| 48 |
+
the ``body`` attribute *after* reading the request with either of these I/O
|
| 49 |
+
stream methods will produce a ``RawPostDataException``.
|
| 50 |
+
|
| 51 |
+
.. attribute:: HttpRequest.path
|
| 52 |
+
|
| 53 |
+
A string representing the full path to the requested page, not including
|
| 54 |
+
the scheme, domain, or query string.
|
| 55 |
+
|
| 56 |
+
Example: ``"/music/bands/the_beatles/"``
|
| 57 |
+
|
| 58 |
+
.. attribute:: HttpRequest.path_info
|
| 59 |
+
|
| 60 |
+
Under some web server configurations, the portion of the URL after the
|
| 61 |
+
host name is split up into a script prefix portion and a path info
|
| 62 |
+
portion. The ``path_info`` attribute always contains the path info portion
|
| 63 |
+
of the path, no matter what web server is being used. Using this instead
|
| 64 |
+
of :attr:`~HttpRequest.path` can make your code easier to move between
|
| 65 |
+
test and deployment servers.
|
| 66 |
+
|
| 67 |
+
For example, if the ``WSGIScriptAlias`` for your application is set to
|
| 68 |
+
``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"``
|
| 69 |
+
and ``path_info`` would be ``"/music/bands/the_beatles/"``.
|
| 70 |
+
|
| 71 |
+
.. attribute:: HttpRequest.method
|
| 72 |
+
|
| 73 |
+
A string representing the HTTP method used in the request. This is
|
| 74 |
+
guaranteed to be uppercase. For example::
|
| 75 |
+
|
| 76 |
+
if request.method == "GET":
|
| 77 |
+
do_something()
|
| 78 |
+
elif request.method == "POST":
|
| 79 |
+
do_something_else()
|
| 80 |
+
|
| 81 |
+
.. attribute:: HttpRequest.encoding
|
| 82 |
+
|
| 83 |
+
A string representing the current encoding used to decode form submission
|
| 84 |
+
data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is
|
| 85 |
+
used). You can write to this attribute to change the encoding used when
|
| 86 |
+
accessing the form data. Any subsequent attribute accesses (such as reading
|
| 87 |
+
from :attr:`GET` or :attr:`POST`) will use the new ``encoding`` value.
|
| 88 |
+
Useful if you know the form data is not in the :setting:`DEFAULT_CHARSET`
|
| 89 |
+
encoding.
|
| 90 |
+
|
| 91 |
+
.. attribute:: HttpRequest.content_type
|
| 92 |
+
|
| 93 |
+
A string representing the MIME type of the request, parsed from the
|
| 94 |
+
``CONTENT_TYPE`` header.
|
| 95 |
+
|
| 96 |
+
.. attribute:: HttpRequest.content_params
|
| 97 |
+
|
| 98 |
+
A dictionary of key/value parameters included in the ``CONTENT_TYPE``
|
| 99 |
+
header.
|
| 100 |
+
|
| 101 |
+
.. attribute:: HttpRequest.GET
|
| 102 |
+
|
| 103 |
+
A dictionary-like object containing all given HTTP GET parameters. See the
|
| 104 |
+
:class:`QueryDict` documentation below.
|
| 105 |
+
|
| 106 |
+
.. attribute:: HttpRequest.POST
|
| 107 |
+
|
| 108 |
+
A dictionary-like object containing all given HTTP POST parameters,
|
| 109 |
+
providing that the request contains form data. See the
|
| 110 |
+
:class:`QueryDict` documentation below. If you need to access raw or
|
| 111 |
+
non-form data posted in the request, access this through the
|
| 112 |
+
:attr:`HttpRequest.body` attribute instead.
|
| 113 |
+
|
| 114 |
+
It's possible that a request can come in via POST with an empty ``POST``
|
| 115 |
+
dictionary -- if, say, a form is requested via the POST HTTP method but
|
| 116 |
+
does not include form data. Therefore, you shouldn't use ``if request.POST``
|
| 117 |
+
to check for use of the POST method; instead, use ``if request.method ==
|
| 118 |
+
"POST"`` (see :attr:`HttpRequest.method`).
|
| 119 |
+
|
| 120 |
+
``POST`` does *not* include file-upload information. See :attr:`FILES`.
|
| 121 |
+
|
| 122 |
+
.. attribute:: HttpRequest.COOKIES
|
| 123 |
+
|
| 124 |
+
A dictionary containing all cookies. Keys and values are strings.
|
| 125 |
+
|
| 126 |
+
.. attribute:: HttpRequest.FILES
|
| 127 |
+
|
| 128 |
+
A dictionary-like object containing all uploaded files. Each key in
|
| 129 |
+
``FILES`` is the ``name`` from the ``<input type="file" name="">``. Each
|
| 130 |
+
value in ``FILES`` is an :class:`~django.core.files.uploadedfile.UploadedFile`.
|
| 131 |
+
|
| 132 |
+
See :doc:`/topics/files` for more information.
|
| 133 |
+
|
| 134 |
+
``FILES`` will only contain data if the request method was POST and the
|
| 135 |
+
``<form>`` that posted to the request had ``enctype="multipart/form-data"``.
|
| 136 |
+
Otherwise, ``FILES`` will be a blank dictionary-like object.
|
| 137 |
+
|
| 138 |
+
.. attribute:: HttpRequest.META
|
| 139 |
+
|
| 140 |
+
A dictionary containing all available HTTP headers. Available headers
|
| 141 |
+
depend on the client and server, but here are some examples:
|
| 142 |
+
|
| 143 |
+
* ``CONTENT_LENGTH`` -- The length of the request body (as a string).
|
| 144 |
+
* ``CONTENT_TYPE`` -- The MIME type of the request body.
|
| 145 |
+
* ``HTTP_ACCEPT`` -- Acceptable content types for the response.
|
| 146 |
+
* ``HTTP_ACCEPT_ENCODING`` -- Acceptable encodings for the response.
|
| 147 |
+
* ``HTTP_ACCEPT_LANGUAGE`` -- Acceptable languages for the response.
|
| 148 |
+
* ``HTTP_HOST`` -- The HTTP Host header sent by the client.
|
| 149 |
+
* ``HTTP_REFERER`` -- The referring page, if any.
|
| 150 |
+
* ``HTTP_USER_AGENT`` -- The client's user-agent string.
|
| 151 |
+
* ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
|
| 152 |
+
* ``REMOTE_ADDR`` -- The IP address of the client.
|
| 153 |
+
* ``REMOTE_HOST`` -- The hostname of the client.
|
| 154 |
+
* ``REMOTE_USER`` -- The user authenticated by the web server, if any.
|
| 155 |
+
* ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
|
| 156 |
+
* ``SERVER_NAME`` -- The hostname of the server.
|
| 157 |
+
* ``SERVER_PORT`` -- The port of the server (as a string).
|
| 158 |
+
|
| 159 |
+
With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
|
| 160 |
+
above, any HTTP headers in the request are converted to ``META`` keys by
|
| 161 |
+
converting all characters to uppercase, replacing any hyphens with
|
| 162 |
+
underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
|
| 163 |
+
header called ``X-Bender`` would be mapped to the ``META`` key
|
| 164 |
+
``HTTP_X_BENDER``.
|
| 165 |
+
|
| 166 |
+
Note that :djadmin:`runserver` strips all headers with underscores in the
|
| 167 |
+
name, so you won't see them in ``META``. This prevents header-spoofing
|
| 168 |
+
based on ambiguity between underscores and dashes both being normalizing to
|
| 169 |
+
underscores in WSGI environment variables. It matches the behavior of
|
| 170 |
+
web servers like Nginx and Apache 2.4+.
|
| 171 |
+
|
| 172 |
+
:attr:`HttpRequest.headers` is a simpler way to access all HTTP-prefixed
|
| 173 |
+
headers, plus ``CONTENT_LENGTH`` and ``CONTENT_TYPE``.
|
| 174 |
+
|
| 175 |
+
.. attribute:: HttpRequest.headers
|
| 176 |
+
|
| 177 |
+
A case insensitive, dict-like object that provides access to all
|
| 178 |
+
HTTP-prefixed headers (plus ``Content-Length`` and ``Content-Type``) from
|
| 179 |
+
the request.
|
| 180 |
+
|
| 181 |
+
The name of each header is stylized with title-casing (e.g. ``User-Agent``)
|
| 182 |
+
when it's displayed. You can access headers case-insensitively:
|
| 183 |
+
|
| 184 |
+
.. code-block:: pycon
|
| 185 |
+
|
| 186 |
+
>>> request.headers
|
| 187 |
+
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}
|
| 188 |
+
|
| 189 |
+
>>> "User-Agent" in request.headers
|
| 190 |
+
True
|
| 191 |
+
>>> "user-agent" in request.headers
|
| 192 |
+
True
|
| 193 |
+
|
| 194 |
+
>>> request.headers["User-Agent"]
|
| 195 |
+
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
|
| 196 |
+
>>> request.headers["user-agent"]
|
| 197 |
+
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
|
| 198 |
+
|
| 199 |
+
>>> request.headers.get("User-Agent")
|
| 200 |
+
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
|
| 201 |
+
>>> request.headers.get("user-agent")
|
| 202 |
+
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
|
| 203 |
+
|
| 204 |
+
For use in, for example, Django templates, headers can also be looked up
|
| 205 |
+
using underscores in place of hyphens:
|
| 206 |
+
|
| 207 |
+
.. code-block:: html+django
|
| 208 |
+
|
| 209 |
+
{{ request.headers.user_agent }}
|
| 210 |
+
|
| 211 |
+
.. attribute:: HttpRequest.resolver_match
|
| 212 |
+
|
| 213 |
+
An instance of :class:`~django.urls.ResolverMatch` representing the
|
| 214 |
+
resolved URL. This attribute is only set after URL resolving took place,
|
| 215 |
+
which means it's available in all views but not in middleware which are
|
| 216 |
+
executed before URL resolving takes place (you can use it in
|
| 217 |
+
:meth:`process_view` though).
|
| 218 |
+
|
| 219 |
+
Attributes set by application code
|
| 220 |
+
----------------------------------
|
| 221 |
+
|
| 222 |
+
Django doesn't set these attributes itself but makes use of them if set by your
|
| 223 |
+
application.
|
| 224 |
+
|
| 225 |
+
.. attribute:: HttpRequest.current_app
|
| 226 |
+
|
| 227 |
+
The :ttag:`url` template tag will use its value as the ``current_app``
|
| 228 |
+
argument to :func:`~django.urls.reverse()`.
|
| 229 |
+
|
| 230 |
+
.. attribute:: HttpRequest.urlconf
|
| 231 |
+
|
| 232 |
+
This will be used as the root URLconf for the current request, overriding
|
| 233 |
+
the :setting:`ROOT_URLCONF` setting. See
|
| 234 |
+
:ref:`how-django-processes-a-request` for details.
|
| 235 |
+
|
| 236 |
+
``urlconf`` can be set to ``None`` to revert any changes made by previous
|
| 237 |
+
middleware and return to using the :setting:`ROOT_URLCONF`.
|
| 238 |
+
|
| 239 |
+
.. attribute:: HttpRequest.exception_reporter_filter
|
| 240 |
+
|
| 241 |
+
This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER`
|
| 242 |
+
for the current request. See :ref:`custom-error-reports` for details.
|
| 243 |
+
|
| 244 |
+
.. attribute:: HttpRequest.exception_reporter_class
|
| 245 |
+
|
| 246 |
+
This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER` for the
|
| 247 |
+
current request. See :ref:`custom-error-reports` for details.
|
| 248 |
+
|
| 249 |
+
Attributes set by middleware
|
| 250 |
+
----------------------------
|
| 251 |
+
|
| 252 |
+
Some of the middleware included in Django's contrib apps set attributes on the
|
| 253 |
+
request. If you don't see the attribute on a request, be sure the appropriate
|
| 254 |
+
middleware class is listed in :setting:`MIDDLEWARE`.
|
| 255 |
+
|
| 256 |
+
.. attribute:: HttpRequest.session
|
| 257 |
+
|
| 258 |
+
From the :class:`~django.contrib.sessions.middleware.SessionMiddleware`: A
|
| 259 |
+
readable and writable, dictionary-like object that represents the current
|
| 260 |
+
session.
|
| 261 |
+
|
| 262 |
+
.. attribute:: HttpRequest.site
|
| 263 |
+
|
| 264 |
+
From the :class:`~django.contrib.sites.middleware.CurrentSiteMiddleware`:
|
| 265 |
+
An instance of :class:`~django.contrib.sites.models.Site` or
|
| 266 |
+
:class:`~django.contrib.sites.requests.RequestSite` as returned by
|
| 267 |
+
:func:`~django.contrib.sites.shortcuts.get_current_site()`
|
| 268 |
+
representing the current site.
|
| 269 |
+
|
| 270 |
+
.. attribute:: HttpRequest.user
|
| 271 |
+
|
| 272 |
+
From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:
|
| 273 |
+
An instance of :setting:`AUTH_USER_MODEL` representing the currently
|
| 274 |
+
logged-in user. If the user isn't currently logged in, ``user`` will be set
|
| 275 |
+
to an instance of :class:`~django.contrib.auth.models.AnonymousUser`. You
|
| 276 |
+
can tell them apart with
|
| 277 |
+
:attr:`~django.contrib.auth.models.User.is_authenticated`, like so::
|
| 278 |
+
|
| 279 |
+
if request.user.is_authenticated:
|
| 280 |
+
... # Do something for logged-in users.
|
| 281 |
+
else:
|
| 282 |
+
... # Do something for anonymous users.
|
| 283 |
+
|
| 284 |
+
The :meth:`auser` method does the same thing but can be used from async
|
| 285 |
+
contexts.
|
| 286 |
+
|
| 287 |
+
Methods
|
| 288 |
+
-------
|
| 289 |
+
|
| 290 |
+
.. method:: HttpRequest.auser()
|
| 291 |
+
|
| 292 |
+
.. versionadded:: 5.0
|
| 293 |
+
|
| 294 |
+
From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:
|
| 295 |
+
Coroutine. Returns an instance of :setting:`AUTH_USER_MODEL` representing
|
| 296 |
+
the currently logged-in user. If the user isn't currently logged in,
|
| 297 |
+
``auser`` will return an instance of
|
| 298 |
+
:class:`~django.contrib.auth.models.AnonymousUser`. This is similar to the
|
| 299 |
+
:attr:`user` attribute but it works in async contexts.
|
| 300 |
+
|
| 301 |
+
.. method:: HttpRequest.get_host()
|
| 302 |
+
|
| 303 |
+
Returns the originating host of the request using information from the
|
| 304 |
+
``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled)
|
| 305 |
+
and ``HTTP_HOST`` headers, in that order. If they don't provide a value,
|
| 306 |
+
the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as
|
| 307 |
+
detailed in :pep:`3333`.
|
| 308 |
+
|
| 309 |
+
Example: ``"127.0.0.1:8000"``
|
| 310 |
+
|
| 311 |
+
Raises ``django.core.exceptions.DisallowedHost`` if the host is not in
|
| 312 |
+
:setting:`ALLOWED_HOSTS` or the domain name is invalid according to
|
| 313 |
+
:rfc:`1034`/:rfc:`1035 <1035>`.
|
| 314 |
+
|
| 315 |
+
.. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
|
| 316 |
+
behind multiple proxies. One solution is to use middleware to rewrite
|
| 317 |
+
the proxy headers, as in the following example::
|
| 318 |
+
|
| 319 |
+
class MultipleProxyMiddleware:
|
| 320 |
+
FORWARDED_FOR_FIELDS = [
|
| 321 |
+
"HTTP_X_FORWARDED_FOR",
|
| 322 |
+
"HTTP_X_FORWARDED_HOST",
|
| 323 |
+
"HTTP_X_FORWARDED_SERVER",
|
| 324 |
+
]
|
| 325 |
+
|
| 326 |
+
def __init__(self, get_response):
|
| 327 |
+
self.get_response = get_response
|
| 328 |
+
|
| 329 |
+
def __call__(self, request):
|
| 330 |
+
"""
|
| 331 |
+
Rewrites the proxy headers so that only the most
|
| 332 |
+
recent proxy is used.
|
| 333 |
+
"""
|
| 334 |
+
for field in self.FORWARDED_FOR_FIELDS:
|
| 335 |
+
if field in request.META:
|
| 336 |
+
if "," in request.META[field]:
|
| 337 |
+
parts = request.META[field].split(",")
|
| 338 |
+
request.META[field] = parts[-1].strip()
|
| 339 |
+
return self.get_response(request)
|
| 340 |
+
|
| 341 |
+
This middleware should be positioned before any other middleware that
|
| 342 |
+
relies on the value of :meth:`~HttpRequest.get_host()` -- for instance,
|
| 343 |
+
:class:`~django.middleware.common.CommonMiddleware` or
|
| 344 |
+
:class:`~django.middleware.csrf.CsrfViewMiddleware`.
|
| 345 |
+
|
| 346 |
+
.. method:: HttpRequest.get_port()
|
| 347 |
+
|
| 348 |
+
Returns the originating port of the request using information from the
|
| 349 |
+
``HTTP_X_FORWARDED_PORT`` (if :setting:`USE_X_FORWARDED_PORT` is enabled)
|
| 350 |
+
and ``SERVER_PORT`` ``META`` variables, in that order.
|
| 351 |
+
|
| 352 |
+
.. method:: HttpRequest.get_full_path()
|
| 353 |
+
|
| 354 |
+
Returns the ``path``, plus an appended query string, if applicable.
|
| 355 |
+
|
| 356 |
+
Example: ``"/music/bands/the_beatles/?print=true"``
|
| 357 |
+
|
| 358 |
+
.. method:: HttpRequest.get_full_path_info()
|
| 359 |
+
|
| 360 |
+
Like :meth:`get_full_path`, but uses :attr:`path_info` instead of
|
| 361 |
+
:attr:`path`.
|
| 362 |
+
|
| 363 |
+
Example: ``"/minfo/music/bands/the_beatles/?print=true"``
|
| 364 |
+
|
| 365 |
+
.. method:: HttpRequest.build_absolute_uri(location=None)
|
| 366 |
+
|
| 367 |
+
Returns the absolute URI form of ``location``. If no location is provided,
|
| 368 |
+
the location will be set to ``request.get_full_path()``.
|
| 369 |
+
|
| 370 |
+
If the location is already an absolute URI, it will not be altered.
|
| 371 |
+
Otherwise the absolute URI is built using the server variables available in
|
| 372 |
+
this request. For example:
|
| 373 |
+
|
| 374 |
+
>>> request.build_absolute_uri()
|
| 375 |
+
'https://example.com/music/bands/the_beatles/?print=true'
|
| 376 |
+
>>> request.build_absolute_uri('/bands/')
|
| 377 |
+
'https://example.com/bands/'
|
| 378 |
+
>>> request.build_absolute_uri('https://example2.com/bands/')
|
| 379 |
+
'https://example2.com/bands/'
|
| 380 |
+
|
| 381 |
+
.. note::
|
| 382 |
+
|
| 383 |
+
Mixing HTTP and HTTPS on the same site is discouraged, therefore
|
| 384 |
+
:meth:`~HttpRequest.build_absolute_uri()` will always generate an
|
| 385 |
+
absolute URI with the same scheme the current request has. If you need
|
| 386 |
+
to redirect users to HTTPS, it's best to let your web server redirect
|
| 387 |
+
all HTTP traffic to HTTPS.
|
| 388 |
+
|
| 389 |
+
.. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
|
| 390 |
+
|
| 391 |
+
Returns a cookie value for a signed cookie, or raises a
|
| 392 |
+
``django.core.signing.BadSignature`` exception if the signature is
|
| 393 |
+
no longer valid. If you provide the ``default`` argument the exception
|
| 394 |
+
will be suppressed and that default value will be returned instead.
|
| 395 |
+
|
| 396 |
+
The optional ``salt`` argument can be used to provide extra protection
|
| 397 |
+
against brute force attacks on your secret key. If supplied, the
|
| 398 |
+
``max_age`` argument will be checked against the signed timestamp
|
| 399 |
+
attached to the cookie value to ensure the cookie is not older than
|
| 400 |
+
``max_age`` seconds.
|
| 401 |
+
|
| 402 |
+
For example:
|
| 403 |
+
|
| 404 |
+
.. code-block:: pycon
|
| 405 |
+
|
| 406 |
+
>>> request.get_signed_cookie("name")
|
| 407 |
+
'Tony'
|
| 408 |
+
>>> request.get_signed_cookie("name", salt="name-salt")
|
| 409 |
+
'Tony' # assuming cookie was set using the same salt
|
| 410 |
+
>>> request.get_signed_cookie("nonexistent-cookie")
|
| 411 |
+
KeyError: 'nonexistent-cookie'
|
| 412 |
+
>>> request.get_signed_cookie("nonexistent-cookie", False)
|
| 413 |
+
False
|
| 414 |
+
>>> request.get_signed_cookie("cookie-that-was-tampered-with")
|
| 415 |
+
BadSignature: ...
|
| 416 |
+
>>> request.get_signed_cookie("name", max_age=60)
|
| 417 |
+
SignatureExpired: Signature age 1677.3839159 > 60 seconds
|
| 418 |
+
>>> request.get_signed_cookie("name", False, max_age=60)
|
| 419 |
+
False
|
| 420 |
+
|
| 421 |
+
See :doc:`cryptographic signing </topics/signing>` for more information.
|
| 422 |
+
|
| 423 |
+
.. method:: HttpRequest.is_secure()
|
| 424 |
+
|
| 425 |
+
Returns ``True`` if the request is secure; that is, if it was made with
|
| 426 |
+
HTTPS.
|
| 427 |
+
|
| 428 |
+
.. method:: HttpRequest.accepts(mime_type)
|
| 429 |
+
|
| 430 |
+
Returns ``True`` if the request ``Accept`` header matches the ``mime_type``
|
| 431 |
+
argument:
|
| 432 |
+
|
| 433 |
+
.. code-block:: pycon
|
| 434 |
+
|
| 435 |
+
>>> request.accepts("text/html")
|
| 436 |
+
True
|
| 437 |
+
|
| 438 |
+
Most browsers send ``Accept: */*`` by default, so this would return
|
| 439 |
+
``True`` for all content types. Setting an explicit ``Accept`` header in
|
| 440 |
+
API requests can be useful for returning a different content type for those
|
| 441 |
+
consumers only. See :ref:`content-negotiation-example` of using
|
| 442 |
+
``accepts()`` to return different content to API consumers.
|
| 443 |
+
|
| 444 |
+
If a response varies depending on the content of the ``Accept`` header and
|
| 445 |
+
you are using some form of caching like Django's :mod:`cache middleware
|
| 446 |
+
<django.middleware.cache>`, you should decorate the view with
|
| 447 |
+
:func:`vary_on_headers('Accept')
|
| 448 |
+
<django.views.decorators.vary.vary_on_headers>` so that the responses are
|
| 449 |
+
properly cached.
|
| 450 |
+
|
| 451 |
+
.. method:: HttpRequest.read(size=None)
|
| 452 |
+
.. method:: HttpRequest.readline()
|
| 453 |
+
.. method:: HttpRequest.readlines()
|
| 454 |
+
.. method:: HttpRequest.__iter__()
|
| 455 |
+
|
| 456 |
+
Methods implementing a file-like interface for reading from an
|
| 457 |
+
``HttpRequest`` instance. This makes it possible to consume an incoming
|
| 458 |
+
request in a streaming fashion. A common use-case would be to process a
|
| 459 |
+
big XML payload with an iterative parser without constructing a whole
|
| 460 |
+
XML tree in memory.
|
| 461 |
+
|
| 462 |
+
Given this standard interface, an ``HttpRequest`` instance can be
|
| 463 |
+
passed directly to an XML parser such as
|
| 464 |
+
:class:`~xml.etree.ElementTree.ElementTree`::
|
| 465 |
+
|
| 466 |
+
import xml.etree.ElementTree as ET
|
| 467 |
+
|
| 468 |
+
for element in ET.iterparse(request):
|
| 469 |
+
process(element)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
``QueryDict`` objects
|
| 473 |
+
=====================
|
| 474 |
+
|
| 475 |
+
.. class:: QueryDict
|
| 476 |
+
|
| 477 |
+
In an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and
|
| 478 |
+
:attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``,
|
| 479 |
+
a dictionary-like class customized to deal with multiple values for the same
|
| 480 |
+
key. This is necessary because some HTML form elements, notably
|
| 481 |
+
``<select multiple>``, pass multiple values for the same key.
|
| 482 |
+
|
| 483 |
+
The ``QueryDict``\ s at ``request.POST`` and ``request.GET`` will be immutable
|
| 484 |
+
when accessed in a normal request/response cycle. To get a mutable version you
|
| 485 |
+
need to use :meth:`QueryDict.copy`.
|
| 486 |
+
|
| 487 |
+
Methods
|
| 488 |
+
-------
|
| 489 |
+
|
| 490 |
+
:class:`QueryDict` implements all the standard dictionary methods because it's
|
| 491 |
+
a subclass of dictionary. Exceptions are outlined here:
|
| 492 |
+
|
| 493 |
+
.. method:: QueryDict.__init__(query_string=None, mutable=False, encoding=None)
|
| 494 |
+
|
| 495 |
+
Instantiates a ``QueryDict`` object based on ``query_string``.
|
| 496 |
+
|
| 497 |
+
>>> QueryDict('a=1&a=2&c=3')
|
| 498 |
+
<QueryDict: {'a': ['1', '2'], 'c': ['3']}>
|
| 499 |
+
|
| 500 |
+
If ``query_string`` is not passed in, the resulting ``QueryDict`` will be
|
| 501 |
+
empty (it will have no keys or values).
|
| 502 |
+
|
| 503 |
+
Most ``QueryDict``\ s you encounter, and in particular those at
|
| 504 |
+
``request.POST`` and ``request.GET``, will be immutable. If you are
|
| 505 |
+
instantiating one yourself, you can make it mutable by passing
|
| 506 |
+
``mutable=True`` to its ``__init__()``.
|
| 507 |
+
|
| 508 |
+
Strings for setting both keys and values will be converted from ``encoding``
|
| 509 |
+
to ``str``. If ``encoding`` is not set, it defaults to
|
| 510 |
+
:setting:`DEFAULT_CHARSET`.
|
| 511 |
+
|
| 512 |
+
.. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)
|
| 513 |
+
|
| 514 |
+
Creates a new ``QueryDict`` with keys from ``iterable`` and each value
|
| 515 |
+
equal to ``value``. For example:
|
| 516 |
+
|
| 517 |
+
.. code-block:: pycon
|
| 518 |
+
|
| 519 |
+
>>> QueryDict.fromkeys(["a", "a", "b"], value="val")
|
| 520 |
+
<QueryDict: {'a': ['val', 'val'], 'b': ['val']}>
|
| 521 |
+
|
| 522 |
+
.. method:: QueryDict.__getitem__(key)
|
| 523 |
+
|
| 524 |
+
Returns the value for the given key. If the key has more than one value,
|
| 525 |
+
it returns the last value. Raises
|
| 526 |
+
``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
|
| 527 |
+
exist. (This is a subclass of Python's standard :exc:`KeyError`, so you can
|
| 528 |
+
stick to catching ``KeyError``.)
|
| 529 |
+
|
| 530 |
+
.. method:: QueryDict.__setitem__(key, value)
|
| 531 |
+
|
| 532 |
+
Sets the given key to ``[value]`` (a list whose single element is
|
| 533 |
+
``value``). Note that this, as other dictionary functions that have side
|
| 534 |
+
effects, can only be called on a mutable ``QueryDict`` (such as one that
|
| 535 |
+
was created via :meth:`QueryDict.copy`).
|
| 536 |
+
|
| 537 |
+
.. method:: QueryDict.__contains__(key)
|
| 538 |
+
|
| 539 |
+
Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
|
| 540 |
+
in request.GET``.
|
| 541 |
+
|
| 542 |
+
.. method:: QueryDict.get(key, default=None)
|
| 543 |
+
|
| 544 |
+
Uses the same logic as :meth:`__getitem__`, with a hook for returning a
|
| 545 |
+
default value if the key doesn't exist.
|
| 546 |
+
|
| 547 |
+
.. method:: QueryDict.setdefault(key, default=None)
|
| 548 |
+
|
| 549 |
+
Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally.
|
| 550 |
+
|
| 551 |
+
.. method:: QueryDict.update(other_dict)
|
| 552 |
+
|
| 553 |
+
Takes either a ``QueryDict`` or a dictionary. Like :meth:`dict.update`,
|
| 554 |
+
except it *appends* to the current dictionary items rather than replacing
|
| 555 |
+
them. For example:
|
| 556 |
+
|
| 557 |
+
.. code-block:: pycon
|
| 558 |
+
|
| 559 |
+
>>> q = QueryDict("a=1", mutable=True)
|
| 560 |
+
>>> q.update({"a": "2"})
|
| 561 |
+
>>> q.getlist("a")
|
| 562 |
+
['1', '2']
|
| 563 |
+
>>> q["a"] # returns the last
|
| 564 |
+
'2'
|
| 565 |
+
|
| 566 |
+
.. method:: QueryDict.items()
|
| 567 |
+
|
| 568 |
+
Like :meth:`dict.items`, except this uses the same last-value logic as
|
| 569 |
+
:meth:`__getitem__` and returns an iterator object instead of a view object.
|
| 570 |
+
For example:
|
| 571 |
+
|
| 572 |
+
.. code-block:: pycon
|
| 573 |
+
|
| 574 |
+
>>> q = QueryDict("a=1&a=2&a=3")
|
| 575 |
+
>>> list(q.items())
|
| 576 |
+
[('a', '3')]
|
| 577 |
+
|
| 578 |
+
.. method:: QueryDict.values()
|
| 579 |
+
|
| 580 |
+
Like :meth:`dict.values`, except this uses the same last-value logic as
|
| 581 |
+
:meth:`__getitem__` and returns an iterator instead of a view object. For
|
| 582 |
+
example:
|
| 583 |
+
|
| 584 |
+
.. code-block:: pycon
|
| 585 |
+
|
| 586 |
+
>>> q = QueryDict("a=1&a=2&a=3")
|
| 587 |
+
>>> list(q.values())
|
| 588 |
+
['3']
|
| 589 |
+
|
| 590 |
+
In addition, ``QueryDict`` has the following methods:
|
| 591 |
+
|
| 592 |
+
.. method:: QueryDict.copy()
|
| 593 |
+
|
| 594 |
+
Returns a copy of the object using :func:`copy.deepcopy`. This copy will
|
| 595 |
+
be mutable even if the original was not.
|
| 596 |
+
|
| 597 |
+
.. method:: QueryDict.getlist(key, default=None)
|
| 598 |
+
|
| 599 |
+
Returns a list of the data with the requested key. Returns an empty list if
|
| 600 |
+
the key doesn't exist and ``default`` is ``None``. It's guaranteed to
|
| 601 |
+
return a list unless the default value provided isn't a list.
|
| 602 |
+
|
| 603 |
+
.. method:: QueryDict.setlist(key, list_)
|
| 604 |
+
|
| 605 |
+
Sets the given key to ``list_`` (unlike :meth:`__setitem__`).
|
| 606 |
+
|
| 607 |
+
.. method:: QueryDict.appendlist(key, item)
|
| 608 |
+
|
| 609 |
+
Appends an item to the internal list associated with key.
|
| 610 |
+
|
| 611 |
+
.. method:: QueryDict.setlistdefault(key, default_list=None)
|
| 612 |
+
|
| 613 |
+
Like :meth:`setdefault`, except it takes a list of values instead of a
|
| 614 |
+
single value.
|
| 615 |
+
|
| 616 |
+
.. method:: QueryDict.lists()
|
| 617 |
+
|
| 618 |
+
Like :meth:`items()`, except it includes all values, as a list, for each
|
| 619 |
+
member of the dictionary. For example:
|
| 620 |
+
|
| 621 |
+
.. code-block:: pycon
|
| 622 |
+
|
| 623 |
+
>>> q = QueryDict("a=1&a=2&a=3")
|
| 624 |
+
>>> q.lists()
|
| 625 |
+
[('a', ['1', '2', '3'])]
|
| 626 |
+
|
| 627 |
+
.. method:: QueryDict.pop(key)
|
| 628 |
+
|
| 629 |
+
Returns a list of values for the given key and removes them from the
|
| 630 |
+
dictionary. Raises ``KeyError`` if the key does not exist. For example:
|
| 631 |
+
|
| 632 |
+
.. code-block:: pycon
|
| 633 |
+
|
| 634 |
+
>>> q = QueryDict("a=1&a=2&a=3", mutable=True)
|
| 635 |
+
>>> q.pop("a")
|
| 636 |
+
['1', '2', '3']
|
| 637 |
+
|
| 638 |
+
.. method:: QueryDict.popitem()
|
| 639 |
+
|
| 640 |
+
Removes an arbitrary member of the dictionary (since there's no concept
|
| 641 |
+
of ordering), and returns a two value tuple containing the key and a list
|
| 642 |
+
of all values for the key. Raises ``KeyError`` when called on an empty
|
| 643 |
+
dictionary. For example:
|
| 644 |
+
|
| 645 |
+
.. code-block:: pycon
|
| 646 |
+
|
| 647 |
+
>>> q = QueryDict("a=1&a=2&a=3", mutable=True)
|
| 648 |
+
>>> q.popitem()
|
| 649 |
+
('a', ['1', '2', '3'])
|
| 650 |
+
|
| 651 |
+
.. method:: QueryDict.dict()
|
| 652 |
+
|
| 653 |
+
Returns a ``dict`` representation of ``QueryDict``. For every (key, list)
|
| 654 |
+
pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
|
| 655 |
+
element of the list, using the same logic as :meth:`QueryDict.__getitem__`:
|
| 656 |
+
|
| 657 |
+
.. code-block:: pycon
|
| 658 |
+
|
| 659 |
+
>>> q = QueryDict("a=1&a=3&a=5")
|
| 660 |
+
>>> q.dict()
|
| 661 |
+
{'a': '5'}
|
| 662 |
+
|
| 663 |
+
.. method:: QueryDict.urlencode(safe=None)
|
| 664 |
+
|
| 665 |
+
Returns a string of the data in query string format. For example:
|
| 666 |
+
|
| 667 |
+
.. code-block:: pycon
|
| 668 |
+
|
| 669 |
+
>>> q = QueryDict("a=2&b=3&b=5")
|
| 670 |
+
>>> q.urlencode()
|
| 671 |
+
'a=2&b=3&b=5'
|
| 672 |
+
|
| 673 |
+
Use the ``safe`` parameter to pass characters which don't require encoding.
|
| 674 |
+
For example:
|
| 675 |
+
|
| 676 |
+
.. code-block:: pycon
|
| 677 |
+
|
| 678 |
+
>>> q = QueryDict(mutable=True)
|
| 679 |
+
>>> q["next"] = "/a&b/"
|
| 680 |
+
>>> q.urlencode(safe="/")
|
| 681 |
+
'next=/a%26b/'
|
| 682 |
+
|
| 683 |
+
``HttpResponse`` objects
|
| 684 |
+
========================
|
| 685 |
+
|
| 686 |
+
.. class:: HttpResponse
|
| 687 |
+
|
| 688 |
+
In contrast to :class:`HttpRequest` objects, which are created automatically by
|
| 689 |
+
Django, :class:`HttpResponse` objects are your responsibility. Each view you
|
| 690 |
+
write is responsible for instantiating, populating, and returning an
|
| 691 |
+
:class:`HttpResponse`.
|
| 692 |
+
|
| 693 |
+
The :class:`HttpResponse` class lives in the :mod:`django.http` module.
|
| 694 |
+
|
| 695 |
+
Usage
|
| 696 |
+
-----
|
| 697 |
+
|
| 698 |
+
Passing strings
|
| 699 |
+
~~~~~~~~~~~~~~~
|
| 700 |
+
|
| 701 |
+
Typical usage is to pass the contents of the page, as a string, bytestring,
|
| 702 |
+
or :class:`memoryview`, to the :class:`HttpResponse` constructor:
|
| 703 |
+
|
| 704 |
+
.. code-block:: pycon
|
| 705 |
+
|
| 706 |
+
>>> from django.http import HttpResponse
|
| 707 |
+
>>> response = HttpResponse("Here's the text of the web page.")
|
| 708 |
+
>>> response = HttpResponse("Text only, please.", content_type="text/plain")
|
| 709 |
+
>>> response = HttpResponse(b"Bytestrings are also accepted.")
|
| 710 |
+
>>> response = HttpResponse(memoryview(b"Memoryview as well."))
|
| 711 |
+
|
| 712 |
+
But if you want to add content incrementally, you can use ``response`` as a
|
| 713 |
+
file-like object:
|
| 714 |
+
|
| 715 |
+
.. code-block:: pycon
|
| 716 |
+
|
| 717 |
+
>>> response = HttpResponse()
|
| 718 |
+
>>> response.write("<p>Here's the text of the web page.</p>")
|
| 719 |
+
>>> response.write("<p>Here's another paragraph.</p>")
|
| 720 |
+
|
| 721 |
+
Passing iterators
|
| 722 |
+
~~~~~~~~~~~~~~~~~
|
| 723 |
+
|
| 724 |
+
Finally, you can pass ``HttpResponse`` an iterator rather than strings.
|
| 725 |
+
``HttpResponse`` will consume the iterator immediately, store its content as a
|
| 726 |
+
string, and discard it. Objects with a ``close()`` method such as files and
|
| 727 |
+
generators are immediately closed.
|
| 728 |
+
|
| 729 |
+
If you need the response to be streamed from the iterator to the client, you
|
| 730 |
+
must use the :class:`StreamingHttpResponse` class instead.
|
| 731 |
+
|
| 732 |
+
.. _setting-header-fields:
|
| 733 |
+
|
| 734 |
+
Setting header fields
|
| 735 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 736 |
+
|
| 737 |
+
To set or remove a header field in your response, use
|
| 738 |
+
:attr:`HttpResponse.headers`:
|
| 739 |
+
|
| 740 |
+
.. code-block:: pycon
|
| 741 |
+
|
| 742 |
+
>>> response = HttpResponse()
|
| 743 |
+
>>> response.headers["Age"] = 120
|
| 744 |
+
>>> del response.headers["Age"]
|
| 745 |
+
|
| 746 |
+
You can also manipulate headers by treating your response like a dictionary:
|
| 747 |
+
|
| 748 |
+
.. code-block:: pycon
|
| 749 |
+
|
| 750 |
+
>>> response = HttpResponse()
|
| 751 |
+
>>> response["Age"] = 120
|
| 752 |
+
>>> del response["Age"]
|
| 753 |
+
|
| 754 |
+
This proxies to ``HttpResponse.headers``, and is the original interface offered
|
| 755 |
+
by ``HttpResponse``.
|
| 756 |
+
|
| 757 |
+
When using this interface, unlike a dictionary, ``del`` doesn't raise
|
| 758 |
+
``KeyError`` if the header field doesn't exist.
|
| 759 |
+
|
| 760 |
+
You can also set headers on instantiation:
|
| 761 |
+
|
| 762 |
+
.. code-block:: pycon
|
| 763 |
+
|
| 764 |
+
>>> response = HttpResponse(headers={"Age": 120})
|
| 765 |
+
|
| 766 |
+
For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended
|
| 767 |
+
to use the :func:`~django.utils.cache.patch_cache_control` and
|
| 768 |
+
:func:`~django.utils.cache.patch_vary_headers` methods from
|
| 769 |
+
:mod:`django.utils.cache`, since these fields can have multiple, comma-separated
|
| 770 |
+
values. The "patch" methods ensure that other values, e.g. added by a
|
| 771 |
+
middleware, are not removed.
|
| 772 |
+
|
| 773 |
+
HTTP header fields cannot contain newlines. An attempt to set a header field
|
| 774 |
+
containing a newline character (CR or LF) will raise ``BadHeaderError``
|
| 775 |
+
|
| 776 |
+
Telling the browser to treat the response as a file attachment
|
| 777 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 778 |
+
|
| 779 |
+
To tell the browser to treat the response as a file attachment, set the
|
| 780 |
+
``Content-Type`` and ``Content-Disposition`` headers. For example, this is how
|
| 781 |
+
you might return a Microsoft Excel spreadsheet:
|
| 782 |
+
|
| 783 |
+
.. code-block:: pycon
|
| 784 |
+
|
| 785 |
+
>>> response = HttpResponse(
|
| 786 |
+
... my_data,
|
| 787 |
+
... headers={
|
| 788 |
+
... "Content-Type": "application/vnd.ms-excel",
|
| 789 |
+
... "Content-Disposition": 'attachment; filename="foo.xls"',
|
| 790 |
+
... },
|
| 791 |
+
... )
|
| 792 |
+
|
| 793 |
+
There's nothing Django-specific about the ``Content-Disposition`` header, but
|
| 794 |
+
it's easy to forget the syntax, so we've included it here.
|
| 795 |
+
|
| 796 |
+
Attributes
|
| 797 |
+
----------
|
| 798 |
+
|
| 799 |
+
.. attribute:: HttpResponse.content
|
| 800 |
+
|
| 801 |
+
A bytestring representing the content, encoded from a string if necessary.
|
| 802 |
+
|
| 803 |
+
.. attribute:: HttpResponse.headers
|
| 804 |
+
|
| 805 |
+
A case insensitive, dict-like object that provides an interface to all
|
| 806 |
+
HTTP headers on the response. See :ref:`setting-header-fields`.
|
| 807 |
+
|
| 808 |
+
.. attribute:: HttpResponse.charset
|
| 809 |
+
|
| 810 |
+
A string denoting the charset in which the response will be encoded. If not
|
| 811 |
+
given at ``HttpResponse`` instantiation time, it will be extracted from
|
| 812 |
+
``content_type`` and if that is unsuccessful, the
|
| 813 |
+
:setting:`DEFAULT_CHARSET` setting will be used.
|
| 814 |
+
|
| 815 |
+
.. attribute:: HttpResponse.status_code
|
| 816 |
+
|
| 817 |
+
The :rfc:`HTTP status code <9110#section-15>` for the response.
|
| 818 |
+
|
| 819 |
+
Unless :attr:`reason_phrase` is explicitly set, modifying the value of
|
| 820 |
+
``status_code`` outside the constructor will also modify the value of
|
| 821 |
+
``reason_phrase``.
|
| 822 |
+
|
| 823 |
+
.. attribute:: HttpResponse.reason_phrase
|
| 824 |
+
|
| 825 |
+
The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
|
| 826 |
+
<9110#section-15.1>` default reason phrases.
|
| 827 |
+
|
| 828 |
+
Unless explicitly set, ``reason_phrase`` is determined by the value of
|
| 829 |
+
:attr:`status_code`.
|
| 830 |
+
|
| 831 |
+
.. attribute:: HttpResponse.streaming
|
| 832 |
+
|
| 833 |
+
This is always ``False``.
|
| 834 |
+
|
| 835 |
+
This attribute exists so middleware can treat streaming responses
|
| 836 |
+
differently from regular responses.
|
| 837 |
+
|
| 838 |
+
.. attribute:: HttpResponse.closed
|
| 839 |
+
|
| 840 |
+
``True`` if the response has been closed.
|
| 841 |
+
|
| 842 |
+
Methods
|
| 843 |
+
-------
|
| 844 |
+
|
| 845 |
+
.. method:: HttpResponse.__init__(content=b'', content_type=None, status=200, reason=None, charset=None, headers=None)
|
| 846 |
+
|
| 847 |
+
Instantiates an ``HttpResponse`` object with the given page content,
|
| 848 |
+
content type, and headers.
|
| 849 |
+
|
| 850 |
+
``content`` is most commonly an iterator, bytestring, :class:`memoryview`,
|
| 851 |
+
or string. Other types will be converted to a bytestring by encoding their
|
| 852 |
+
string representation. Iterators should return strings or bytestrings and
|
| 853 |
+
those will be joined together to form the content of the response.
|
| 854 |
+
|
| 855 |
+
``content_type`` is the MIME type optionally completed by a character set
|
| 856 |
+
encoding and is used to fill the HTTP ``Content-Type`` header. If not
|
| 857 |
+
specified, it is formed by ``'text/html'`` and the
|
| 858 |
+
:setting:`DEFAULT_CHARSET` settings, by default:
|
| 859 |
+
``"text/html; charset=utf-8"``.
|
| 860 |
+
|
| 861 |
+
``status`` is the :rfc:`HTTP status code <9110#section-15>` for the
|
| 862 |
+
response. You can use Python's :py:class:`http.HTTPStatus` for meaningful
|
| 863 |
+
aliases, such as ``HTTPStatus.NO_CONTENT``.
|
| 864 |
+
|
| 865 |
+
``reason`` is the HTTP response phrase. If not provided, a default phrase
|
| 866 |
+
will be used.
|
| 867 |
+
|
| 868 |
+
``charset`` is the charset in which the response will be encoded. If not
|
| 869 |
+
given it will be extracted from ``content_type``, and if that
|
| 870 |
+
is unsuccessful, the :setting:`DEFAULT_CHARSET` setting will be used.
|
| 871 |
+
|
| 872 |
+
``headers`` is a :class:`dict` of HTTP headers for the response.
|
| 873 |
+
|
| 874 |
+
.. method:: HttpResponse.__setitem__(header, value)
|
| 875 |
+
|
| 876 |
+
Sets the given header name to the given value. Both ``header`` and
|
| 877 |
+
``value`` should be strings.
|
| 878 |
+
|
| 879 |
+
.. method:: HttpResponse.__delitem__(header)
|
| 880 |
+
|
| 881 |
+
Deletes the header with the given name. Fails silently if the header
|
| 882 |
+
doesn't exist. Case-insensitive.
|
| 883 |
+
|
| 884 |
+
.. method:: HttpResponse.__getitem__(header)
|
| 885 |
+
|
| 886 |
+
Returns the value for the given header name. Case-insensitive.
|
| 887 |
+
|
| 888 |
+
.. method:: HttpResponse.get(header, alternate=None)
|
| 889 |
+
|
| 890 |
+
Returns the value for the given header, or an ``alternate`` if the header
|
| 891 |
+
doesn't exist.
|
| 892 |
+
|
| 893 |
+
.. method:: HttpResponse.has_header(header)
|
| 894 |
+
|
| 895 |
+
Returns ``True`` or ``False`` based on a case-insensitive check for a
|
| 896 |
+
header with the given name.
|
| 897 |
+
|
| 898 |
+
.. method:: HttpResponse.items()
|
| 899 |
+
|
| 900 |
+
Acts like :meth:`dict.items` for HTTP headers on the response.
|
| 901 |
+
|
| 902 |
+
.. method:: HttpResponse.setdefault(header, value)
|
| 903 |
+
|
| 904 |
+
Sets a header unless it has already been set.
|
| 905 |
+
|
| 906 |
+
.. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
|
| 907 |
+
|
| 908 |
+
Sets a cookie. The parameters are the same as in the
|
| 909 |
+
:class:`~http.cookies.Morsel` cookie object in the Python standard library.
|
| 910 |
+
|
| 911 |
+
* ``max_age`` should be a :class:`~datetime.timedelta` object, an integer
|
| 912 |
+
number of seconds, or ``None`` (default) if the cookie should last only
|
| 913 |
+
as long as the client's browser session. If ``expires`` is not specified,
|
| 914 |
+
it will be calculated.
|
| 915 |
+
* ``expires`` should either be a string in the format
|
| 916 |
+
``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
|
| 917 |
+
in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
|
| 918 |
+
will be calculated.
|
| 919 |
+
* Use ``domain`` if you want to set a cross-domain cookie. For example,
|
| 920 |
+
``domain="example.com"`` will set a cookie that is readable by the
|
| 921 |
+
domains www.example.com, blog.example.com, etc. Otherwise, a cookie will
|
| 922 |
+
only be readable by the domain that set it.
|
| 923 |
+
* Use ``secure=True`` if you want the cookie to be only sent to the server
|
| 924 |
+
when a request is made with the ``https`` scheme.
|
| 925 |
+
* Use ``httponly=True`` if you want to prevent client-side
|
| 926 |
+
JavaScript from having access to the cookie.
|
| 927 |
+
|
| 928 |
+
HttpOnly_ is a flag included in a Set-Cookie HTTP response header. It's
|
| 929 |
+
part of the :rfc:`RFC 6265 <6265#section-4.1.2.6>` standard for cookies
|
| 930 |
+
and can be a useful way to mitigate the risk of a client-side script
|
| 931 |
+
accessing the protected cookie data.
|
| 932 |
+
* Use ``samesite='Strict'`` or ``samesite='Lax'`` to tell the browser not
|
| 933 |
+
to send this cookie when performing a cross-origin request. `SameSite`_
|
| 934 |
+
isn't supported by all browsers, so it's not a replacement for Django's
|
| 935 |
+
CSRF protection, but rather a defense in depth measure.
|
| 936 |
+
|
| 937 |
+
Use ``samesite='None'`` (string) to explicitly state that this cookie is
|
| 938 |
+
sent with all same-site and cross-site requests.
|
| 939 |
+
|
| 940 |
+
.. _HttpOnly: https://owasp.org/www-community/HttpOnly
|
| 941 |
+
.. _SameSite: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
|
| 942 |
+
|
| 943 |
+
.. warning::
|
| 944 |
+
|
| 945 |
+
:rfc:`RFC 6265 <6265#section-6.1>` states that user agents should
|
| 946 |
+
support cookies of at least 4096 bytes. For many browsers this is also
|
| 947 |
+
the maximum size. Django will not raise an exception if there's an
|
| 948 |
+
attempt to store a cookie of more than 4096 bytes, but many browsers
|
| 949 |
+
will not set the cookie correctly.
|
| 950 |
+
|
| 951 |
+
.. method:: HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
|
| 952 |
+
|
| 953 |
+
Like :meth:`~HttpResponse.set_cookie()`, but
|
| 954 |
+
:doc:`cryptographic signing </topics/signing>` the cookie before setting
|
| 955 |
+
it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.
|
| 956 |
+
You can use the optional ``salt`` argument for added key strength, but
|
| 957 |
+
you will need to remember to pass it to the corresponding
|
| 958 |
+
:meth:`HttpRequest.get_signed_cookie` call.
|
| 959 |
+
|
| 960 |
+
.. method:: HttpResponse.delete_cookie(key, path='/', domain=None, samesite=None)
|
| 961 |
+
|
| 962 |
+
Deletes the cookie with the given key. Fails silently if the key doesn't
|
| 963 |
+
exist.
|
| 964 |
+
|
| 965 |
+
Due to the way cookies work, ``path`` and ``domain`` should be the same
|
| 966 |
+
values you used in ``set_cookie()`` -- otherwise the cookie may not be
|
| 967 |
+
deleted.
|
| 968 |
+
|
| 969 |
+
.. method:: HttpResponse.close()
|
| 970 |
+
|
| 971 |
+
This method is called at the end of the request directly by the WSGI
|
| 972 |
+
server.
|
| 973 |
+
|
| 974 |
+
.. method:: HttpResponse.write(content)
|
| 975 |
+
|
| 976 |
+
This method makes an :class:`HttpResponse` instance a file-like object.
|
| 977 |
+
|
| 978 |
+
.. method:: HttpResponse.flush()
|
| 979 |
+
|
| 980 |
+
This method makes an :class:`HttpResponse` instance a file-like object.
|
| 981 |
+
|
| 982 |
+
.. method:: HttpResponse.tell()
|
| 983 |
+
|
| 984 |
+
This method makes an :class:`HttpResponse` instance a file-like object.
|
| 985 |
+
|
| 986 |
+
.. method:: HttpResponse.getvalue()
|
| 987 |
+
|
| 988 |
+
Returns the value of :attr:`HttpResponse.content`. This method makes
|
| 989 |
+
an :class:`HttpResponse` instance a stream-like object.
|
| 990 |
+
|
| 991 |
+
.. method:: HttpResponse.readable()
|
| 992 |
+
|
| 993 |
+
Always ``False``. This method makes an :class:`HttpResponse` instance a
|
| 994 |
+
stream-like object.
|
| 995 |
+
|
| 996 |
+
.. method:: HttpResponse.seekable()
|
| 997 |
+
|
| 998 |
+
Always ``False``. This method makes an :class:`HttpResponse` instance a
|
| 999 |
+
stream-like object.
|
| 1000 |
+
|
| 1001 |
+
.. method:: HttpResponse.writable()
|
| 1002 |
+
|
| 1003 |
+
Always ``True``. This method makes an :class:`HttpResponse` instance a
|
| 1004 |
+
stream-like object.
|
| 1005 |
+
|
| 1006 |
+
.. method:: HttpResponse.writelines(lines)
|
| 1007 |
+
|
| 1008 |
+
Writes a list of lines to the response. Line separators are not added. This
|
| 1009 |
+
method makes an :class:`HttpResponse` instance a stream-like object.
|
| 1010 |
+
|
| 1011 |
+
.. _ref-httpresponse-subclasses:
|
| 1012 |
+
|
| 1013 |
+
``HttpResponse`` subclasses
|
| 1014 |
+
---------------------------
|
| 1015 |
+
|
| 1016 |
+
Django includes a number of ``HttpResponse`` subclasses that handle different
|
| 1017 |
+
types of HTTP responses. Like ``HttpResponse``, these subclasses live in
|
| 1018 |
+
:mod:`django.http`.
|
| 1019 |
+
|
| 1020 |
+
.. class:: HttpResponseRedirect
|
| 1021 |
+
|
| 1022 |
+
The first argument to the constructor is required -- the path to redirect
|
| 1023 |
+
to. This can be a fully qualified URL
|
| 1024 |
+
(e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain
|
| 1025 |
+
(e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that
|
| 1026 |
+
last case, the client browser will reconstruct the full URL itself
|
| 1027 |
+
according to the current path. See :class:`HttpResponse` for other optional
|
| 1028 |
+
constructor arguments. Note that this returns an HTTP status code 302.
|
| 1029 |
+
|
| 1030 |
+
.. attribute:: HttpResponseRedirect.url
|
| 1031 |
+
|
| 1032 |
+
This read-only attribute represents the URL the response will redirect
|
| 1033 |
+
to (equivalent to the ``Location`` response header).
|
| 1034 |
+
|
| 1035 |
+
.. class:: HttpResponsePermanentRedirect
|
| 1036 |
+
|
| 1037 |
+
Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
|
| 1038 |
+
(HTTP status code 301) instead of a "found" redirect (status code 302).
|
| 1039 |
+
|
| 1040 |
+
.. class:: HttpResponseNotModified
|
| 1041 |
+
|
| 1042 |
+
The constructor doesn't take any arguments and no content should be added
|
| 1043 |
+
to this response. Use this to designate that a page hasn't been modified
|
| 1044 |
+
since the user's last request (status code 304).
|
| 1045 |
+
|
| 1046 |
+
.. class:: HttpResponseBadRequest
|
| 1047 |
+
|
| 1048 |
+
Acts just like :class:`HttpResponse` but uses a 400 status code.
|
| 1049 |
+
|
| 1050 |
+
.. class:: HttpResponseNotFound
|
| 1051 |
+
|
| 1052 |
+
Acts just like :class:`HttpResponse` but uses a 404 status code.
|
| 1053 |
+
|
| 1054 |
+
.. class:: HttpResponseForbidden
|
| 1055 |
+
|
| 1056 |
+
Acts just like :class:`HttpResponse` but uses a 403 status code.
|
| 1057 |
+
|
| 1058 |
+
.. class:: HttpResponseNotAllowed
|
| 1059 |
+
|
| 1060 |
+
Like :class:`HttpResponse`, but uses a 405 status code. The first argument
|
| 1061 |
+
to the constructor is required: a list of permitted methods (e.g.
|
| 1062 |
+
``['GET', 'POST']``).
|
| 1063 |
+
|
| 1064 |
+
.. class:: HttpResponseGone
|
| 1065 |
+
|
| 1066 |
+
Acts just like :class:`HttpResponse` but uses a 410 status code.
|
| 1067 |
+
|
| 1068 |
+
.. class:: HttpResponseServerError
|
| 1069 |
+
|
| 1070 |
+
Acts just like :class:`HttpResponse` but uses a 500 status code.
|
| 1071 |
+
|
| 1072 |
+
.. note::
|
| 1073 |
+
|
| 1074 |
+
If a custom subclass of :class:`HttpResponse` implements a ``render``
|
| 1075 |
+
method, Django will treat it as emulating a
|
| 1076 |
+
:class:`~django.template.response.SimpleTemplateResponse`, and the
|
| 1077 |
+
``render`` method must itself return a valid response object.
|
| 1078 |
+
|
| 1079 |
+
Custom response classes
|
| 1080 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 1081 |
+
|
| 1082 |
+
If you find yourself needing a response class that Django doesn't provide, you
|
| 1083 |
+
can create it with the help of :py:class:`http.HTTPStatus`. For example:
|
| 1084 |
+
|
| 1085 |
+
.. code-block:: pycon
|
| 1086 |
+
|
| 1087 |
+
from http import HTTPStatus
|
| 1088 |
+
from django.http import HttpResponse
|
| 1089 |
+
|
| 1090 |
+
class HttpResponseNoContent(HttpResponse):
|
| 1091 |
+
status_code = HTTPStatus.NO_CONTENT
|
| 1092 |
+
|
| 1093 |
+
``JsonResponse`` objects
|
| 1094 |
+
========================
|
| 1095 |
+
|
| 1096 |
+
.. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
|
| 1097 |
+
|
| 1098 |
+
An :class:`HttpResponse` subclass that helps to create a JSON-encoded
|
| 1099 |
+
response. It inherits most behavior from its superclass with a couple
|
| 1100 |
+
differences:
|
| 1101 |
+
|
| 1102 |
+
Its default ``Content-Type`` header is set to :mimetype:`application/json`.
|
| 1103 |
+
|
| 1104 |
+
The first parameter, ``data``, should be a ``dict`` instance. If the
|
| 1105 |
+
``safe`` parameter is set to ``False`` (see below) it can be any
|
| 1106 |
+
JSON-serializable object.
|
| 1107 |
+
|
| 1108 |
+
The ``encoder``, which defaults to
|
| 1109 |
+
:class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
|
| 1110 |
+
serialize the data. See :ref:`JSON serialization
|
| 1111 |
+
<serialization-formats-json>` for more details about this serializer.
|
| 1112 |
+
|
| 1113 |
+
The ``safe`` boolean parameter defaults to ``True``. If it's set to
|
| 1114 |
+
``False``, any object can be passed for serialization (otherwise only
|
| 1115 |
+
``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``
|
| 1116 |
+
object is passed as the first argument, a :exc:`TypeError` will be raised.
|
| 1117 |
+
|
| 1118 |
+
The ``json_dumps_params`` parameter is a dictionary of keyword arguments
|
| 1119 |
+
to pass to the ``json.dumps()`` call used to generate the response.
|
| 1120 |
+
|
| 1121 |
+
Usage
|
| 1122 |
+
-----
|
| 1123 |
+
|
| 1124 |
+
Typical usage could look like:
|
| 1125 |
+
|
| 1126 |
+
.. code-block:: pycon
|
| 1127 |
+
|
| 1128 |
+
>>> from django.http import JsonResponse
|
| 1129 |
+
>>> response = JsonResponse({"foo": "bar"})
|
| 1130 |
+
>>> response.content
|
| 1131 |
+
b'{"foo": "bar"}'
|
| 1132 |
+
|
| 1133 |
+
Serializing non-dictionary objects
|
| 1134 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1135 |
+
|
| 1136 |
+
In order to serialize objects other than ``dict`` you must set the ``safe``
|
| 1137 |
+
parameter to ``False``:
|
| 1138 |
+
|
| 1139 |
+
.. code-block:: pycon
|
| 1140 |
+
|
| 1141 |
+
>>> response = JsonResponse([1, 2, 3], safe=False)
|
| 1142 |
+
|
| 1143 |
+
Without passing ``safe=False``, a :exc:`TypeError` will be raised.
|
| 1144 |
+
|
| 1145 |
+
Note that an API based on ``dict`` objects is more extensible, flexible, and
|
| 1146 |
+
makes it easier to maintain forwards compatibility. Therefore, you should avoid
|
| 1147 |
+
using non-dict objects in JSON-encoded response.
|
| 1148 |
+
|
| 1149 |
+
.. warning::
|
| 1150 |
+
|
| 1151 |
+
Before the `5th edition of ECMAScript
|
| 1152 |
+
<https://262.ecma-international.org/5.1/#sec-11.1.4>`_ it was possible to
|
| 1153 |
+
poison the JavaScript ``Array`` constructor. For this reason, Django does
|
| 1154 |
+
not allow passing non-dict objects to the
|
| 1155 |
+
:class:`~django.http.JsonResponse` constructor by default. However, most
|
| 1156 |
+
modern browsers implement ECMAScript 5 which removes this attack vector.
|
| 1157 |
+
Therefore it is possible to disable this security precaution.
|
| 1158 |
+
|
| 1159 |
+
Changing the default JSON encoder
|
| 1160 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 1161 |
+
|
| 1162 |
+
If you need to use a different JSON encoder class you can pass the ``encoder``
|
| 1163 |
+
parameter to the constructor method:
|
| 1164 |
+
|
| 1165 |
+
.. code-block:: pycon
|
| 1166 |
+
|
| 1167 |
+
>>> response = JsonResponse(data, encoder=MyJSONEncoder)
|
| 1168 |
+
|
| 1169 |
+
.. _httpresponse-streaming:
|
| 1170 |
+
|
| 1171 |
+
``StreamingHttpResponse`` objects
|
| 1172 |
+
=================================
|
| 1173 |
+
|
| 1174 |
+
.. class:: StreamingHttpResponse
|
| 1175 |
+
|
| 1176 |
+
The :class:`StreamingHttpResponse` class is used to stream a response from
|
| 1177 |
+
Django to the browser.
|
| 1178 |
+
|
| 1179 |
+
.. admonition:: Advanced usage
|
| 1180 |
+
|
| 1181 |
+
:class:`StreamingHttpResponse` is somewhat advanced, in that it is
|
| 1182 |
+
important to know whether you'll be serving your application synchronously
|
| 1183 |
+
under WSGI or asynchronously under ASGI, and adjust your usage
|
| 1184 |
+
appropriately.
|
| 1185 |
+
|
| 1186 |
+
Please read these notes with care.
|
| 1187 |
+
|
| 1188 |
+
An example usage of :class:`StreamingHttpResponse` under WSGI is streaming
|
| 1189 |
+
content when generating the response would take too long or uses too much
|
| 1190 |
+
memory. For instance, it's useful for :ref:`generating large CSV files
|
| 1191 |
+
<streaming-csv-files>`.
|
| 1192 |
+
|
| 1193 |
+
There are performance considerations when doing this, though. Django, under
|
| 1194 |
+
WSGI, is designed for short-lived requests. Streaming responses will tie a
|
| 1195 |
+
worker process for the entire duration of the response. This may result in poor
|
| 1196 |
+
performance.
|
| 1197 |
+
|
| 1198 |
+
Generally speaking, you would perform expensive tasks outside of the
|
| 1199 |
+
request-response cycle, rather than resorting to a streamed response.
|
| 1200 |
+
|
| 1201 |
+
When serving under ASGI, however, a :class:`StreamingHttpResponse` need not
|
| 1202 |
+
stop other requests from being served whilst waiting for I/O. This opens up
|
| 1203 |
+
the possibility of long-lived requests for streaming content and implementing
|
| 1204 |
+
patterns such as long-polling, and server-sent events.
|
| 1205 |
+
|
| 1206 |
+
Even under ASGI note, :class:`StreamingHttpResponse` should only be used in
|
| 1207 |
+
situations where it is absolutely required that the whole content isn't
|
| 1208 |
+
iterated before transferring the data to the client. Because the content can't
|
| 1209 |
+
be accessed, many middleware can't function normally. For example the ``ETag``
|
| 1210 |
+
and ``Content-Length`` headers can't be generated for streaming responses.
|
| 1211 |
+
|
| 1212 |
+
The :class:`StreamingHttpResponse` is not a subclass of :class:`HttpResponse`,
|
| 1213 |
+
because it features a slightly different API. However, it is almost identical,
|
| 1214 |
+
with the following notable differences:
|
| 1215 |
+
|
| 1216 |
+
* It should be given an iterator that yields bytestrings, :class:`memoryview`,
|
| 1217 |
+
or strings as content. When serving under WSGI, this should be a sync
|
| 1218 |
+
iterator. When serving under ASGI, then it should be an async iterator.
|
| 1219 |
+
|
| 1220 |
+
* You cannot access its content, except by iterating the response object
|
| 1221 |
+
itself. This should only occur when the response is returned to the client:
|
| 1222 |
+
you should not iterate the response yourself.
|
| 1223 |
+
|
| 1224 |
+
Under WSGI the response will be iterated synchronously. Under ASGI the
|
| 1225 |
+
response will be iterated asynchronously. (This is why the iterator type must
|
| 1226 |
+
match the protocol you're using.)
|
| 1227 |
+
|
| 1228 |
+
To avoid a crash, an incorrect iterator type will be mapped to the correct
|
| 1229 |
+
type during iteration, and a warning will be raised, but in order to do this
|
| 1230 |
+
the iterator must be fully-consumed, which defeats the purpose of using a
|
| 1231 |
+
:class:`StreamingHttpResponse` at all.
|
| 1232 |
+
|
| 1233 |
+
* It has no ``content`` attribute. Instead, it has a
|
| 1234 |
+
:attr:`~StreamingHttpResponse.streaming_content` attribute. This can be used
|
| 1235 |
+
in middleware to wrap the response iterable, but should not be consumed.
|
| 1236 |
+
|
| 1237 |
+
* You cannot use the file-like object ``tell()`` or ``write()`` methods.
|
| 1238 |
+
Doing so will raise an exception.
|
| 1239 |
+
|
| 1240 |
+
The :class:`HttpResponseBase` base class is common between
|
| 1241 |
+
:class:`HttpResponse` and :class:`StreamingHttpResponse`.
|
| 1242 |
+
|
| 1243 |
+
.. versionchanged:: 4.2
|
| 1244 |
+
|
| 1245 |
+
Support for asynchronous iteration was added.
|
| 1246 |
+
|
| 1247 |
+
Attributes
|
| 1248 |
+
----------
|
| 1249 |
+
|
| 1250 |
+
.. attribute:: StreamingHttpResponse.streaming_content
|
| 1251 |
+
|
| 1252 |
+
An iterator of the response content, bytestring encoded according to
|
| 1253 |
+
:attr:`HttpResponse.charset`.
|
| 1254 |
+
|
| 1255 |
+
.. attribute:: StreamingHttpResponse.status_code
|
| 1256 |
+
|
| 1257 |
+
The :rfc:`HTTP status code <9110#section-15>` for the response.
|
| 1258 |
+
|
| 1259 |
+
Unless :attr:`reason_phrase` is explicitly set, modifying the value of
|
| 1260 |
+
``status_code`` outside the constructor will also modify the value of
|
| 1261 |
+
``reason_phrase``.
|
| 1262 |
+
|
| 1263 |
+
.. attribute:: StreamingHttpResponse.reason_phrase
|
| 1264 |
+
|
| 1265 |
+
The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
|
| 1266 |
+
<9110#section-15.1>` default reason phrases.
|
| 1267 |
+
|
| 1268 |
+
Unless explicitly set, ``reason_phrase`` is determined by the value of
|
| 1269 |
+
:attr:`status_code`.
|
| 1270 |
+
|
| 1271 |
+
.. attribute:: StreamingHttpResponse.streaming
|
| 1272 |
+
|
| 1273 |
+
This is always ``True``.
|
| 1274 |
+
|
| 1275 |
+
.. attribute:: StreamingHttpResponse.is_async
|
| 1276 |
+
|
| 1277 |
+
.. versionadded:: 4.2
|
| 1278 |
+
|
| 1279 |
+
Boolean indicating whether :attr:`StreamingHttpResponse.streaming_content`
|
| 1280 |
+
is an asynchronous iterator or not.
|
| 1281 |
+
|
| 1282 |
+
This is useful for middleware needing to wrap
|
| 1283 |
+
:attr:`StreamingHttpResponse.streaming_content`.
|
| 1284 |
+
|
| 1285 |
+
``FileResponse`` objects
|
| 1286 |
+
========================
|
| 1287 |
+
|
| 1288 |
+
.. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)
|
| 1289 |
+
|
| 1290 |
+
:class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`
|
| 1291 |
+
optimized for binary files. It uses :pep:`wsgi.file_wrapper
|
| 1292 |
+
<3333#optional-platform-specific-file-handling>` if provided by the wsgi
|
| 1293 |
+
server, otherwise it streams the file out in small chunks.
|
| 1294 |
+
|
| 1295 |
+
If ``as_attachment=True``, the ``Content-Disposition`` header is set to
|
| 1296 |
+
``attachment``, which asks the browser to offer the file to the user as a
|
| 1297 |
+
download. Otherwise, a ``Content-Disposition`` header with a value of
|
| 1298 |
+
``inline`` (the browser default) will be set only if a filename is
|
| 1299 |
+
available.
|
| 1300 |
+
|
| 1301 |
+
If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't
|
| 1302 |
+
appropriate, provide a custom file name using the ``filename`` parameter.
|
| 1303 |
+
Note that if you pass a file-like object like ``io.BytesIO``, it's your
|
| 1304 |
+
task to ``seek()`` it before passing it to ``FileResponse``.
|
| 1305 |
+
|
| 1306 |
+
The ``Content-Length`` header is automatically set when it can be guessed
|
| 1307 |
+
from the content of ``open_file``.
|
| 1308 |
+
|
| 1309 |
+
The ``Content-Type`` header is automatically set when it can be guessed
|
| 1310 |
+
from the ``filename``, or the name of ``open_file``.
|
| 1311 |
+
|
| 1312 |
+
``FileResponse`` accepts any file-like object with binary content, for example
|
| 1313 |
+
a file open in binary mode like so:
|
| 1314 |
+
|
| 1315 |
+
.. code-block:: pycon
|
| 1316 |
+
|
| 1317 |
+
>>> from django.http import FileResponse
|
| 1318 |
+
>>> response = FileResponse(open("myfile.png", "rb"))
|
| 1319 |
+
|
| 1320 |
+
The file will be closed automatically, so don't open it with a context manager.
|
| 1321 |
+
|
| 1322 |
+
.. admonition:: Use under ASGI
|
| 1323 |
+
|
| 1324 |
+
Python's file API is synchronous. This means that the file must be fully
|
| 1325 |
+
consumed in order to be served under ASGI.
|
| 1326 |
+
|
| 1327 |
+
In order to stream a file asynchronously you need to use a third-party
|
| 1328 |
+
package that provides an asynchronous file API, such as `aiofiles
|
| 1329 |
+
<https://github.com/Tinche/aiofiles>`_.
|
| 1330 |
+
|
| 1331 |
+
Methods
|
| 1332 |
+
-------
|
| 1333 |
+
|
| 1334 |
+
.. method:: FileResponse.set_headers(open_file)
|
| 1335 |
+
|
| 1336 |
+
This method is automatically called during the response initialization and
|
| 1337 |
+
set various headers (``Content-Length``, ``Content-Type``, and
|
| 1338 |
+
``Content-Disposition``) depending on ``open_file``.
|
| 1339 |
+
|
| 1340 |
+
``HttpResponseBase`` class
|
| 1341 |
+
==========================
|
| 1342 |
+
|
| 1343 |
+
.. class:: HttpResponseBase
|
| 1344 |
+
|
| 1345 |
+
The :class:`HttpResponseBase` class is common to all Django responses.
|
| 1346 |
+
It should not be used to create responses directly, but it can be
|
| 1347 |
+
useful for type-checking.
|
testbed/django__django/docs/ref/schema-editor.txt
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================
|
| 2 |
+
``SchemaEditor``
|
| 3 |
+
================
|
| 4 |
+
|
| 5 |
+
.. module:: django.db.backends.base.schema
|
| 6 |
+
|
| 7 |
+
.. class:: BaseDatabaseSchemaEditor
|
| 8 |
+
|
| 9 |
+
Django's migration system is split into two parts; the logic for calculating
|
| 10 |
+
and storing what operations should be run (``django.db.migrations``), and the
|
| 11 |
+
database abstraction layer that turns things like "create a model" or
|
| 12 |
+
"delete a field" into SQL - which is the job of the ``SchemaEditor``.
|
| 13 |
+
|
| 14 |
+
It's unlikely that you will want to interact directly with ``SchemaEditor`` as
|
| 15 |
+
a normal developer using Django, but if you want to write your own migration
|
| 16 |
+
system, or have more advanced needs, it's a lot nicer than writing SQL.
|
| 17 |
+
|
| 18 |
+
Each database backend in Django supplies its own version of ``SchemaEditor``,
|
| 19 |
+
and it's always accessible via the ``connection.schema_editor()`` context
|
| 20 |
+
manager::
|
| 21 |
+
|
| 22 |
+
with connection.schema_editor() as schema_editor:
|
| 23 |
+
schema_editor.delete_model(MyModel)
|
| 24 |
+
|
| 25 |
+
It must be used via the context manager as this allows it to manage things
|
| 26 |
+
like transactions and deferred SQL (like creating ``ForeignKey`` constraints).
|
| 27 |
+
|
| 28 |
+
It exposes all possible operations as methods, that should be called in
|
| 29 |
+
the order you wish changes to be applied. Some possible operations or types
|
| 30 |
+
of change are not possible on all databases - for example, MyISAM does not
|
| 31 |
+
support foreign key constraints.
|
| 32 |
+
|
| 33 |
+
If you are writing or maintaining a third-party database backend for Django,
|
| 34 |
+
you will need to provide a ``SchemaEditor`` implementation in order to work with
|
| 35 |
+
Django's migration functionality - however, as long as your database is
|
| 36 |
+
relatively standard in its use of SQL and relational design, you should be able
|
| 37 |
+
to subclass one of the built-in Django ``SchemaEditor`` classes and tweak the
|
| 38 |
+
syntax a little.
|
| 39 |
+
|
| 40 |
+
Methods
|
| 41 |
+
=======
|
| 42 |
+
|
| 43 |
+
``execute()``
|
| 44 |
+
-------------
|
| 45 |
+
|
| 46 |
+
.. method:: BaseDatabaseSchemaEditor.execute(sql, params=())
|
| 47 |
+
|
| 48 |
+
Executes the SQL statement passed in, with parameters if supplied. This
|
| 49 |
+
is a wrapper around the normal database cursors that allows capture of the SQL
|
| 50 |
+
to a ``.sql`` file if the user wishes.
|
| 51 |
+
|
| 52 |
+
``create_model()``
|
| 53 |
+
------------------
|
| 54 |
+
|
| 55 |
+
.. method:: BaseDatabaseSchemaEditor.create_model(model)
|
| 56 |
+
|
| 57 |
+
Creates a new table in the database for the provided model, along with any
|
| 58 |
+
unique constraints or indexes it requires.
|
| 59 |
+
|
| 60 |
+
``delete_model()``
|
| 61 |
+
------------------
|
| 62 |
+
|
| 63 |
+
.. method:: BaseDatabaseSchemaEditor.delete_model(model)
|
| 64 |
+
|
| 65 |
+
Drops the model's table in the database along with any unique constraints
|
| 66 |
+
or indexes it has.
|
| 67 |
+
|
| 68 |
+
``add_index()``
|
| 69 |
+
---------------
|
| 70 |
+
|
| 71 |
+
.. method:: BaseDatabaseSchemaEditor.add_index(model, index)
|
| 72 |
+
|
| 73 |
+
Adds ``index`` to ``model``’s table.
|
| 74 |
+
|
| 75 |
+
``remove_index()``
|
| 76 |
+
------------------
|
| 77 |
+
|
| 78 |
+
.. method:: BaseDatabaseSchemaEditor.remove_index(model, index)
|
| 79 |
+
|
| 80 |
+
Removes ``index`` from ``model``’s table.
|
| 81 |
+
|
| 82 |
+
``rename_index()``
|
| 83 |
+
------------------
|
| 84 |
+
|
| 85 |
+
.. method:: BaseDatabaseSchemaEditor.rename_index(model, old_index, new_index)
|
| 86 |
+
|
| 87 |
+
Renames ``old_index`` from ``model``’s table to ``new_index``.
|
| 88 |
+
|
| 89 |
+
``add_constraint()``
|
| 90 |
+
--------------------
|
| 91 |
+
|
| 92 |
+
.. method:: BaseDatabaseSchemaEditor.add_constraint(model, constraint)
|
| 93 |
+
|
| 94 |
+
Adds ``constraint`` to ``model``'s table.
|
| 95 |
+
|
| 96 |
+
``remove_constraint()``
|
| 97 |
+
-----------------------
|
| 98 |
+
|
| 99 |
+
.. method:: BaseDatabaseSchemaEditor.remove_constraint(model, constraint)
|
| 100 |
+
|
| 101 |
+
Removes ``constraint`` from ``model``'s table.
|
| 102 |
+
|
| 103 |
+
``alter_unique_together()``
|
| 104 |
+
---------------------------
|
| 105 |
+
|
| 106 |
+
.. method:: BaseDatabaseSchemaEditor.alter_unique_together(model, old_unique_together, new_unique_together)
|
| 107 |
+
|
| 108 |
+
Changes a model's :attr:`~django.db.models.Options.unique_together` value; this
|
| 109 |
+
will add or remove unique constraints from the model's table until they match
|
| 110 |
+
the new value.
|
| 111 |
+
|
| 112 |
+
``alter_index_together()``
|
| 113 |
+
--------------------------
|
| 114 |
+
|
| 115 |
+
.. method:: BaseDatabaseSchemaEditor.alter_index_together(model, old_index_together, new_index_together)
|
| 116 |
+
|
| 117 |
+
Changes a model's :attr:`~django.db.models.Options.index_together` value; this
|
| 118 |
+
will add or remove indexes from the model's table until they match the new
|
| 119 |
+
value.
|
| 120 |
+
|
| 121 |
+
``alter_db_table()``
|
| 122 |
+
--------------------
|
| 123 |
+
|
| 124 |
+
.. method:: BaseDatabaseSchemaEditor.alter_db_table(model, old_db_table, new_db_table)
|
| 125 |
+
|
| 126 |
+
Renames the model's table from ``old_db_table`` to ``new_db_table``.
|
| 127 |
+
|
| 128 |
+
``alter_db_table_comment()``
|
| 129 |
+
----------------------------
|
| 130 |
+
|
| 131 |
+
.. versionadded:: 4.2
|
| 132 |
+
|
| 133 |
+
.. method:: BaseDatabaseSchemaEditor.alter_db_table_comment(model, old_db_table_comment, new_db_table_comment)
|
| 134 |
+
|
| 135 |
+
Change the ``model``’s table comment to ``new_db_table_comment``.
|
| 136 |
+
|
| 137 |
+
``alter_db_tablespace()``
|
| 138 |
+
-------------------------
|
| 139 |
+
|
| 140 |
+
.. method:: BaseDatabaseSchemaEditor.alter_db_tablespace(model, old_db_tablespace, new_db_tablespace)
|
| 141 |
+
|
| 142 |
+
Moves the model's table from one tablespace to another.
|
| 143 |
+
|
| 144 |
+
``add_field()``
|
| 145 |
+
---------------
|
| 146 |
+
|
| 147 |
+
.. method:: BaseDatabaseSchemaEditor.add_field(model, field)
|
| 148 |
+
|
| 149 |
+
Adds a column (or sometimes multiple) to the model's table to represent the
|
| 150 |
+
field. This will also add indexes or a unique constraint
|
| 151 |
+
if the field has ``db_index=True`` or ``unique=True``.
|
| 152 |
+
|
| 153 |
+
If the field is a ``ManyToManyField`` without a value for ``through``, instead
|
| 154 |
+
of creating a column, it will make a table to represent the relationship. If
|
| 155 |
+
``through`` is provided, it is a no-op.
|
| 156 |
+
|
| 157 |
+
If the field is a ``ForeignKey``, this will also add the foreign key
|
| 158 |
+
constraint to the column.
|
| 159 |
+
|
| 160 |
+
``remove_field()``
|
| 161 |
+
------------------
|
| 162 |
+
|
| 163 |
+
.. method:: BaseDatabaseSchemaEditor.remove_field(model, field)
|
| 164 |
+
|
| 165 |
+
Removes the column(s) representing the field from the model's table, along
|
| 166 |
+
with any unique constraints, foreign key constraints, or indexes caused by
|
| 167 |
+
that field.
|
| 168 |
+
|
| 169 |
+
If the field is a ManyToManyField without a value for ``through``, it will
|
| 170 |
+
remove the table created to track the relationship. If
|
| 171 |
+
``through`` is provided, it is a no-op.
|
| 172 |
+
|
| 173 |
+
``alter_field()``
|
| 174 |
+
-----------------
|
| 175 |
+
|
| 176 |
+
.. method:: BaseDatabaseSchemaEditor.alter_field(model, old_field, new_field, strict=False)
|
| 177 |
+
|
| 178 |
+
This transforms the field on the model from the old field to the new one. This
|
| 179 |
+
includes changing the name of the column (the
|
| 180 |
+
:attr:`~django.db.models.Field.db_column` attribute), changing the type of the
|
| 181 |
+
field (if the field class changes), changing the ``NULL`` status of the field,
|
| 182 |
+
adding or removing field-only unique constraints and indexes, changing primary
|
| 183 |
+
key, and changing the destination of ``ForeignKey`` constraints.
|
| 184 |
+
|
| 185 |
+
The most common transformation this cannot do is transforming a
|
| 186 |
+
``ManyToManyField`` into a normal Field or vice-versa; Django cannot do this
|
| 187 |
+
without losing data, and so it will refuse to do it. Instead,
|
| 188 |
+
:meth:`.remove_field` and :meth:`.add_field` should be called separately.
|
| 189 |
+
|
| 190 |
+
If the database has the ``supports_combined_alters``, Django will try and
|
| 191 |
+
do as many of these in a single database call as possible; otherwise, it will
|
| 192 |
+
issue a separate ALTER statement for each change, but will not issue ALTERs
|
| 193 |
+
where no change is required.
|
| 194 |
+
|
| 195 |
+
Attributes
|
| 196 |
+
==========
|
| 197 |
+
|
| 198 |
+
All attributes should be considered read-only unless stated otherwise.
|
| 199 |
+
|
| 200 |
+
``connection``
|
| 201 |
+
--------------
|
| 202 |
+
|
| 203 |
+
.. attribute:: SchemaEditor.connection
|
| 204 |
+
|
| 205 |
+
A connection object to the database. A useful attribute of the connection is
|
| 206 |
+
``alias`` which can be used to determine the name of the database being
|
| 207 |
+
accessed.
|
| 208 |
+
|
| 209 |
+
This is useful when doing data migrations for :ref:`migrations with multiple
|
| 210 |
+
databases <data-migrations-and-multiple-databases>`.
|
testbed/django__django/docs/ref/settings.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
testbed/django__django/docs/ref/signals.txt
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=======
|
| 2 |
+
Signals
|
| 3 |
+
=======
|
| 4 |
+
|
| 5 |
+
A list of all the signals that Django sends. All built-in signals are sent
|
| 6 |
+
using the :meth:`~django.dispatch.Signal.send` method.
|
| 7 |
+
|
| 8 |
+
.. seealso::
|
| 9 |
+
|
| 10 |
+
See the documentation on the :doc:`signal dispatcher </topics/signals>` for
|
| 11 |
+
information regarding how to register for and receive signals.
|
| 12 |
+
|
| 13 |
+
The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when
|
| 14 |
+
a user is logged in / out <topics-auth-signals>`.
|
| 15 |
+
|
| 16 |
+
Model signals
|
| 17 |
+
=============
|
| 18 |
+
|
| 19 |
+
.. module:: django.db.models.signals
|
| 20 |
+
:synopsis: Signals sent by the model system.
|
| 21 |
+
|
| 22 |
+
The :mod:`django.db.models.signals` module defines a set of signals sent by the
|
| 23 |
+
model system.
|
| 24 |
+
|
| 25 |
+
.. warning::
|
| 26 |
+
|
| 27 |
+
Signals can make your code harder to maintain. Consider implementing a
|
| 28 |
+
helper method on a :ref:`custom manager <custom-managers>`, to
|
| 29 |
+
both update your models and perform additional logic, or else
|
| 30 |
+
:ref:`overriding model methods <overriding-model-methods>` before using
|
| 31 |
+
model signals.
|
| 32 |
+
|
| 33 |
+
.. warning::
|
| 34 |
+
|
| 35 |
+
Many of these signals are sent by various model methods like
|
| 36 |
+
``__init__()`` or :meth:`~django.db.models.Model.save` that you can
|
| 37 |
+
override in your own code.
|
| 38 |
+
|
| 39 |
+
If you override these methods on your model, you must call the parent class'
|
| 40 |
+
methods for these signals to be sent.
|
| 41 |
+
|
| 42 |
+
Note also that Django stores signal handlers as weak references by default,
|
| 43 |
+
so if your handler is a local function, it may be garbage collected. To
|
| 44 |
+
prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`.
|
| 45 |
+
|
| 46 |
+
.. note::
|
| 47 |
+
|
| 48 |
+
Model signals ``sender`` model can be lazily referenced when connecting a
|
| 49 |
+
receiver by specifying its full application label. For example, an
|
| 50 |
+
``Question`` model defined in the ``polls`` application could be referenced
|
| 51 |
+
as ``'polls.Question'``. This sort of reference can be quite handy when
|
| 52 |
+
dealing with circular import dependencies and swappable models.
|
| 53 |
+
|
| 54 |
+
``pre_init``
|
| 55 |
+
------------
|
| 56 |
+
|
| 57 |
+
.. attribute:: django.db.models.signals.pre_init
|
| 58 |
+
:module:
|
| 59 |
+
|
| 60 |
+
.. ^^^^^^^ this :module: hack keeps Sphinx from prepending the module.
|
| 61 |
+
|
| 62 |
+
Whenever you instantiate a Django model, this signal is sent at the beginning
|
| 63 |
+
of the model's ``__init__()`` method.
|
| 64 |
+
|
| 65 |
+
Arguments sent with this signal:
|
| 66 |
+
|
| 67 |
+
``sender``
|
| 68 |
+
The model class that just had an instance created.
|
| 69 |
+
|
| 70 |
+
``args``
|
| 71 |
+
A list of positional arguments passed to ``__init__()``.
|
| 72 |
+
|
| 73 |
+
``kwargs``
|
| 74 |
+
A dictionary of keyword arguments passed to ``__init__()``.
|
| 75 |
+
|
| 76 |
+
For example, the :doc:`tutorial </intro/tutorial02>` has this line::
|
| 77 |
+
|
| 78 |
+
q = Question(question_text="What's new?", pub_date=timezone.now())
|
| 79 |
+
|
| 80 |
+
The arguments sent to a :data:`pre_init` handler would be:
|
| 81 |
+
|
| 82 |
+
========== ===============================================================
|
| 83 |
+
Argument Value
|
| 84 |
+
========== ===============================================================
|
| 85 |
+
``sender`` ``Question`` (the class itself)
|
| 86 |
+
|
| 87 |
+
``args`` ``[]`` (an empty list because there were no positional
|
| 88 |
+
arguments passed to ``__init__()``)
|
| 89 |
+
|
| 90 |
+
``kwargs`` ``{'question_text': "What's new?",``
|
| 91 |
+
``'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc)}``
|
| 92 |
+
========== ===============================================================
|
| 93 |
+
|
| 94 |
+
``post_init``
|
| 95 |
+
-------------
|
| 96 |
+
|
| 97 |
+
.. data:: django.db.models.signals.post_init
|
| 98 |
+
:module:
|
| 99 |
+
|
| 100 |
+
Like pre_init, but this one is sent when the ``__init__()`` method finishes.
|
| 101 |
+
|
| 102 |
+
Arguments sent with this signal:
|
| 103 |
+
|
| 104 |
+
``sender``
|
| 105 |
+
As above: the model class that just had an instance created.
|
| 106 |
+
|
| 107 |
+
``instance``
|
| 108 |
+
The actual instance of the model that's just been created.
|
| 109 |
+
|
| 110 |
+
.. note::
|
| 111 |
+
|
| 112 |
+
:attr:`instance._state <django.db.models.Model._state>` isn't set
|
| 113 |
+
before sending the ``post_init`` signal, so ``_state`` attributes
|
| 114 |
+
always have their default values. For example, ``_state.db`` is
|
| 115 |
+
``None``.
|
| 116 |
+
|
| 117 |
+
.. warning::
|
| 118 |
+
|
| 119 |
+
For performance reasons, you shouldn't perform queries in receivers of
|
| 120 |
+
``pre_init`` or ``post_init`` signals because they would be executed for
|
| 121 |
+
each instance returned during queryset iteration.
|
| 122 |
+
|
| 123 |
+
``pre_save``
|
| 124 |
+
------------
|
| 125 |
+
|
| 126 |
+
.. data:: django.db.models.signals.pre_save
|
| 127 |
+
:module:
|
| 128 |
+
|
| 129 |
+
This is sent at the beginning of a model's :meth:`~django.db.models.Model.save`
|
| 130 |
+
method.
|
| 131 |
+
|
| 132 |
+
Arguments sent with this signal:
|
| 133 |
+
|
| 134 |
+
``sender``
|
| 135 |
+
The model class.
|
| 136 |
+
|
| 137 |
+
``instance``
|
| 138 |
+
The actual instance being saved.
|
| 139 |
+
|
| 140 |
+
``raw``
|
| 141 |
+
A boolean; ``True`` if the model is saved exactly as presented
|
| 142 |
+
(i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
|
| 143 |
+
query/modify other records in the database as the database might not be in
|
| 144 |
+
a consistent state yet.
|
| 145 |
+
|
| 146 |
+
``using``
|
| 147 |
+
The database alias being used.
|
| 148 |
+
|
| 149 |
+
``update_fields``
|
| 150 |
+
The set of fields to update as passed to :meth:`.Model.save`, or ``None``
|
| 151 |
+
if ``update_fields`` wasn't passed to ``save()``.
|
| 152 |
+
|
| 153 |
+
``post_save``
|
| 154 |
+
-------------
|
| 155 |
+
|
| 156 |
+
.. data:: django.db.models.signals.post_save
|
| 157 |
+
:module:
|
| 158 |
+
|
| 159 |
+
Like :data:`pre_save`, but sent at the end of the
|
| 160 |
+
:meth:`~django.db.models.Model.save` method.
|
| 161 |
+
|
| 162 |
+
Arguments sent with this signal:
|
| 163 |
+
|
| 164 |
+
``sender``
|
| 165 |
+
The model class.
|
| 166 |
+
|
| 167 |
+
``instance``
|
| 168 |
+
The actual instance being saved.
|
| 169 |
+
|
| 170 |
+
``created``
|
| 171 |
+
A boolean; ``True`` if a new record was created.
|
| 172 |
+
|
| 173 |
+
``raw``
|
| 174 |
+
A boolean; ``True`` if the model is saved exactly as presented
|
| 175 |
+
(i.e. when loading a :ref:`fixture <fixtures-explanation>`). One should not
|
| 176 |
+
query/modify other records in the database as the database might not be in
|
| 177 |
+
a consistent state yet.
|
| 178 |
+
|
| 179 |
+
``using``
|
| 180 |
+
The database alias being used.
|
| 181 |
+
|
| 182 |
+
``update_fields``
|
| 183 |
+
The set of fields to update as passed to :meth:`.Model.save`, or ``None``
|
| 184 |
+
if ``update_fields`` wasn't passed to ``save()``.
|
| 185 |
+
|
| 186 |
+
``pre_delete``
|
| 187 |
+
--------------
|
| 188 |
+
|
| 189 |
+
.. data:: django.db.models.signals.pre_delete
|
| 190 |
+
:module:
|
| 191 |
+
|
| 192 |
+
Sent at the beginning of a model's :meth:`~django.db.models.Model.delete`
|
| 193 |
+
method and a queryset's :meth:`~django.db.models.query.QuerySet.delete` method.
|
| 194 |
+
|
| 195 |
+
Arguments sent with this signal:
|
| 196 |
+
|
| 197 |
+
``sender``
|
| 198 |
+
The model class.
|
| 199 |
+
|
| 200 |
+
``instance``
|
| 201 |
+
The actual instance being deleted.
|
| 202 |
+
|
| 203 |
+
``using``
|
| 204 |
+
The database alias being used.
|
| 205 |
+
|
| 206 |
+
``origin``
|
| 207 |
+
|
| 208 |
+
The origin of the deletion being the instance of a ``Model`` or
|
| 209 |
+
``QuerySet`` class.
|
| 210 |
+
|
| 211 |
+
``post_delete``
|
| 212 |
+
---------------
|
| 213 |
+
|
| 214 |
+
.. data:: django.db.models.signals.post_delete
|
| 215 |
+
:module:
|
| 216 |
+
|
| 217 |
+
Like :data:`pre_delete`, but sent at the end of a model's
|
| 218 |
+
:meth:`~django.db.models.Model.delete` method and a queryset's
|
| 219 |
+
:meth:`~django.db.models.query.QuerySet.delete` method.
|
| 220 |
+
|
| 221 |
+
Arguments sent with this signal:
|
| 222 |
+
|
| 223 |
+
``sender``
|
| 224 |
+
The model class.
|
| 225 |
+
|
| 226 |
+
``instance``
|
| 227 |
+
The actual instance being deleted.
|
| 228 |
+
|
| 229 |
+
Note that the object will no longer be in the database, so be very
|
| 230 |
+
careful what you do with this instance.
|
| 231 |
+
|
| 232 |
+
``using``
|
| 233 |
+
The database alias being used.
|
| 234 |
+
|
| 235 |
+
``origin``
|
| 236 |
+
|
| 237 |
+
The origin of the deletion being the instance of a ``Model`` or
|
| 238 |
+
``QuerySet`` class.
|
| 239 |
+
|
| 240 |
+
``m2m_changed``
|
| 241 |
+
---------------
|
| 242 |
+
|
| 243 |
+
.. data:: django.db.models.signals.m2m_changed
|
| 244 |
+
:module:
|
| 245 |
+
|
| 246 |
+
Sent when a :class:`~django.db.models.ManyToManyField` is changed on a model
|
| 247 |
+
instance. Strictly speaking, this is not a model signal since it is sent by the
|
| 248 |
+
:class:`~django.db.models.ManyToManyField`, but since it complements the
|
| 249 |
+
:data:`pre_save`/:data:`post_save` and :data:`pre_delete`/:data:`post_delete`
|
| 250 |
+
when it comes to tracking changes to models, it is included here.
|
| 251 |
+
|
| 252 |
+
Arguments sent with this signal:
|
| 253 |
+
|
| 254 |
+
``sender``
|
| 255 |
+
The intermediate model class describing the
|
| 256 |
+
:class:`~django.db.models.ManyToManyField`. This class is automatically
|
| 257 |
+
created when a many-to-many field is defined; you can access it using the
|
| 258 |
+
``through`` attribute on the many-to-many field.
|
| 259 |
+
|
| 260 |
+
``instance``
|
| 261 |
+
The instance whose many-to-many relation is updated. This can be an
|
| 262 |
+
instance of the ``sender``, or of the class the
|
| 263 |
+
:class:`~django.db.models.ManyToManyField` is related to.
|
| 264 |
+
|
| 265 |
+
``action``
|
| 266 |
+
A string indicating the type of update that is done on the relation.
|
| 267 |
+
This can be one of the following:
|
| 268 |
+
|
| 269 |
+
``"pre_add"``
|
| 270 |
+
Sent *before* one or more objects are added to the relation.
|
| 271 |
+
``"post_add"``
|
| 272 |
+
Sent *after* one or more objects are added to the relation.
|
| 273 |
+
``"pre_remove"``
|
| 274 |
+
Sent *before* one or more objects are removed from the relation.
|
| 275 |
+
``"post_remove"``
|
| 276 |
+
Sent *after* one or more objects are removed from the relation.
|
| 277 |
+
``"pre_clear"``
|
| 278 |
+
Sent *before* the relation is cleared.
|
| 279 |
+
``"post_clear"``
|
| 280 |
+
Sent *after* the relation is cleared.
|
| 281 |
+
|
| 282 |
+
``reverse``
|
| 283 |
+
Indicates which side of the relation is updated (i.e., if it is the
|
| 284 |
+
forward or reverse relation that is being modified).
|
| 285 |
+
|
| 286 |
+
``model``
|
| 287 |
+
The class of the objects that are added to, removed from or cleared
|
| 288 |
+
from the relation.
|
| 289 |
+
|
| 290 |
+
``pk_set``
|
| 291 |
+
For the ``pre_add`` and ``post_add`` actions, this is a set of primary key
|
| 292 |
+
values that will be, or have been, added to the relation. This may be a
|
| 293 |
+
subset of the values submitted to be added, since inserts must filter
|
| 294 |
+
existing values in order to avoid a database ``IntegrityError``.
|
| 295 |
+
|
| 296 |
+
For the ``pre_remove`` and ``post_remove`` actions, this is a set of
|
| 297 |
+
primary key values that was submitted to be removed from the relation. This
|
| 298 |
+
is not dependent on whether the values actually will be, or have been,
|
| 299 |
+
removed. In particular, non-existent values may be submitted, and will
|
| 300 |
+
appear in ``pk_set``, even though they have no effect on the database.
|
| 301 |
+
|
| 302 |
+
For the ``pre_clear`` and ``post_clear`` actions, this is ``None``.
|
| 303 |
+
|
| 304 |
+
``using``
|
| 305 |
+
The database alias being used.
|
| 306 |
+
|
| 307 |
+
For example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled
|
| 308 |
+
like this::
|
| 309 |
+
|
| 310 |
+
class Topping(models.Model):
|
| 311 |
+
# ...
|
| 312 |
+
pass
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class Pizza(models.Model):
|
| 316 |
+
# ...
|
| 317 |
+
toppings = models.ManyToManyField(Topping)
|
| 318 |
+
|
| 319 |
+
If we connected a handler like this::
|
| 320 |
+
|
| 321 |
+
from django.db.models.signals import m2m_changed
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def toppings_changed(sender, **kwargs):
|
| 325 |
+
# Do something
|
| 326 |
+
pass
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
|
| 330 |
+
|
| 331 |
+
and then did something like this:
|
| 332 |
+
|
| 333 |
+
.. code-block:: pycon
|
| 334 |
+
|
| 335 |
+
>>> p = Pizza.objects.create(...)
|
| 336 |
+
>>> t = Topping.objects.create(...)
|
| 337 |
+
>>> p.toppings.add(t)
|
| 338 |
+
|
| 339 |
+
the arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in
|
| 340 |
+
the example above) would be:
|
| 341 |
+
|
| 342 |
+
============== ============================================================
|
| 343 |
+
Argument Value
|
| 344 |
+
============== ============================================================
|
| 345 |
+
``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
|
| 346 |
+
|
| 347 |
+
``instance`` ``p`` (the ``Pizza`` instance being modified)
|
| 348 |
+
|
| 349 |
+
``action`` ``"pre_add"`` (followed by a separate signal with ``"post_add"``)
|
| 350 |
+
|
| 351 |
+
``reverse`` ``False`` (``Pizza`` contains the
|
| 352 |
+
:class:`~django.db.models.ManyToManyField`, so this call
|
| 353 |
+
modifies the forward relation)
|
| 354 |
+
|
| 355 |
+
``model`` ``Topping`` (the class of the objects added to the
|
| 356 |
+
``Pizza``)
|
| 357 |
+
|
| 358 |
+
``pk_set`` ``{t.id}`` (since only ``Topping t`` was added to the relation)
|
| 359 |
+
|
| 360 |
+
``using`` ``"default"`` (since the default router sends writes here)
|
| 361 |
+
============== ============================================================
|
| 362 |
+
|
| 363 |
+
And if we would then do something like this:
|
| 364 |
+
|
| 365 |
+
.. code-block:: pycon
|
| 366 |
+
|
| 367 |
+
>>> t.pizza_set.remove(p)
|
| 368 |
+
|
| 369 |
+
the arguments sent to a :data:`m2m_changed` handler would be:
|
| 370 |
+
|
| 371 |
+
============== ============================================================
|
| 372 |
+
Argument Value
|
| 373 |
+
============== ============================================================
|
| 374 |
+
``sender`` ``Pizza.toppings.through`` (the intermediate m2m class)
|
| 375 |
+
|
| 376 |
+
``instance`` ``t`` (the ``Topping`` instance being modified)
|
| 377 |
+
|
| 378 |
+
``action`` ``"pre_remove"`` (followed by a separate signal with ``"post_remove"``)
|
| 379 |
+
|
| 380 |
+
``reverse`` ``True`` (``Pizza`` contains the
|
| 381 |
+
:class:`~django.db.models.ManyToManyField`, so this call
|
| 382 |
+
modifies the reverse relation)
|
| 383 |
+
|
| 384 |
+
``model`` ``Pizza`` (the class of the objects removed from the
|
| 385 |
+
``Topping``)
|
| 386 |
+
|
| 387 |
+
``pk_set`` ``{p.id}`` (since only ``Pizza p`` was removed from the
|
| 388 |
+
relation)
|
| 389 |
+
|
| 390 |
+
``using`` ``"default"`` (since the default router sends writes here)
|
| 391 |
+
============== ============================================================
|
| 392 |
+
|
| 393 |
+
``class_prepared``
|
| 394 |
+
------------------
|
| 395 |
+
|
| 396 |
+
.. data:: django.db.models.signals.class_prepared
|
| 397 |
+
:module:
|
| 398 |
+
|
| 399 |
+
Sent whenever a model class has been "prepared" -- that is, once a model has
|
| 400 |
+
been defined and registered with Django's model system. Django uses this
|
| 401 |
+
signal internally; it's not generally used in third-party applications.
|
| 402 |
+
|
| 403 |
+
Since this signal is sent during the app registry population process, and
|
| 404 |
+
:meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app
|
| 405 |
+
registry is fully populated, receivers cannot be connected in that method.
|
| 406 |
+
One possibility is to connect them ``AppConfig.__init__()`` instead, taking
|
| 407 |
+
care not to import models or trigger calls to the app registry.
|
| 408 |
+
|
| 409 |
+
Arguments that are sent with this signal:
|
| 410 |
+
|
| 411 |
+
``sender``
|
| 412 |
+
The model class which was just prepared.
|
| 413 |
+
|
| 414 |
+
Management signals
|
| 415 |
+
==================
|
| 416 |
+
|
| 417 |
+
Signals sent by :doc:`django-admin </ref/django-admin>`.
|
| 418 |
+
|
| 419 |
+
``pre_migrate``
|
| 420 |
+
---------------
|
| 421 |
+
|
| 422 |
+
.. data:: django.db.models.signals.pre_migrate
|
| 423 |
+
:module:
|
| 424 |
+
|
| 425 |
+
Sent by the :djadmin:`migrate` command before it starts to install an
|
| 426 |
+
application. It's not emitted for applications that lack a ``models`` module.
|
| 427 |
+
|
| 428 |
+
Arguments sent with this signal:
|
| 429 |
+
|
| 430 |
+
``sender``
|
| 431 |
+
An :class:`~django.apps.AppConfig` instance for the application about to
|
| 432 |
+
be migrated/synced.
|
| 433 |
+
|
| 434 |
+
``app_config``
|
| 435 |
+
Same as ``sender``.
|
| 436 |
+
|
| 437 |
+
``verbosity``
|
| 438 |
+
Indicates how much information ``manage.py`` is printing on screen. See
|
| 439 |
+
the :option:`--verbosity` flag for details.
|
| 440 |
+
|
| 441 |
+
Functions which listen for :data:`pre_migrate` should adjust what they
|
| 442 |
+
output to the screen based on the value of this argument.
|
| 443 |
+
|
| 444 |
+
``interactive``
|
| 445 |
+
If ``interactive`` is ``True``, it's safe to prompt the user to input
|
| 446 |
+
things on the command line. If ``interactive`` is ``False``, functions
|
| 447 |
+
which listen for this signal should not try to prompt for anything.
|
| 448 |
+
|
| 449 |
+
For example, the :mod:`django.contrib.auth` app only prompts to create a
|
| 450 |
+
superuser when ``interactive`` is ``True``.
|
| 451 |
+
|
| 452 |
+
``stdout``
|
| 453 |
+
A stream-like object where verbose output should be redirected.
|
| 454 |
+
|
| 455 |
+
``using``
|
| 456 |
+
The alias of database on which a command will operate.
|
| 457 |
+
|
| 458 |
+
``plan``
|
| 459 |
+
The migration plan that is going to be used for the migration run. While
|
| 460 |
+
the plan is not public API, this allows for the rare cases when it is
|
| 461 |
+
necessary to know the plan. A plan is a list of 2-tuples with the first
|
| 462 |
+
item being the instance of a migration class and the second item showing
|
| 463 |
+
if the migration was rolled back (``True``) or applied (``False``).
|
| 464 |
+
|
| 465 |
+
``apps``
|
| 466 |
+
An instance of :data:`Apps <django.apps>` containing the state of the
|
| 467 |
+
project before the migration run. It should be used instead of the global
|
| 468 |
+
:attr:`apps <django.apps.apps>` registry to retrieve the models you
|
| 469 |
+
want to perform operations on.
|
| 470 |
+
|
| 471 |
+
``post_migrate``
|
| 472 |
+
----------------
|
| 473 |
+
|
| 474 |
+
.. data:: django.db.models.signals.post_migrate
|
| 475 |
+
:module:
|
| 476 |
+
|
| 477 |
+
Sent at the end of the :djadmin:`migrate` (even if no migrations are run) and
|
| 478 |
+
:djadmin:`flush` commands. It's not emitted for applications that lack a
|
| 479 |
+
``models`` module.
|
| 480 |
+
|
| 481 |
+
Handlers of this signal must not perform database schema alterations as doing
|
| 482 |
+
so may cause the :djadmin:`flush` command to fail if it runs during the
|
| 483 |
+
:djadmin:`migrate` command.
|
| 484 |
+
|
| 485 |
+
Arguments sent with this signal:
|
| 486 |
+
|
| 487 |
+
``sender``
|
| 488 |
+
An :class:`~django.apps.AppConfig` instance for the application that was
|
| 489 |
+
just installed.
|
| 490 |
+
|
| 491 |
+
``app_config``
|
| 492 |
+
Same as ``sender``.
|
| 493 |
+
|
| 494 |
+
``verbosity``
|
| 495 |
+
Indicates how much information ``manage.py`` is printing on screen. See
|
| 496 |
+
the :option:`--verbosity` flag for details.
|
| 497 |
+
|
| 498 |
+
Functions which listen for :data:`post_migrate` should adjust what they
|
| 499 |
+
output to the screen based on the value of this argument.
|
| 500 |
+
|
| 501 |
+
``interactive``
|
| 502 |
+
If ``interactive`` is ``True``, it's safe to prompt the user to input
|
| 503 |
+
things on the command line. If ``interactive`` is ``False``, functions
|
| 504 |
+
which listen for this signal should not try to prompt for anything.
|
| 505 |
+
|
| 506 |
+
For example, the :mod:`django.contrib.auth` app only prompts to create a
|
| 507 |
+
superuser when ``interactive`` is ``True``.
|
| 508 |
+
|
| 509 |
+
``stdout``
|
| 510 |
+
A stream-like object where verbose output should be redirected.
|
| 511 |
+
|
| 512 |
+
``using``
|
| 513 |
+
The database alias used for synchronization. Defaults to the ``default``
|
| 514 |
+
database.
|
| 515 |
+
|
| 516 |
+
``plan``
|
| 517 |
+
The migration plan that was used for the migration run. While the plan is
|
| 518 |
+
not public API, this allows for the rare cases when it is necessary to
|
| 519 |
+
know the plan. A plan is a list of 2-tuples with the first item being
|
| 520 |
+
the instance of a migration class and the second item showing if the
|
| 521 |
+
migration was rolled back (``True``) or applied (``False``).
|
| 522 |
+
|
| 523 |
+
``apps``
|
| 524 |
+
An instance of :data:`Apps <django.apps.apps>` containing the state of the
|
| 525 |
+
project after the migration run. It should be used instead of the global
|
| 526 |
+
:attr:`apps <django.apps.apps>` registry to retrieve the models you
|
| 527 |
+
want to perform operations on.
|
| 528 |
+
|
| 529 |
+
For example, you could register a callback in an
|
| 530 |
+
:class:`~django.apps.AppConfig` like this::
|
| 531 |
+
|
| 532 |
+
from django.apps import AppConfig
|
| 533 |
+
from django.db.models.signals import post_migrate
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def my_callback(sender, **kwargs):
|
| 537 |
+
# Your specific logic here
|
| 538 |
+
pass
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class MyAppConfig(AppConfig):
|
| 542 |
+
...
|
| 543 |
+
|
| 544 |
+
def ready(self):
|
| 545 |
+
post_migrate.connect(my_callback, sender=self)
|
| 546 |
+
|
| 547 |
+
.. note::
|
| 548 |
+
|
| 549 |
+
If you provide an :class:`~django.apps.AppConfig` instance as the sender
|
| 550 |
+
argument, please ensure that the signal is registered in
|
| 551 |
+
:meth:`~django.apps.AppConfig.ready`. ``AppConfig``\s are recreated for
|
| 552 |
+
tests that run with a modified set of :setting:`INSTALLED_APPS` (such as
|
| 553 |
+
when settings are overridden) and such signals should be connected for each
|
| 554 |
+
new ``AppConfig`` instance.
|
| 555 |
+
|
| 556 |
+
Request/response signals
|
| 557 |
+
========================
|
| 558 |
+
|
| 559 |
+
.. module:: django.core.signals
|
| 560 |
+
:synopsis: Core signals sent by the request/response system.
|
| 561 |
+
|
| 562 |
+
Signals sent by the core framework when processing a request.
|
| 563 |
+
|
| 564 |
+
.. warning::
|
| 565 |
+
|
| 566 |
+
Signals can make your code harder to maintain. Consider :doc:`using a
|
| 567 |
+
middleware </topics/http/middleware>` before using request/response
|
| 568 |
+
signals.
|
| 569 |
+
|
| 570 |
+
``request_started``
|
| 571 |
+
-------------------
|
| 572 |
+
|
| 573 |
+
.. data:: django.core.signals.request_started
|
| 574 |
+
:module:
|
| 575 |
+
|
| 576 |
+
Sent when Django begins processing an HTTP request.
|
| 577 |
+
|
| 578 |
+
Arguments sent with this signal:
|
| 579 |
+
|
| 580 |
+
``sender``
|
| 581 |
+
The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
|
| 582 |
+
handled the request.
|
| 583 |
+
``environ``
|
| 584 |
+
The ``environ`` dictionary provided to the request.
|
| 585 |
+
|
| 586 |
+
``request_finished``
|
| 587 |
+
--------------------
|
| 588 |
+
|
| 589 |
+
.. data:: django.core.signals.request_finished
|
| 590 |
+
:module:
|
| 591 |
+
|
| 592 |
+
Sent when Django finishes delivering an HTTP response to the client.
|
| 593 |
+
|
| 594 |
+
Arguments sent with this signal:
|
| 595 |
+
|
| 596 |
+
``sender``
|
| 597 |
+
The handler class, as above.
|
| 598 |
+
|
| 599 |
+
``got_request_exception``
|
| 600 |
+
-------------------------
|
| 601 |
+
|
| 602 |
+
.. data:: django.core.signals.got_request_exception
|
| 603 |
+
:module:
|
| 604 |
+
|
| 605 |
+
This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
|
| 606 |
+
|
| 607 |
+
Arguments sent with this signal:
|
| 608 |
+
|
| 609 |
+
``sender``
|
| 610 |
+
Unused (always ``None``).
|
| 611 |
+
|
| 612 |
+
``request``
|
| 613 |
+
The :class:`~django.http.HttpRequest` object.
|
| 614 |
+
|
| 615 |
+
Test signals
|
| 616 |
+
============
|
| 617 |
+
|
| 618 |
+
.. module:: django.test.signals
|
| 619 |
+
:synopsis: Signals sent during testing.
|
| 620 |
+
|
| 621 |
+
Signals only sent when :ref:`running tests <running-tests>`.
|
| 622 |
+
|
| 623 |
+
``setting_changed``
|
| 624 |
+
-------------------
|
| 625 |
+
|
| 626 |
+
.. data:: django.test.signals.setting_changed
|
| 627 |
+
:module:
|
| 628 |
+
|
| 629 |
+
This signal is sent when the value of a setting is changed through the
|
| 630 |
+
``django.test.TestCase.settings()`` context manager or the
|
| 631 |
+
:func:`django.test.override_settings` decorator/context manager.
|
| 632 |
+
|
| 633 |
+
It's actually sent twice: when the new value is applied ("setup") and when the
|
| 634 |
+
original value is restored ("teardown"). Use the ``enter`` argument to
|
| 635 |
+
distinguish between the two.
|
| 636 |
+
|
| 637 |
+
You can also import this signal from ``django.core.signals`` to avoid importing
|
| 638 |
+
from ``django.test`` in non-test situations.
|
| 639 |
+
|
| 640 |
+
Arguments sent with this signal:
|
| 641 |
+
|
| 642 |
+
``sender``
|
| 643 |
+
The settings handler.
|
| 644 |
+
|
| 645 |
+
``setting``
|
| 646 |
+
The name of the setting.
|
| 647 |
+
|
| 648 |
+
``value``
|
| 649 |
+
The value of the setting after the change. For settings that initially
|
| 650 |
+
don't exist, in the "teardown" phase, ``value`` is ``None``.
|
| 651 |
+
|
| 652 |
+
``enter``
|
| 653 |
+
A boolean; ``True`` if the setting is applied, ``False`` if restored.
|
| 654 |
+
|
| 655 |
+
``template_rendered``
|
| 656 |
+
---------------------
|
| 657 |
+
|
| 658 |
+
.. data:: django.test.signals.template_rendered
|
| 659 |
+
:module:
|
| 660 |
+
|
| 661 |
+
Sent when the test system renders a template. This signal is not emitted during
|
| 662 |
+
normal operation of a Django server -- it is only available during testing.
|
| 663 |
+
|
| 664 |
+
Arguments sent with this signal:
|
| 665 |
+
|
| 666 |
+
``sender``
|
| 667 |
+
The :class:`~django.template.Template` object which was rendered.
|
| 668 |
+
|
| 669 |
+
``template``
|
| 670 |
+
Same as sender
|
| 671 |
+
|
| 672 |
+
``context``
|
| 673 |
+
The :class:`~django.template.Context` with which the template was
|
| 674 |
+
rendered.
|
| 675 |
+
|
| 676 |
+
Database Wrappers
|
| 677 |
+
=================
|
| 678 |
+
|
| 679 |
+
.. module:: django.db.backends
|
| 680 |
+
:synopsis: Core signals sent by the database wrapper.
|
| 681 |
+
|
| 682 |
+
Signals sent by the database wrapper when a database connection is
|
| 683 |
+
initiated.
|
| 684 |
+
|
| 685 |
+
``connection_created``
|
| 686 |
+
----------------------
|
| 687 |
+
|
| 688 |
+
.. data:: django.db.backends.signals.connection_created
|
| 689 |
+
:module:
|
| 690 |
+
|
| 691 |
+
Sent when the database wrapper makes the initial connection to the
|
| 692 |
+
database. This is particularly useful if you'd like to send any post
|
| 693 |
+
connection commands to the SQL backend.
|
| 694 |
+
|
| 695 |
+
Arguments sent with this signal:
|
| 696 |
+
|
| 697 |
+
``sender``
|
| 698 |
+
The database wrapper class -- i.e.
|
| 699 |
+
``django.db.backends.postgresql.DatabaseWrapper`` or
|
| 700 |
+
``django.db.backends.mysql.DatabaseWrapper``, etc.
|
| 701 |
+
|
| 702 |
+
``connection``
|
| 703 |
+
The database connection that was opened. This can be used in a
|
| 704 |
+
multiple-database configuration to differentiate connection signals
|
| 705 |
+
from different databases.
|
testbed/django__django/docs/ref/template-response.txt
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===================================================
|
| 2 |
+
``TemplateResponse`` and ``SimpleTemplateResponse``
|
| 3 |
+
===================================================
|
| 4 |
+
|
| 5 |
+
.. module:: django.template.response
|
| 6 |
+
:synopsis: Classes dealing with lazy-rendered HTTP responses.
|
| 7 |
+
|
| 8 |
+
Standard :class:`~django.http.HttpResponse` objects are static structures.
|
| 9 |
+
They are provided with a block of pre-rendered content at time of
|
| 10 |
+
construction, and while that content can be modified, it isn't in a form that
|
| 11 |
+
makes it easy to perform modifications.
|
| 12 |
+
|
| 13 |
+
However, it can sometimes be beneficial to allow decorators or
|
| 14 |
+
middleware to modify a response *after* it has been constructed by the
|
| 15 |
+
view. For example, you may want to change the template that is used,
|
| 16 |
+
or put additional data into the context.
|
| 17 |
+
|
| 18 |
+
TemplateResponse provides a way to do just that. Unlike basic
|
| 19 |
+
:class:`~django.http.HttpResponse` objects, TemplateResponse objects retain
|
| 20 |
+
the details of the template and context that was provided by the view to
|
| 21 |
+
compute the response. The final output of the response is not computed until
|
| 22 |
+
it is needed, later in the response process.
|
| 23 |
+
|
| 24 |
+
``SimpleTemplateResponse`` objects
|
| 25 |
+
==================================
|
| 26 |
+
|
| 27 |
+
.. class:: SimpleTemplateResponse()
|
| 28 |
+
|
| 29 |
+
Attributes
|
| 30 |
+
----------
|
| 31 |
+
|
| 32 |
+
.. attribute:: SimpleTemplateResponse.template_name
|
| 33 |
+
|
| 34 |
+
The name of the template to be rendered. Accepts a backend-dependent
|
| 35 |
+
template object (such as those returned by
|
| 36 |
+
:func:`~django.template.loader.get_template()`), the name of a template,
|
| 37 |
+
or a list of template names.
|
| 38 |
+
|
| 39 |
+
Example: ``['foo.html', 'path/to/bar.html']``
|
| 40 |
+
|
| 41 |
+
.. attribute:: SimpleTemplateResponse.context_data
|
| 42 |
+
|
| 43 |
+
The context data to be used when rendering the template. It must be a
|
| 44 |
+
:class:`dict`.
|
| 45 |
+
|
| 46 |
+
Example: ``{'foo': 123}``
|
| 47 |
+
|
| 48 |
+
.. attribute:: SimpleTemplateResponse.rendered_content
|
| 49 |
+
|
| 50 |
+
The current rendered value of the response content, using the current
|
| 51 |
+
template and context data.
|
| 52 |
+
|
| 53 |
+
.. attribute:: SimpleTemplateResponse.is_rendered
|
| 54 |
+
|
| 55 |
+
A boolean indicating whether the response content has been rendered.
|
| 56 |
+
|
| 57 |
+
Methods
|
| 58 |
+
-------
|
| 59 |
+
|
| 60 |
+
.. method:: SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)
|
| 61 |
+
|
| 62 |
+
Instantiates a :class:`~django.template.response.SimpleTemplateResponse`
|
| 63 |
+
object with the given template, context, content type, HTTP status, and
|
| 64 |
+
charset.
|
| 65 |
+
|
| 66 |
+
``template``
|
| 67 |
+
A backend-dependent template object (such as those returned by
|
| 68 |
+
:func:`~django.template.loader.get_template()`), the name of a template,
|
| 69 |
+
or a list of template names.
|
| 70 |
+
|
| 71 |
+
``context``
|
| 72 |
+
A :class:`dict` of values to add to the template context. By default,
|
| 73 |
+
this is an empty dictionary.
|
| 74 |
+
|
| 75 |
+
``content_type``
|
| 76 |
+
The value included in the HTTP ``Content-Type`` header, including the
|
| 77 |
+
MIME type specification and the character set encoding. If
|
| 78 |
+
``content_type`` is specified, then its value is used. Otherwise,
|
| 79 |
+
``'text/html'`` is used.
|
| 80 |
+
|
| 81 |
+
``status``
|
| 82 |
+
The HTTP status code for the response.
|
| 83 |
+
|
| 84 |
+
``charset``
|
| 85 |
+
The charset in which the response will be encoded. If not given it will
|
| 86 |
+
be extracted from ``content_type``, and if that is unsuccessful, the
|
| 87 |
+
:setting:`DEFAULT_CHARSET` setting will be used.
|
| 88 |
+
|
| 89 |
+
``using``
|
| 90 |
+
The :setting:`NAME <TEMPLATES-NAME>` of a template engine to use for
|
| 91 |
+
loading the template.
|
| 92 |
+
|
| 93 |
+
``headers``
|
| 94 |
+
A :class:`dict` of HTTP headers to add to the response.
|
| 95 |
+
|
| 96 |
+
.. method:: SimpleTemplateResponse.resolve_context(context)
|
| 97 |
+
|
| 98 |
+
Preprocesses context data that will be used for rendering a template.
|
| 99 |
+
Accepts a :class:`dict` of context data. By default, returns the same
|
| 100 |
+
:class:`dict`.
|
| 101 |
+
|
| 102 |
+
Override this method in order to customize the context.
|
| 103 |
+
|
| 104 |
+
.. method:: SimpleTemplateResponse.resolve_template(template)
|
| 105 |
+
|
| 106 |
+
Resolves the template instance to use for rendering. Accepts a
|
| 107 |
+
backend-dependent template object (such as those returned by
|
| 108 |
+
:func:`~django.template.loader.get_template()`), the name of a template,
|
| 109 |
+
or a list of template names.
|
| 110 |
+
|
| 111 |
+
Returns the backend-dependent template object instance to be rendered.
|
| 112 |
+
|
| 113 |
+
Override this method in order to customize template loading.
|
| 114 |
+
|
| 115 |
+
.. method:: SimpleTemplateResponse.add_post_render_callback()
|
| 116 |
+
|
| 117 |
+
Add a callback that will be invoked after rendering has taken
|
| 118 |
+
place. This hook can be used to defer certain processing
|
| 119 |
+
operations (such as caching) until after rendering has occurred.
|
| 120 |
+
|
| 121 |
+
If the :class:`~django.template.response.SimpleTemplateResponse`
|
| 122 |
+
has already been rendered, the callback will be invoked
|
| 123 |
+
immediately.
|
| 124 |
+
|
| 125 |
+
When called, callbacks will be passed a single argument -- the
|
| 126 |
+
rendered :class:`~django.template.response.SimpleTemplateResponse`
|
| 127 |
+
instance.
|
| 128 |
+
|
| 129 |
+
If the callback returns a value that is not ``None``, this will be
|
| 130 |
+
used as the response instead of the original response object (and
|
| 131 |
+
will be passed to the next post rendering callback etc.)
|
| 132 |
+
|
| 133 |
+
.. method:: SimpleTemplateResponse.render()
|
| 134 |
+
|
| 135 |
+
Sets ``response.content`` to the result obtained by
|
| 136 |
+
:attr:`SimpleTemplateResponse.rendered_content`, runs all post-rendering
|
| 137 |
+
callbacks, and returns the resulting response object.
|
| 138 |
+
|
| 139 |
+
``render()`` will only have an effect the first time it is called. On
|
| 140 |
+
subsequent calls, it will return the result obtained from the first call.
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
``TemplateResponse`` objects
|
| 144 |
+
============================
|
| 145 |
+
|
| 146 |
+
.. class:: TemplateResponse()
|
| 147 |
+
|
| 148 |
+
``TemplateResponse`` is a subclass of
|
| 149 |
+
:class:`~django.template.response.SimpleTemplateResponse` that knows about
|
| 150 |
+
the current :class:`~django.http.HttpRequest`.
|
| 151 |
+
|
| 152 |
+
Methods
|
| 153 |
+
-------
|
| 154 |
+
|
| 155 |
+
.. method:: TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)
|
| 156 |
+
|
| 157 |
+
Instantiates a :class:`~django.template.response.TemplateResponse` object
|
| 158 |
+
with the given request, template, context, content type, HTTP status, and
|
| 159 |
+
charset.
|
| 160 |
+
|
| 161 |
+
``request``
|
| 162 |
+
An :class:`~django.http.HttpRequest` instance.
|
| 163 |
+
|
| 164 |
+
``template``
|
| 165 |
+
A backend-dependent template object (such as those returned by
|
| 166 |
+
:func:`~django.template.loader.get_template()`), the name of a template,
|
| 167 |
+
or a list of template names.
|
| 168 |
+
|
| 169 |
+
``context``
|
| 170 |
+
A :class:`dict` of values to add to the template context. By default,
|
| 171 |
+
this is an empty dictionary.
|
| 172 |
+
|
| 173 |
+
``content_type``
|
| 174 |
+
The value included in the HTTP ``Content-Type`` header, including the
|
| 175 |
+
MIME type specification and the character set encoding. If
|
| 176 |
+
``content_type`` is specified, then its value is used. Otherwise,
|
| 177 |
+
``'text/html'`` is used.
|
| 178 |
+
|
| 179 |
+
``status``
|
| 180 |
+
The HTTP status code for the response.
|
| 181 |
+
|
| 182 |
+
``charset``
|
| 183 |
+
The charset in which the response will be encoded. If not given it will
|
| 184 |
+
be extracted from ``content_type``, and if that is unsuccessful, the
|
| 185 |
+
:setting:`DEFAULT_CHARSET` setting will be used.
|
| 186 |
+
|
| 187 |
+
``using``
|
| 188 |
+
The :setting:`NAME <TEMPLATES-NAME>` of a template engine to use for
|
| 189 |
+
loading the template.
|
| 190 |
+
|
| 191 |
+
``headers``
|
| 192 |
+
A :class:`dict` of HTTP headers to add to the response.
|
| 193 |
+
|
| 194 |
+
The rendering process
|
| 195 |
+
=====================
|
| 196 |
+
|
| 197 |
+
Before a :class:`~django.template.response.TemplateResponse` instance can be
|
| 198 |
+
returned to the client, it must be rendered. The rendering process takes the
|
| 199 |
+
intermediate representation of template and context, and turns it into the
|
| 200 |
+
final byte stream that can be served to the client.
|
| 201 |
+
|
| 202 |
+
There are three circumstances under which a ``TemplateResponse`` will be
|
| 203 |
+
rendered:
|
| 204 |
+
|
| 205 |
+
* When the ``TemplateResponse`` instance is explicitly rendered, using
|
| 206 |
+
the :meth:`SimpleTemplateResponse.render()` method.
|
| 207 |
+
|
| 208 |
+
* When the content of the response is explicitly set by assigning
|
| 209 |
+
``response.content``.
|
| 210 |
+
|
| 211 |
+
* After passing through template response middleware, but before
|
| 212 |
+
passing through response middleware.
|
| 213 |
+
|
| 214 |
+
A ``TemplateResponse`` can only be rendered once. The first call to
|
| 215 |
+
:meth:`SimpleTemplateResponse.render` sets the content of the response;
|
| 216 |
+
subsequent rendering calls do not change the response content.
|
| 217 |
+
|
| 218 |
+
However, when ``response.content`` is explicitly assigned, the
|
| 219 |
+
change is always applied. If you want to force the content to be
|
| 220 |
+
re-rendered, you can reevaluate the rendered content, and assign
|
| 221 |
+
the content of the response manually:
|
| 222 |
+
|
| 223 |
+
.. code-block:: pycon
|
| 224 |
+
|
| 225 |
+
# Set up a rendered TemplateResponse
|
| 226 |
+
>>> from django.template.response import TemplateResponse
|
| 227 |
+
>>> t = TemplateResponse(request, "original.html", {})
|
| 228 |
+
>>> t.render()
|
| 229 |
+
>>> print(t.content)
|
| 230 |
+
Original content
|
| 231 |
+
|
| 232 |
+
# Re-rendering doesn't change content
|
| 233 |
+
>>> t.template_name = "new.html"
|
| 234 |
+
>>> t.render()
|
| 235 |
+
>>> print(t.content)
|
| 236 |
+
Original content
|
| 237 |
+
|
| 238 |
+
# Assigning content does change, no render() call required
|
| 239 |
+
>>> t.content = t.rendered_content
|
| 240 |
+
>>> print(t.content)
|
| 241 |
+
New content
|
| 242 |
+
|
| 243 |
+
Post-render callbacks
|
| 244 |
+
---------------------
|
| 245 |
+
|
| 246 |
+
Some operations -- such as caching -- cannot be performed on an
|
| 247 |
+
unrendered template. They must be performed on a fully complete and
|
| 248 |
+
rendered response.
|
| 249 |
+
|
| 250 |
+
If you're using middleware, you can do that. Middleware provides
|
| 251 |
+
multiple opportunities to process a response on exit from a view. If
|
| 252 |
+
you put behavior in the response middleware, it's guaranteed to execute
|
| 253 |
+
after template rendering has taken place.
|
| 254 |
+
|
| 255 |
+
However, if you're using a decorator, the same opportunities do not
|
| 256 |
+
exist. Any behavior defined in a decorator is handled immediately.
|
| 257 |
+
|
| 258 |
+
To compensate for this (and any other analogous use cases),
|
| 259 |
+
:class:`TemplateResponse` allows you to register callbacks that will
|
| 260 |
+
be invoked when rendering has completed. Using this callback, you can
|
| 261 |
+
defer critical processing until a point where you can guarantee that
|
| 262 |
+
rendered content will be available.
|
| 263 |
+
|
| 264 |
+
To define a post-render callback, define a function that takes
|
| 265 |
+
a single argument -- response -- and register that function with
|
| 266 |
+
the template response::
|
| 267 |
+
|
| 268 |
+
from django.template.response import TemplateResponse
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def my_render_callback(response):
|
| 272 |
+
# Do content-sensitive processing
|
| 273 |
+
do_post_processing()
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def my_view(request):
|
| 277 |
+
# Create a response
|
| 278 |
+
response = TemplateResponse(request, "mytemplate.html", {})
|
| 279 |
+
# Register the callback
|
| 280 |
+
response.add_post_render_callback(my_render_callback)
|
| 281 |
+
# Return the response
|
| 282 |
+
return response
|
| 283 |
+
|
| 284 |
+
``my_render_callback()`` will be invoked after the ``mytemplate.html``
|
| 285 |
+
has been rendered, and will be provided the fully rendered
|
| 286 |
+
:class:`TemplateResponse` instance as an argument.
|
| 287 |
+
|
| 288 |
+
If the template has already been rendered, the callback will be
|
| 289 |
+
invoked immediately.
|
| 290 |
+
|
| 291 |
+
Using ``TemplateResponse`` and ``SimpleTemplateResponse``
|
| 292 |
+
=========================================================
|
| 293 |
+
|
| 294 |
+
A :class:`TemplateResponse` object can be used anywhere that a normal
|
| 295 |
+
:class:`django.http.HttpResponse` can be used. It can also be used as an
|
| 296 |
+
alternative to calling :func:`~django.shortcuts.render()`.
|
| 297 |
+
|
| 298 |
+
For example, the following view returns a :class:`TemplateResponse` with a
|
| 299 |
+
template and a context containing a queryset::
|
| 300 |
+
|
| 301 |
+
from django.template.response import TemplateResponse
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def blog_index(request):
|
| 305 |
+
return TemplateResponse(
|
| 306 |
+
request, "entry_list.html", {"entries": Entry.objects.all()}
|
| 307 |
+
)
|
testbed/django__django/docs/ref/unicode.txt
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============
|
| 2 |
+
Unicode data
|
| 3 |
+
============
|
| 4 |
+
|
| 5 |
+
Django supports Unicode data everywhere.
|
| 6 |
+
|
| 7 |
+
This document tells you what you need to know if you're writing applications
|
| 8 |
+
that use data or templates that are encoded in something other than ASCII.
|
| 9 |
+
|
| 10 |
+
Creating the database
|
| 11 |
+
=====================
|
| 12 |
+
|
| 13 |
+
Make sure your database is configured to be able to store arbitrary string
|
| 14 |
+
data. Normally, this means giving it an encoding of UTF-8 or UTF-16. If you use
|
| 15 |
+
a more restrictive encoding -- for example, latin1 (iso8859-1) -- you won't be
|
| 16 |
+
able to store certain characters in the database, and information will be lost.
|
| 17 |
+
|
| 18 |
+
* MySQL users, refer to the `MySQL manual`_ for details on how to set or alter
|
| 19 |
+
the database character set encoding.
|
| 20 |
+
|
| 21 |
+
* PostgreSQL users, refer to the `PostgreSQL manual`_ for details on creating
|
| 22 |
+
databases with the correct encoding.
|
| 23 |
+
|
| 24 |
+
* Oracle users, refer to the `Oracle manual`_ for details on how to set
|
| 25 |
+
(`section 2`_) or alter (`section 11`_) the database character set encoding.
|
| 26 |
+
|
| 27 |
+
* SQLite users, there is nothing you need to do. SQLite always uses UTF-8
|
| 28 |
+
for internal encoding.
|
| 29 |
+
|
| 30 |
+
.. _MySQL manual: https://dev.mysql.com/doc/refman/en/charset-database.html
|
| 31 |
+
.. _PostgreSQL manual: https://www.postgresql.org/docs/current/multibyte.html#id-1.6.11.5.6
|
| 32 |
+
.. _Oracle manual: https://docs.oracle.com/en/database/oracle/oracle-database/21/nlspg/index.html
|
| 33 |
+
.. _section 2: https://docs.oracle.com/en/database/oracle/oracle-database/21/nlspg/choosing-character-set.html
|
| 34 |
+
.. _section 11: https://docs.oracle.com/en/database/oracle/oracle-database/21/nlspg/character-set-migration.html
|
| 35 |
+
|
| 36 |
+
All of Django's database backends automatically convert strings into
|
| 37 |
+
the appropriate encoding for talking to the database. They also automatically
|
| 38 |
+
convert strings retrieved from the database into strings. You don't even need
|
| 39 |
+
to tell Django what encoding your database uses: that is handled transparently.
|
| 40 |
+
|
| 41 |
+
For more, see the section "The database API" below.
|
| 42 |
+
|
| 43 |
+
General string handling
|
| 44 |
+
=======================
|
| 45 |
+
|
| 46 |
+
Whenever you use strings with Django -- e.g., in database lookups, template
|
| 47 |
+
rendering or anywhere else -- you have two choices for encoding those strings.
|
| 48 |
+
You can use normal strings or bytestrings (starting with a 'b').
|
| 49 |
+
|
| 50 |
+
.. warning::
|
| 51 |
+
|
| 52 |
+
A bytestring does not carry any information with it about its encoding.
|
| 53 |
+
For that reason, we have to make an assumption, and Django assumes that all
|
| 54 |
+
bytestrings are in UTF-8.
|
| 55 |
+
|
| 56 |
+
If you pass a string to Django that has been encoded in some other format,
|
| 57 |
+
things will go wrong in interesting ways. Usually, Django will raise a
|
| 58 |
+
``UnicodeDecodeError`` at some point.
|
| 59 |
+
|
| 60 |
+
If your code only uses ASCII data, it's safe to use your normal strings,
|
| 61 |
+
passing them around at will, because ASCII is a subset of UTF-8.
|
| 62 |
+
|
| 63 |
+
Don't be fooled into thinking that if your :setting:`DEFAULT_CHARSET` setting is set
|
| 64 |
+
to something other than ``'utf-8'`` you can use that other encoding in your
|
| 65 |
+
bytestrings! :setting:`DEFAULT_CHARSET` only applies to the strings generated as
|
| 66 |
+
the result of template rendering (and email). Django will always assume UTF-8
|
| 67 |
+
encoding for internal bytestrings. The reason for this is that the
|
| 68 |
+
:setting:`DEFAULT_CHARSET` setting is not actually under your control (if you are the
|
| 69 |
+
application developer). It's under the control of the person installing and
|
| 70 |
+
using your application -- and if that person chooses a different setting, your
|
| 71 |
+
code must still continue to work. Ergo, it cannot rely on that setting.
|
| 72 |
+
|
| 73 |
+
In most cases when Django is dealing with strings, it will convert them to
|
| 74 |
+
strings before doing anything else. So, as a general rule, if you pass
|
| 75 |
+
in a bytestring, be prepared to receive a string back in the result.
|
| 76 |
+
|
| 77 |
+
Translated strings
|
| 78 |
+
------------------
|
| 79 |
+
|
| 80 |
+
Aside from strings and bytestrings, there's a third type of string-like
|
| 81 |
+
object you may encounter when using Django. The framework's
|
| 82 |
+
internationalization features introduce the concept of a "lazy translation" --
|
| 83 |
+
a string that has been marked as translated but whose actual translation result
|
| 84 |
+
isn't determined until the object is used in a string. This feature is useful
|
| 85 |
+
in cases where the translation locale is unknown until the string is used, even
|
| 86 |
+
though the string might have originally been created when the code was first
|
| 87 |
+
imported.
|
| 88 |
+
|
| 89 |
+
Normally, you won't have to worry about lazy translations. Just be aware that
|
| 90 |
+
if you examine an object and it claims to be a
|
| 91 |
+
``django.utils.functional.__proxy__`` object, it is a lazy translation.
|
| 92 |
+
Calling ``str()`` with the lazy translation as the argument will generate a
|
| 93 |
+
string in the current locale.
|
| 94 |
+
|
| 95 |
+
For more details about lazy translation objects, refer to the
|
| 96 |
+
:doc:`internationalization </topics/i18n/index>` documentation.
|
| 97 |
+
|
| 98 |
+
Useful utility functions
|
| 99 |
+
------------------------
|
| 100 |
+
|
| 101 |
+
Because some string operations come up again and again, Django ships with a few
|
| 102 |
+
useful functions that should make working with string and bytestring objects
|
| 103 |
+
a bit easier.
|
| 104 |
+
|
| 105 |
+
Conversion functions
|
| 106 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 107 |
+
|
| 108 |
+
The ``django.utils.encoding`` module contains a few functions that are handy
|
| 109 |
+
for converting back and forth between strings and bytestrings.
|
| 110 |
+
|
| 111 |
+
* ``smart_str(s, encoding='utf-8', strings_only=False, errors='strict')``
|
| 112 |
+
converts its input to a string. The ``encoding`` parameter
|
| 113 |
+
specifies the input encoding. (For example, Django uses this internally
|
| 114 |
+
when processing form input data, which might not be UTF-8 encoded.) The
|
| 115 |
+
``strings_only`` parameter, if set to True, will result in Python
|
| 116 |
+
numbers, booleans and ``None`` not being converted to a string (they keep
|
| 117 |
+
their original types). The ``errors`` parameter takes any of the values
|
| 118 |
+
that are accepted by Python's ``str()`` function for its error
|
| 119 |
+
handling.
|
| 120 |
+
|
| 121 |
+
* ``force_str(s, encoding='utf-8', strings_only=False, errors='strict')`` is
|
| 122 |
+
identical to ``smart_str()`` in almost all cases. The difference is when the
|
| 123 |
+
first argument is a :ref:`lazy translation <lazy-translations>` instance.
|
| 124 |
+
While ``smart_str()`` preserves lazy translations, ``force_str()`` forces
|
| 125 |
+
those objects to a string (causing the translation to occur). Normally,
|
| 126 |
+
you'll want to use ``smart_str()``. However, ``force_str()`` is useful in
|
| 127 |
+
template tags and filters that absolutely *must* have a string to work with,
|
| 128 |
+
not just something that can be converted to a string.
|
| 129 |
+
|
| 130 |
+
* ``smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')``
|
| 131 |
+
is essentially the opposite of ``smart_str()``. It forces the first
|
| 132 |
+
argument to a bytestring. The ``strings_only`` parameter has the same
|
| 133 |
+
behavior as for ``smart_str()`` and ``force_str()``. This is
|
| 134 |
+
slightly different semantics from Python's builtin ``str()`` function,
|
| 135 |
+
but the difference is needed in a few places within Django's internals.
|
| 136 |
+
|
| 137 |
+
Normally, you'll only need to use ``force_str()``. Call it as early as
|
| 138 |
+
possible on any input data that might be either a string or a bytestring, and
|
| 139 |
+
from then on, you can treat the result as always being a string.
|
| 140 |
+
|
| 141 |
+
.. _uri-and-iri-handling:
|
| 142 |
+
|
| 143 |
+
URI and IRI handling
|
| 144 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 145 |
+
|
| 146 |
+
Web frameworks have to deal with URLs (which are a type of IRI). One
|
| 147 |
+
requirement of URLs is that they are encoded using only ASCII characters.
|
| 148 |
+
However, in an international environment, you might need to construct a
|
| 149 |
+
URL from an :rfc:`IRI <3987>` -- very loosely speaking, a :rfc:`URI <3986>`
|
| 150 |
+
that can contain Unicode characters. Use these functions for quoting and
|
| 151 |
+
converting an IRI to a URI:
|
| 152 |
+
|
| 153 |
+
* The :func:`django.utils.encoding.iri_to_uri()` function, which implements the
|
| 154 |
+
conversion from IRI to URI as required by :rfc:`3987#section-3.1`.
|
| 155 |
+
|
| 156 |
+
* The :func:`urllib.parse.quote` and :func:`urllib.parse.quote_plus`
|
| 157 |
+
functions from Python's standard library.
|
| 158 |
+
|
| 159 |
+
These two groups of functions have slightly different purposes, and it's
|
| 160 |
+
important to keep them straight. Normally, you would use ``quote()`` on the
|
| 161 |
+
individual portions of the IRI or URI path so that any reserved characters
|
| 162 |
+
such as '&' or '%' are correctly encoded. Then, you apply ``iri_to_uri()`` to
|
| 163 |
+
the full IRI and it converts any non-ASCII characters to the correct encoded
|
| 164 |
+
values.
|
| 165 |
+
|
| 166 |
+
.. note::
|
| 167 |
+
Technically, it isn't correct to say that ``iri_to_uri()`` implements the
|
| 168 |
+
full algorithm in the IRI specification. It doesn't (yet) perform the
|
| 169 |
+
international domain name encoding portion of the algorithm.
|
| 170 |
+
|
| 171 |
+
The ``iri_to_uri()`` function will not change ASCII characters that are
|
| 172 |
+
otherwise permitted in a URL. So, for example, the character '%' is not
|
| 173 |
+
further encoded when passed to ``iri_to_uri()``. This means you can pass a
|
| 174 |
+
full URL to this function and it will not mess up the query string or anything
|
| 175 |
+
like that.
|
| 176 |
+
|
| 177 |
+
An example might clarify things here:
|
| 178 |
+
|
| 179 |
+
.. code-block:: pycon
|
| 180 |
+
|
| 181 |
+
>>> from urllib.parse import quote
|
| 182 |
+
>>> from django.utils.encoding import iri_to_uri
|
| 183 |
+
>>> quote("Paris & Orléans")
|
| 184 |
+
'Paris%20%26%20Orl%C3%A9ans'
|
| 185 |
+
>>> iri_to_uri("/favorites/François/%s" % quote("Paris & Orléans"))
|
| 186 |
+
'/favorites/Fran%C3%A7ois/Paris%20%26%20Orl%C3%A9ans'
|
| 187 |
+
|
| 188 |
+
If you look carefully, you can see that the portion that was generated by
|
| 189 |
+
``quote()`` in the second example was not double-quoted when passed to
|
| 190 |
+
``iri_to_uri()``. This is a very important and useful feature. It means that
|
| 191 |
+
you can construct your IRI without worrying about whether it contains
|
| 192 |
+
non-ASCII characters and then, right at the end, call ``iri_to_uri()`` on the
|
| 193 |
+
result.
|
| 194 |
+
|
| 195 |
+
Similarly, Django provides :func:`django.utils.encoding.uri_to_iri()` which
|
| 196 |
+
implements the conversion from URI to IRI as per :rfc:`3987#section-3.2`.
|
| 197 |
+
|
| 198 |
+
An example to demonstrate:
|
| 199 |
+
|
| 200 |
+
.. code-block:: pycon
|
| 201 |
+
|
| 202 |
+
>>> from django.utils.encoding import uri_to_iri
|
| 203 |
+
>>> uri_to_iri("/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93")
|
| 204 |
+
'/♥♥/?utf8=✓'
|
| 205 |
+
>>> uri_to_iri("%A9hello%3Fworld")
|
| 206 |
+
'%A9hello%3Fworld'
|
| 207 |
+
|
| 208 |
+
In the first example, the UTF-8 characters are unquoted. In the second, the
|
| 209 |
+
percent-encodings remain unchanged because they lie outside the valid UTF-8
|
| 210 |
+
range or represent a reserved character.
|
| 211 |
+
|
| 212 |
+
Both ``iri_to_uri()`` and ``uri_to_iri()`` functions are idempotent, which means the
|
| 213 |
+
following is always true::
|
| 214 |
+
|
| 215 |
+
iri_to_uri(iri_to_uri(some_string)) == iri_to_uri(some_string)
|
| 216 |
+
uri_to_iri(uri_to_iri(some_string)) == uri_to_iri(some_string)
|
| 217 |
+
|
| 218 |
+
So you can safely call it multiple times on the same URI/IRI without risking
|
| 219 |
+
double-quoting problems.
|
| 220 |
+
|
| 221 |
+
Models
|
| 222 |
+
======
|
| 223 |
+
|
| 224 |
+
Because all strings are returned from the database as ``str`` objects, model
|
| 225 |
+
fields that are character based (CharField, TextField, URLField, etc.) will
|
| 226 |
+
contain Unicode values when Django retrieves data from the database. This
|
| 227 |
+
is *always* the case, even if the data could fit into an ASCII bytestring.
|
| 228 |
+
|
| 229 |
+
You can pass in bytestrings when creating a model or populating a field, and
|
| 230 |
+
Django will convert it to strings when it needs to.
|
| 231 |
+
|
| 232 |
+
Taking care in ``get_absolute_url()``
|
| 233 |
+
-------------------------------------
|
| 234 |
+
|
| 235 |
+
URLs can only contain ASCII characters. If you're constructing a URL from
|
| 236 |
+
pieces of data that might be non-ASCII, be careful to encode the results in a
|
| 237 |
+
way that is suitable for a URL. The :func:`~django.urls.reverse` function
|
| 238 |
+
handles this for you automatically.
|
| 239 |
+
|
| 240 |
+
If you're constructing a URL manually (i.e., *not* using the ``reverse()``
|
| 241 |
+
function), you'll need to take care of the encoding yourself. In this case,
|
| 242 |
+
use the ``iri_to_uri()`` and ``quote()`` functions that were documented
|
| 243 |
+
above_. For example::
|
| 244 |
+
|
| 245 |
+
from urllib.parse import quote
|
| 246 |
+
from django.utils.encoding import iri_to_uri
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def get_absolute_url(self):
|
| 250 |
+
url = "/person/%s/?x=0&y=0" % quote(self.location)
|
| 251 |
+
return iri_to_uri(url)
|
| 252 |
+
|
| 253 |
+
This function returns a correctly encoded URL even if ``self.location`` is
|
| 254 |
+
something like "Jack visited Paris & Orléans". (In fact, the ``iri_to_uri()``
|
| 255 |
+
call isn't strictly necessary in the above example, because all the
|
| 256 |
+
non-ASCII characters would have been removed in quoting in the first line.)
|
| 257 |
+
|
| 258 |
+
.. _above: `URI and IRI handling`_
|
| 259 |
+
|
| 260 |
+
Templates
|
| 261 |
+
=========
|
| 262 |
+
|
| 263 |
+
Use strings when creating templates manually::
|
| 264 |
+
|
| 265 |
+
from django.template import Template
|
| 266 |
+
|
| 267 |
+
t2 = Template("This is a string template.")
|
| 268 |
+
|
| 269 |
+
But the common case is to read templates from the filesystem. If your template
|
| 270 |
+
files are not stored with a UTF-8 encoding, adjust the :setting:`TEMPLATES`
|
| 271 |
+
setting. The built-in :py:mod:`~django.template.backends.django` backend
|
| 272 |
+
provides the ``'file_charset'`` option to change the encoding used to read
|
| 273 |
+
files from disk.
|
| 274 |
+
|
| 275 |
+
The :setting:`DEFAULT_CHARSET` setting controls the encoding of rendered templates.
|
| 276 |
+
This is set to UTF-8 by default.
|
| 277 |
+
|
| 278 |
+
Template tags and filters
|
| 279 |
+
-------------------------
|
| 280 |
+
|
| 281 |
+
A couple of tips to remember when writing your own template tags and filters:
|
| 282 |
+
|
| 283 |
+
* Always return strings from a template tag's ``render()`` method
|
| 284 |
+
and from template filters.
|
| 285 |
+
|
| 286 |
+
* Use ``force_str()`` in preference to ``smart_str()`` in these
|
| 287 |
+
places. Tag rendering and filter calls occur as the template is being
|
| 288 |
+
rendered, so there is no advantage to postponing the conversion of lazy
|
| 289 |
+
translation objects into strings. It's easier to work solely with
|
| 290 |
+
strings at that point.
|
| 291 |
+
|
| 292 |
+
.. _unicode-files:
|
| 293 |
+
|
| 294 |
+
Files
|
| 295 |
+
=====
|
| 296 |
+
|
| 297 |
+
If you intend to allow users to upload files, you must ensure that the
|
| 298 |
+
environment used to run Django is configured to work with non-ASCII file names.
|
| 299 |
+
If your environment isn't configured correctly, you'll encounter
|
| 300 |
+
``UnicodeEncodeError`` exceptions when saving files with file names or content
|
| 301 |
+
that contains non-ASCII characters.
|
| 302 |
+
|
| 303 |
+
Filesystem support for UTF-8 file names varies and might depend on the
|
| 304 |
+
environment. Check your current configuration in an interactive Python shell by
|
| 305 |
+
running::
|
| 306 |
+
|
| 307 |
+
import sys
|
| 308 |
+
|
| 309 |
+
sys.getfilesystemencoding()
|
| 310 |
+
|
| 311 |
+
This should output "UTF-8".
|
| 312 |
+
|
| 313 |
+
The ``LANG`` environment variable is responsible for setting the expected
|
| 314 |
+
encoding on Unix platforms. Consult the documentation for your operating system
|
| 315 |
+
and application server for the appropriate syntax and location to set this
|
| 316 |
+
variable. See the :doc:`/howto/deployment/wsgi/modwsgi` for examples.
|
| 317 |
+
|
| 318 |
+
In your development environment, you might need to add a setting to your
|
| 319 |
+
``~.bashrc`` analogous to:
|
| 320 |
+
|
| 321 |
+
.. code-block:: shell
|
| 322 |
+
|
| 323 |
+
export LANG="en_US.UTF-8"
|
| 324 |
+
|
| 325 |
+
Form submission
|
| 326 |
+
===============
|
| 327 |
+
|
| 328 |
+
HTML form submission is a tricky area. There's no guarantee that the
|
| 329 |
+
submission will include encoding information, which means the framework might
|
| 330 |
+
have to guess at the encoding of submitted data.
|
| 331 |
+
|
| 332 |
+
Django adopts a "lazy" approach to decoding form data. The data in an
|
| 333 |
+
``HttpRequest`` object is only decoded when you access it. In fact, most of
|
| 334 |
+
the data is not decoded at all. Only the ``HttpRequest.GET`` and
|
| 335 |
+
``HttpRequest.POST`` data structures have any decoding applied to them. Those
|
| 336 |
+
two fields will return their members as Unicode data. All other attributes and
|
| 337 |
+
methods of ``HttpRequest`` return data exactly as it was submitted by the
|
| 338 |
+
client.
|
| 339 |
+
|
| 340 |
+
By default, the :setting:`DEFAULT_CHARSET` setting is used as the assumed encoding
|
| 341 |
+
for form data. If you need to change this for a particular form, you can set
|
| 342 |
+
the ``encoding`` attribute on an ``HttpRequest`` instance. For example::
|
| 343 |
+
|
| 344 |
+
def some_view(request):
|
| 345 |
+
# We know that the data must be encoded as KOI8-R (for some reason).
|
| 346 |
+
request.encoding = "koi8-r"
|
| 347 |
+
...
|
| 348 |
+
|
| 349 |
+
You can even change the encoding after having accessed ``request.GET`` or
|
| 350 |
+
``request.POST``, and all subsequent accesses will use the new encoding.
|
| 351 |
+
|
| 352 |
+
Most developers won't need to worry about changing form encoding, but this is
|
| 353 |
+
a useful feature for applications that talk to legacy systems whose encoding
|
| 354 |
+
you cannot control.
|
| 355 |
+
|
| 356 |
+
Django does not decode the data of file uploads, because that data is normally
|
| 357 |
+
treated as collections of bytes, rather than strings. Any automatic decoding
|
| 358 |
+
there would alter the meaning of the stream of bytes.
|
testbed/django__django/docs/ref/urlresolvers.txt
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=================================
|
| 2 |
+
``django.urls`` utility functions
|
| 3 |
+
=================================
|
| 4 |
+
|
| 5 |
+
.. module:: django.urls
|
| 6 |
+
|
| 7 |
+
``reverse()``
|
| 8 |
+
=============
|
| 9 |
+
|
| 10 |
+
If you need to use something similar to the :ttag:`url` template tag in
|
| 11 |
+
your code, Django provides the following function:
|
| 12 |
+
|
| 13 |
+
.. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
|
| 14 |
+
|
| 15 |
+
``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or the
|
| 16 |
+
callable view object. For example, given the following ``url``::
|
| 17 |
+
|
| 18 |
+
from news import views
|
| 19 |
+
|
| 20 |
+
path("archive/", views.archive, name="news-archive")
|
| 21 |
+
|
| 22 |
+
you can use any of the following to reverse the URL::
|
| 23 |
+
|
| 24 |
+
# using the named URL
|
| 25 |
+
reverse("news-archive")
|
| 26 |
+
|
| 27 |
+
# passing a callable object
|
| 28 |
+
# (This is discouraged because you can't reverse namespaced views this way.)
|
| 29 |
+
from news import views
|
| 30 |
+
|
| 31 |
+
reverse(views.archive)
|
| 32 |
+
|
| 33 |
+
If the URL accepts arguments, you may pass them in ``args``. For example::
|
| 34 |
+
|
| 35 |
+
from django.urls import reverse
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def myview(request):
|
| 39 |
+
return HttpResponseRedirect(reverse("arch-summary", args=[1945]))
|
| 40 |
+
|
| 41 |
+
You can also pass ``kwargs`` instead of ``args``. For example:
|
| 42 |
+
|
| 43 |
+
.. code-block:: pycon
|
| 44 |
+
|
| 45 |
+
>>> reverse("admin:app_list", kwargs={"app_label": "auth"})
|
| 46 |
+
'/admin/auth/'
|
| 47 |
+
|
| 48 |
+
``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
|
| 49 |
+
|
| 50 |
+
If no match can be made, ``reverse()`` raises a
|
| 51 |
+
:class:`~django.urls.NoReverseMatch` exception.
|
| 52 |
+
|
| 53 |
+
The ``reverse()`` function can reverse a large variety of regular expression
|
| 54 |
+
patterns for URLs, but not every possible one. The main restriction at the
|
| 55 |
+
moment is that the pattern cannot contain alternative choices using the
|
| 56 |
+
vertical bar (``"|"``) character. You can quite happily use such patterns for
|
| 57 |
+
matching against incoming URLs and sending them off to views, but you cannot
|
| 58 |
+
reverse such patterns.
|
| 59 |
+
|
| 60 |
+
The ``current_app`` argument allows you to provide a hint to the resolver
|
| 61 |
+
indicating the application to which the currently executing view belongs.
|
| 62 |
+
This ``current_app`` argument is used as a hint to resolve application
|
| 63 |
+
namespaces into URLs on specific application instances, according to the
|
| 64 |
+
:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
|
| 65 |
+
|
| 66 |
+
The ``urlconf`` argument is the URLconf module containing the URL patterns to
|
| 67 |
+
use for reversing. By default, the root URLconf for the current thread is used.
|
| 68 |
+
|
| 69 |
+
.. note::
|
| 70 |
+
|
| 71 |
+
The string returned by ``reverse()`` is already
|
| 72 |
+
:ref:`urlquoted <uri-and-iri-handling>`. For example:
|
| 73 |
+
|
| 74 |
+
.. code-block:: pycon
|
| 75 |
+
|
| 76 |
+
>>> reverse("cities", args=["Orléans"])
|
| 77 |
+
'.../Orl%C3%A9ans/'
|
| 78 |
+
|
| 79 |
+
Applying further encoding (such as :func:`urllib.parse.quote`) to the output
|
| 80 |
+
of ``reverse()`` may produce undesirable results.
|
| 81 |
+
|
| 82 |
+
``reverse_lazy()``
|
| 83 |
+
==================
|
| 84 |
+
|
| 85 |
+
A lazily evaluated version of `reverse()`_.
|
| 86 |
+
|
| 87 |
+
.. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
|
| 88 |
+
|
| 89 |
+
It is useful for when you need to use a URL reversal before your project's
|
| 90 |
+
URLConf is loaded. Some common cases where this function is necessary are:
|
| 91 |
+
|
| 92 |
+
* providing a reversed URL as the ``url`` attribute of a generic class-based
|
| 93 |
+
view.
|
| 94 |
+
|
| 95 |
+
* providing a reversed URL to a decorator (such as the ``login_url`` argument
|
| 96 |
+
for the :func:`django.contrib.auth.decorators.permission_required`
|
| 97 |
+
decorator).
|
| 98 |
+
|
| 99 |
+
* providing a reversed URL as a default value for a parameter in a function's
|
| 100 |
+
signature.
|
| 101 |
+
|
| 102 |
+
``resolve()``
|
| 103 |
+
=============
|
| 104 |
+
|
| 105 |
+
The ``resolve()`` function can be used for resolving URL paths to the
|
| 106 |
+
corresponding view functions. It has the following signature:
|
| 107 |
+
|
| 108 |
+
.. function:: resolve(path, urlconf=None)
|
| 109 |
+
|
| 110 |
+
``path`` is the URL path you want to resolve. As with
|
| 111 |
+
:func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``
|
| 112 |
+
parameter. The function returns a :class:`ResolverMatch` object that allows you
|
| 113 |
+
to access various metadata about the resolved URL.
|
| 114 |
+
|
| 115 |
+
If the URL does not resolve, the function raises a
|
| 116 |
+
:exc:`~django.urls.Resolver404` exception (a subclass of
|
| 117 |
+
:class:`~django.http.Http404`) .
|
| 118 |
+
|
| 119 |
+
.. class:: ResolverMatch
|
| 120 |
+
|
| 121 |
+
.. attribute:: ResolverMatch.func
|
| 122 |
+
|
| 123 |
+
The view function that would be used to serve the URL
|
| 124 |
+
|
| 125 |
+
.. attribute:: ResolverMatch.args
|
| 126 |
+
|
| 127 |
+
The arguments that would be passed to the view function, as
|
| 128 |
+
parsed from the URL.
|
| 129 |
+
|
| 130 |
+
.. attribute:: ResolverMatch.kwargs
|
| 131 |
+
|
| 132 |
+
All keyword arguments that would be passed to the view function, i.e.
|
| 133 |
+
:attr:`~ResolverMatch.captured_kwargs` and
|
| 134 |
+
:attr:`~ResolverMatch.extra_kwargs`.
|
| 135 |
+
|
| 136 |
+
.. attribute:: ResolverMatch.captured_kwargs
|
| 137 |
+
|
| 138 |
+
The captured keyword arguments that would be passed to the view
|
| 139 |
+
function, as parsed from the URL.
|
| 140 |
+
|
| 141 |
+
.. attribute:: ResolverMatch.extra_kwargs
|
| 142 |
+
|
| 143 |
+
The additional keyword arguments that would be passed to the view
|
| 144 |
+
function.
|
| 145 |
+
|
| 146 |
+
.. attribute:: ResolverMatch.url_name
|
| 147 |
+
|
| 148 |
+
The name of the URL pattern that matches the URL.
|
| 149 |
+
|
| 150 |
+
.. attribute:: ResolverMatch.route
|
| 151 |
+
|
| 152 |
+
The route of the matching URL pattern.
|
| 153 |
+
|
| 154 |
+
For example, if ``path('users/<id>/', ...)`` is the matching pattern,
|
| 155 |
+
``route`` will contain ``'users/<id>/'``.
|
| 156 |
+
|
| 157 |
+
.. attribute:: ResolverMatch.tried
|
| 158 |
+
|
| 159 |
+
The list of URL patterns tried before the URL either matched one or
|
| 160 |
+
exhausted available patterns.
|
| 161 |
+
|
| 162 |
+
.. attribute:: ResolverMatch.app_name
|
| 163 |
+
|
| 164 |
+
The application namespace for the URL pattern that matches the
|
| 165 |
+
URL.
|
| 166 |
+
|
| 167 |
+
.. attribute:: ResolverMatch.app_names
|
| 168 |
+
|
| 169 |
+
The list of individual namespace components in the full
|
| 170 |
+
application namespace for the URL pattern that matches the URL.
|
| 171 |
+
For example, if the ``app_name`` is ``'foo:bar'``, then ``app_names``
|
| 172 |
+
will be ``['foo', 'bar']``.
|
| 173 |
+
|
| 174 |
+
.. attribute:: ResolverMatch.namespace
|
| 175 |
+
|
| 176 |
+
The instance namespace for the URL pattern that matches the
|
| 177 |
+
URL.
|
| 178 |
+
|
| 179 |
+
.. attribute:: ResolverMatch.namespaces
|
| 180 |
+
|
| 181 |
+
The list of individual namespace components in the full
|
| 182 |
+
instance namespace for the URL pattern that matches the URL.
|
| 183 |
+
i.e., if the namespace is ``foo:bar``, then namespaces will be
|
| 184 |
+
``['foo', 'bar']``.
|
| 185 |
+
|
| 186 |
+
.. attribute:: ResolverMatch.view_name
|
| 187 |
+
|
| 188 |
+
The name of the view that matches the URL, including the namespace if
|
| 189 |
+
there is one.
|
| 190 |
+
|
| 191 |
+
A :class:`ResolverMatch` object can then be interrogated to provide
|
| 192 |
+
information about the URL pattern that matches a URL::
|
| 193 |
+
|
| 194 |
+
# Resolve a URL
|
| 195 |
+
match = resolve("/some/path/")
|
| 196 |
+
# Print the URL pattern that matches the URL
|
| 197 |
+
print(match.url_name)
|
| 198 |
+
|
| 199 |
+
A :class:`ResolverMatch` object can also be assigned to a triple::
|
| 200 |
+
|
| 201 |
+
func, args, kwargs = resolve("/some/path/")
|
| 202 |
+
|
| 203 |
+
One possible use of :func:`~django.urls.resolve` would be to test whether a
|
| 204 |
+
view would raise a ``Http404`` error before redirecting to it::
|
| 205 |
+
|
| 206 |
+
from urllib.parse import urlparse
|
| 207 |
+
from django.urls import resolve
|
| 208 |
+
from django.http import Http404, HttpResponseRedirect
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def myview(request):
|
| 212 |
+
next = request.META.get("HTTP_REFERER", None) or "/"
|
| 213 |
+
response = HttpResponseRedirect(next)
|
| 214 |
+
|
| 215 |
+
# modify the request and response as required, e.g. change locale
|
| 216 |
+
# and set corresponding locale cookie
|
| 217 |
+
|
| 218 |
+
view, args, kwargs = resolve(urlparse(next)[2])
|
| 219 |
+
kwargs["request"] = request
|
| 220 |
+
try:
|
| 221 |
+
view(*args, **kwargs)
|
| 222 |
+
except Http404:
|
| 223 |
+
return HttpResponseRedirect("/")
|
| 224 |
+
return response
|
| 225 |
+
|
| 226 |
+
``get_script_prefix()``
|
| 227 |
+
=======================
|
| 228 |
+
|
| 229 |
+
.. function:: get_script_prefix()
|
| 230 |
+
|
| 231 |
+
Normally, you should always use :func:`~django.urls.reverse` to define URLs
|
| 232 |
+
within your application. However, if your application constructs part of the
|
| 233 |
+
URL hierarchy itself, you may occasionally need to generate URLs. In that
|
| 234 |
+
case, you need to be able to find the base URL of the Django project within
|
| 235 |
+
its web server (normally, :func:`~django.urls.reverse` takes care of this for
|
| 236 |
+
you). In that case, you can call ``get_script_prefix()``, which will return
|
| 237 |
+
the script prefix portion of the URL for your Django project. If your Django
|
| 238 |
+
project is at the root of its web server, this is always ``"/"``.
|
| 239 |
+
|
| 240 |
+
.. warning::
|
| 241 |
+
|
| 242 |
+
This function **cannot** be used outside of the request-response cycle
|
| 243 |
+
since it relies on values initialized during that cycle.
|
testbed/django__django/docs/ref/urls.txt
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=============================================
|
| 2 |
+
``django.urls`` functions for use in URLconfs
|
| 3 |
+
=============================================
|
| 4 |
+
|
| 5 |
+
.. module:: django.urls.conf
|
| 6 |
+
:synopsis: Functions for use in URLconfs.
|
| 7 |
+
|
| 8 |
+
.. currentmodule:: django.urls
|
| 9 |
+
|
| 10 |
+
``path()``
|
| 11 |
+
==========
|
| 12 |
+
|
| 13 |
+
.. function:: path(route, view, kwargs=None, name=None)
|
| 14 |
+
|
| 15 |
+
Returns an element for inclusion in ``urlpatterns``. For example::
|
| 16 |
+
|
| 17 |
+
from django.urls import include, path
|
| 18 |
+
|
| 19 |
+
urlpatterns = [
|
| 20 |
+
path("index/", views.index, name="main-view"),
|
| 21 |
+
path("bio/<username>/", views.bio, name="bio"),
|
| 22 |
+
path("articles/<slug:title>/", views.article, name="article-detail"),
|
| 23 |
+
path("articles/<slug:title>/<int:section>/", views.section, name="article-section"),
|
| 24 |
+
path("blog/", include("blog.urls")),
|
| 25 |
+
...,
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
The ``route`` argument should be a string or
|
| 29 |
+
:func:`~django.utils.translation.gettext_lazy()` (see
|
| 30 |
+
:ref:`translating-urlpatterns`) that contains a URL pattern. The string
|
| 31 |
+
may contain angle brackets (like ``<username>`` above) to capture part of the
|
| 32 |
+
URL and send it as a keyword argument to the view. The angle brackets may
|
| 33 |
+
include a converter specification (like the ``int`` part of ``<int:section>``)
|
| 34 |
+
which limits the characters matched and may also change the type of the
|
| 35 |
+
variable passed to the view. For example, ``<int:section>`` matches a string
|
| 36 |
+
of decimal digits and converts the value to an ``int``. See
|
| 37 |
+
:ref:`how-django-processes-a-request` for more details.
|
| 38 |
+
|
| 39 |
+
The ``view`` argument is a view function or the result of
|
| 40 |
+
:meth:`~django.views.generic.base.View.as_view` for class-based views. It can
|
| 41 |
+
also be an :func:`django.urls.include`.
|
| 42 |
+
|
| 43 |
+
The ``kwargs`` argument allows you to pass additional arguments to the view
|
| 44 |
+
function or method. See :ref:`views-extra-options` for an example.
|
| 45 |
+
|
| 46 |
+
See :ref:`Naming URL patterns <naming-url-patterns>` for why the ``name``
|
| 47 |
+
argument is useful.
|
| 48 |
+
|
| 49 |
+
``re_path()``
|
| 50 |
+
=============
|
| 51 |
+
|
| 52 |
+
.. function:: re_path(route, view, kwargs=None, name=None)
|
| 53 |
+
|
| 54 |
+
Returns an element for inclusion in ``urlpatterns``. For example::
|
| 55 |
+
|
| 56 |
+
from django.urls import include, re_path
|
| 57 |
+
|
| 58 |
+
urlpatterns = [
|
| 59 |
+
re_path(r"^index/$", views.index, name="index"),
|
| 60 |
+
re_path(r"^bio/(?P<username>\w+)/$", views.bio, name="bio"),
|
| 61 |
+
re_path(r"^blog/", include("blog.urls")),
|
| 62 |
+
...,
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
The ``route`` argument should be a string or
|
| 66 |
+
:func:`~django.utils.translation.gettext_lazy()` (see
|
| 67 |
+
:ref:`translating-urlpatterns`) that contains a regular expression compatible
|
| 68 |
+
with Python's :py:mod:`re` module. Strings typically use raw string syntax
|
| 69 |
+
(``r''``) so that they can contain sequences like ``\d`` without the need to
|
| 70 |
+
escape the backslash with another backslash. When a match is made, captured
|
| 71 |
+
groups from the regular expression are passed to the view -- as named arguments
|
| 72 |
+
if the groups are named, and as positional arguments otherwise. The values are
|
| 73 |
+
passed as strings, without any type conversion.
|
| 74 |
+
|
| 75 |
+
When a ``route`` ends with ``$`` the whole requested URL, matching against
|
| 76 |
+
:attr:`~django.http.HttpRequest.path_info`, must match the regular expression
|
| 77 |
+
pattern (:py:func:`re.fullmatch` is used).
|
| 78 |
+
|
| 79 |
+
The ``view``, ``kwargs`` and ``name`` arguments are the same as for
|
| 80 |
+
:func:`~django.urls.path()`.
|
| 81 |
+
|
| 82 |
+
.. versionchanged:: 2.2.25
|
| 83 |
+
|
| 84 |
+
In older versions, a full-match wasn't required for a ``route`` which ends
|
| 85 |
+
with ``$``.
|
| 86 |
+
|
| 87 |
+
``include()``
|
| 88 |
+
=============
|
| 89 |
+
|
| 90 |
+
.. function:: include(module, namespace=None)
|
| 91 |
+
include(pattern_list)
|
| 92 |
+
include((pattern_list, app_namespace), namespace=None)
|
| 93 |
+
|
| 94 |
+
A function that takes a full Python import path to another URLconf module
|
| 95 |
+
that should be "included" in this place. Optionally, the :term:`application
|
| 96 |
+
namespace` and :term:`instance namespace` where the entries will be included
|
| 97 |
+
into can also be specified.
|
| 98 |
+
|
| 99 |
+
Usually, the application namespace should be specified by the included
|
| 100 |
+
module. If an application namespace is set, the ``namespace`` argument
|
| 101 |
+
can be used to set a different instance namespace.
|
| 102 |
+
|
| 103 |
+
``include()`` also accepts as an argument either an iterable that returns
|
| 104 |
+
URL patterns or a 2-tuple containing such iterable plus the names of the
|
| 105 |
+
application namespaces.
|
| 106 |
+
|
| 107 |
+
:arg module: URLconf module (or module name)
|
| 108 |
+
:arg namespace: Instance namespace for the URL entries being included
|
| 109 |
+
:type namespace: str
|
| 110 |
+
:arg pattern_list: Iterable of :func:`~django.urls.path` and/or :func:`~django.urls.re_path` instances.
|
| 111 |
+
:arg app_namespace: Application namespace for the URL entries being included
|
| 112 |
+
:type app_namespace: str
|
| 113 |
+
|
| 114 |
+
See :ref:`including-other-urlconfs` and :ref:`namespaces-and-include`.
|
| 115 |
+
|
| 116 |
+
``register_converter()``
|
| 117 |
+
========================
|
| 118 |
+
|
| 119 |
+
.. function:: register_converter(converter, type_name)
|
| 120 |
+
|
| 121 |
+
The function for registering a converter for use in :func:`~django.urls.path()`
|
| 122 |
+
``route``\s.
|
| 123 |
+
|
| 124 |
+
The ``converter`` argument is a converter class, and ``type_name`` is the
|
| 125 |
+
converter name to use in path patterns. See
|
| 126 |
+
:ref:`registering-custom-path-converters` for an example.
|
| 127 |
+
|
| 128 |
+
==================================================
|
| 129 |
+
``django.conf.urls`` functions for use in URLconfs
|
| 130 |
+
==================================================
|
| 131 |
+
|
| 132 |
+
.. module:: django.conf.urls
|
| 133 |
+
|
| 134 |
+
``static()``
|
| 135 |
+
============
|
| 136 |
+
|
| 137 |
+
.. function:: static.static(prefix, view=django.views.static.serve, **kwargs)
|
| 138 |
+
|
| 139 |
+
Helper function to return a URL pattern for serving files in debug mode::
|
| 140 |
+
|
| 141 |
+
from django.conf import settings
|
| 142 |
+
from django.conf.urls.static import static
|
| 143 |
+
|
| 144 |
+
urlpatterns = [
|
| 145 |
+
# ... the rest of your URLconf goes here ...
|
| 146 |
+
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
| 147 |
+
|
| 148 |
+
``handler400``
|
| 149 |
+
==============
|
| 150 |
+
|
| 151 |
+
.. data:: handler400
|
| 152 |
+
|
| 153 |
+
A callable, or a string representing the full Python import path to the view
|
| 154 |
+
that should be called if the HTTP client has sent a request that caused an error
|
| 155 |
+
condition and a response with a status code of 400.
|
| 156 |
+
|
| 157 |
+
By default, this is :func:`django.views.defaults.bad_request`. If you
|
| 158 |
+
implement a custom view, be sure it accepts ``request`` and ``exception``
|
| 159 |
+
arguments and returns an :class:`~django.http.HttpResponseBadRequest`.
|
| 160 |
+
|
| 161 |
+
``handler403``
|
| 162 |
+
==============
|
| 163 |
+
|
| 164 |
+
.. data:: handler403
|
| 165 |
+
|
| 166 |
+
A callable, or a string representing the full Python import path to the view
|
| 167 |
+
that should be called if the user doesn't have the permissions required to
|
| 168 |
+
access a resource.
|
| 169 |
+
|
| 170 |
+
By default, this is :func:`django.views.defaults.permission_denied`. If you
|
| 171 |
+
implement a custom view, be sure it accepts ``request`` and ``exception``
|
| 172 |
+
arguments and returns an :class:`~django.http.HttpResponseForbidden`.
|
| 173 |
+
|
| 174 |
+
``handler404``
|
| 175 |
+
==============
|
| 176 |
+
|
| 177 |
+
.. data:: handler404
|
| 178 |
+
|
| 179 |
+
A callable, or a string representing the full Python import path to the view
|
| 180 |
+
that should be called if none of the URL patterns match.
|
| 181 |
+
|
| 182 |
+
By default, this is :func:`django.views.defaults.page_not_found`. If you
|
| 183 |
+
implement a custom view, be sure it accepts ``request`` and ``exception``
|
| 184 |
+
arguments and returns an :class:`~django.http.HttpResponseNotFound`.
|
| 185 |
+
|
| 186 |
+
``handler500``
|
| 187 |
+
==============
|
| 188 |
+
|
| 189 |
+
.. data:: handler500
|
| 190 |
+
|
| 191 |
+
A callable, or a string representing the full Python import path to the view
|
| 192 |
+
that should be called in case of server errors. Server errors happen when you
|
| 193 |
+
have runtime errors in view code.
|
| 194 |
+
|
| 195 |
+
By default, this is :func:`django.views.defaults.server_error`. If you
|
| 196 |
+
implement a custom view, be sure it accepts a ``request`` argument and returns
|
| 197 |
+
an :class:`~django.http.HttpResponseServerError`.
|
testbed/django__django/docs/ref/utils.txt
ADDED
|
@@ -0,0 +1,1136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============
|
| 2 |
+
Django Utils
|
| 3 |
+
============
|
| 4 |
+
|
| 5 |
+
.. module:: django.utils
|
| 6 |
+
:synopsis: Django's built-in utilities.
|
| 7 |
+
|
| 8 |
+
This document covers all stable modules in ``django.utils``. Most of the
|
| 9 |
+
modules in ``django.utils`` are designed for internal use and only the
|
| 10 |
+
following parts can be considered stable and thus backwards compatible as per
|
| 11 |
+
the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`.
|
| 12 |
+
|
| 13 |
+
``django.utils.cache``
|
| 14 |
+
======================
|
| 15 |
+
|
| 16 |
+
.. module:: django.utils.cache
|
| 17 |
+
:synopsis: Helper functions for controlling caching.
|
| 18 |
+
|
| 19 |
+
This module contains helper functions for controlling HTTP caching. It does so
|
| 20 |
+
by managing the ``Vary`` header of responses. It includes functions to patch
|
| 21 |
+
the header of response objects directly and decorators that change functions to
|
| 22 |
+
do that header-patching themselves.
|
| 23 |
+
|
| 24 |
+
For information on the ``Vary`` header, see :rfc:`9110#section-12.5.5`.
|
| 25 |
+
|
| 26 |
+
Essentially, the ``Vary`` HTTP header defines which headers a cache should take
|
| 27 |
+
into account when building its cache key. Requests with the same path but
|
| 28 |
+
different header content for headers named in ``Vary`` need to get different
|
| 29 |
+
cache keys to prevent delivery of wrong content.
|
| 30 |
+
|
| 31 |
+
For example, :doc:`internationalization </topics/i18n/index>` middleware would
|
| 32 |
+
need to distinguish caches by the ``Accept-language`` header.
|
| 33 |
+
|
| 34 |
+
.. function:: patch_cache_control(response, **kwargs)
|
| 35 |
+
|
| 36 |
+
This function patches the ``Cache-Control`` header by adding all keyword
|
| 37 |
+
arguments to it. The transformation is as follows:
|
| 38 |
+
|
| 39 |
+
* All keyword parameter names are turned to lowercase, and underscores
|
| 40 |
+
are converted to hyphens.
|
| 41 |
+
* If the value of a parameter is ``True`` (exactly ``True``, not just a
|
| 42 |
+
true value), only the parameter name is added to the header.
|
| 43 |
+
* All other parameters are added with their value, after applying
|
| 44 |
+
``str()`` to it.
|
| 45 |
+
|
| 46 |
+
.. function:: get_max_age(response)
|
| 47 |
+
|
| 48 |
+
Returns the max-age from the response Cache-Control header as an integer
|
| 49 |
+
(or ``None`` if it wasn't found or wasn't an integer).
|
| 50 |
+
|
| 51 |
+
.. function:: patch_response_headers(response, cache_timeout=None)
|
| 52 |
+
|
| 53 |
+
Adds some useful headers to the given ``HttpResponse`` object:
|
| 54 |
+
|
| 55 |
+
* ``Expires``
|
| 56 |
+
* ``Cache-Control``
|
| 57 |
+
|
| 58 |
+
Each header is only added if it isn't already set.
|
| 59 |
+
|
| 60 |
+
``cache_timeout`` is in seconds. The :setting:`CACHE_MIDDLEWARE_SECONDS`
|
| 61 |
+
setting is used by default.
|
| 62 |
+
|
| 63 |
+
.. function:: add_never_cache_headers(response)
|
| 64 |
+
|
| 65 |
+
Adds an ``Expires`` header to the current date/time.
|
| 66 |
+
|
| 67 |
+
Adds a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate,
|
| 68 |
+
private`` header to a response to indicate that a page should never be
|
| 69 |
+
cached.
|
| 70 |
+
|
| 71 |
+
Each header is only added if it isn't already set.
|
| 72 |
+
|
| 73 |
+
.. function:: patch_vary_headers(response, newheaders)
|
| 74 |
+
|
| 75 |
+
Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
|
| 76 |
+
``newheaders`` is a list of header names that should be in ``Vary``. If
|
| 77 |
+
headers contains an asterisk, then ``Vary`` header will consist of a single
|
| 78 |
+
asterisk ``'*'``, according to :rfc:`9110#section-12.5.5`. Otherwise,
|
| 79 |
+
existing headers in ``Vary`` aren't removed.
|
| 80 |
+
|
| 81 |
+
.. function:: get_cache_key(request, key_prefix=None, method='GET', cache=None)
|
| 82 |
+
|
| 83 |
+
Returns a cache key based on the request path. It can be used in the
|
| 84 |
+
request phase because it pulls the list of headers to take into account
|
| 85 |
+
from the global path registry and uses those to build a cache key to
|
| 86 |
+
check against.
|
| 87 |
+
|
| 88 |
+
If there is no headerlist stored, the page needs to be rebuilt, so this
|
| 89 |
+
function returns ``None``.
|
| 90 |
+
|
| 91 |
+
.. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None)
|
| 92 |
+
|
| 93 |
+
Learns what headers to take into account for some request path from the
|
| 94 |
+
response object. It stores those headers in a global path registry so that
|
| 95 |
+
later access to that path will know what headers to take into account
|
| 96 |
+
without building the response object itself. The headers are named in
|
| 97 |
+
the ``Vary`` header of the response, but we want to prevent response
|
| 98 |
+
generation.
|
| 99 |
+
|
| 100 |
+
The list of headers to use for cache key generation is stored in the same
|
| 101 |
+
cache as the pages themselves. If the cache ages some data out of the
|
| 102 |
+
cache, this means that we have to build the response once to get at the
|
| 103 |
+
Vary header and so at the list of headers to use for the cache key.
|
| 104 |
+
|
| 105 |
+
``django.utils.dateparse``
|
| 106 |
+
==========================
|
| 107 |
+
|
| 108 |
+
.. module:: django.utils.dateparse
|
| 109 |
+
:synopsis: Functions to parse strings to datetime objects.
|
| 110 |
+
|
| 111 |
+
The functions defined in this module share the following properties:
|
| 112 |
+
|
| 113 |
+
- They accept strings in ISO 8601 date/time formats (or some close
|
| 114 |
+
alternatives) and return objects from the corresponding classes in Python's
|
| 115 |
+
:mod:`datetime` module.
|
| 116 |
+
- They raise :exc:`ValueError` if their input is well formatted but isn't a
|
| 117 |
+
valid date or time.
|
| 118 |
+
- They return ``None`` if it isn't well formatted at all.
|
| 119 |
+
- They accept up to picosecond resolution in input, but they truncate it to
|
| 120 |
+
microseconds, since that's what Python supports.
|
| 121 |
+
|
| 122 |
+
.. function:: parse_date(value)
|
| 123 |
+
|
| 124 |
+
Parses a string and returns a :class:`datetime.date`.
|
| 125 |
+
|
| 126 |
+
.. function:: parse_time(value)
|
| 127 |
+
|
| 128 |
+
Parses a string and returns a :class:`datetime.time`.
|
| 129 |
+
|
| 130 |
+
UTC offsets aren't supported; if ``value`` describes one, the result is
|
| 131 |
+
``None``.
|
| 132 |
+
|
| 133 |
+
.. function:: parse_datetime(value)
|
| 134 |
+
|
| 135 |
+
Parses a string and returns a :class:`datetime.datetime`.
|
| 136 |
+
|
| 137 |
+
UTC offsets are supported; if ``value`` describes one, the result's
|
| 138 |
+
``tzinfo`` attribute is a :class:`datetime.timezone` instance.
|
| 139 |
+
|
| 140 |
+
.. function:: parse_duration(value)
|
| 141 |
+
|
| 142 |
+
Parses a string and returns a :class:`datetime.timedelta`.
|
| 143 |
+
|
| 144 |
+
Expects data in the format ``"DD HH:MM:SS.uuuuuu"``,
|
| 145 |
+
``"DD HH:MM:SS,uuuuuu"``, or as specified by ISO 8601 (e.g.
|
| 146 |
+
``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``) or PostgreSQL's
|
| 147 |
+
day-time interval format (e.g. ``3 days 04:05:06``).
|
| 148 |
+
|
| 149 |
+
``django.utils.decorators``
|
| 150 |
+
===========================
|
| 151 |
+
|
| 152 |
+
.. module:: django.utils.decorators
|
| 153 |
+
:synopsis: Functions that help with creating decorators for views.
|
| 154 |
+
|
| 155 |
+
.. function:: method_decorator(decorator, name='')
|
| 156 |
+
|
| 157 |
+
Converts a function decorator into a method decorator. It can be used to
|
| 158 |
+
decorate methods or classes; in the latter case, ``name`` is the name
|
| 159 |
+
of the method to be decorated and is required.
|
| 160 |
+
|
| 161 |
+
``decorator`` may also be a list or tuple of functions. They are wrapped
|
| 162 |
+
in reverse order so that the call order is the order in which the functions
|
| 163 |
+
appear in the list/tuple.
|
| 164 |
+
|
| 165 |
+
See :ref:`decorating class based views <decorating-class-based-views>` for
|
| 166 |
+
example usage.
|
| 167 |
+
|
| 168 |
+
.. function:: decorator_from_middleware(middleware_class)
|
| 169 |
+
|
| 170 |
+
Given a middleware class, returns a view decorator. This lets you use
|
| 171 |
+
middleware functionality on a per-view basis. The middleware is created
|
| 172 |
+
with no params passed.
|
| 173 |
+
|
| 174 |
+
It assumes middleware that's compatible with the old style of Django 1.9
|
| 175 |
+
and earlier (having methods like ``process_request()``,
|
| 176 |
+
``process_exception()``, and ``process_response()``).
|
| 177 |
+
|
| 178 |
+
.. function:: decorator_from_middleware_with_args(middleware_class)
|
| 179 |
+
|
| 180 |
+
Like ``decorator_from_middleware``, but returns a function
|
| 181 |
+
that accepts the arguments to be passed to the middleware_class.
|
| 182 |
+
For example, the :func:`~django.views.decorators.cache.cache_page`
|
| 183 |
+
decorator is created from the ``CacheMiddleware`` like this::
|
| 184 |
+
|
| 185 |
+
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@cache_page(3600)
|
| 189 |
+
def my_view(request):
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
.. function:: sync_only_middleware(middleware)
|
| 193 |
+
|
| 194 |
+
Marks a middleware as :ref:`synchronous-only <async-middleware>`. (The
|
| 195 |
+
default in Django, but this allows you to future-proof if the default ever
|
| 196 |
+
changes in a future release.)
|
| 197 |
+
|
| 198 |
+
.. function:: async_only_middleware(middleware)
|
| 199 |
+
|
| 200 |
+
Marks a middleware as :ref:`asynchronous-only <async-middleware>`. Django
|
| 201 |
+
will wrap it in an asynchronous event loop when it is called from the WSGI
|
| 202 |
+
request path.
|
| 203 |
+
|
| 204 |
+
.. function:: sync_and_async_middleware(middleware)
|
| 205 |
+
|
| 206 |
+
Marks a middleware as :ref:`sync and async compatible <async-middleware>`,
|
| 207 |
+
this allows to avoid converting requests. You must implement detection of
|
| 208 |
+
the current request type to use this decorator. See :ref:`asynchronous
|
| 209 |
+
middleware documentation <async-middleware>` for details.
|
| 210 |
+
|
| 211 |
+
``django.utils.encoding``
|
| 212 |
+
=========================
|
| 213 |
+
|
| 214 |
+
.. module:: django.utils.encoding
|
| 215 |
+
:synopsis: A series of helper functions to manage character encoding.
|
| 216 |
+
|
| 217 |
+
.. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
|
| 218 |
+
|
| 219 |
+
Returns a ``str`` object representing arbitrary object ``s``. Treats
|
| 220 |
+
bytestrings using the ``encoding`` codec.
|
| 221 |
+
|
| 222 |
+
If ``strings_only`` is ``True``, don't convert (some) non-string-like
|
| 223 |
+
objects.
|
| 224 |
+
|
| 225 |
+
.. function:: is_protected_type(obj)
|
| 226 |
+
|
| 227 |
+
Determine if the object instance is of a protected type.
|
| 228 |
+
|
| 229 |
+
Objects of protected types are preserved as-is when passed to
|
| 230 |
+
``force_str(strings_only=True)``.
|
| 231 |
+
|
| 232 |
+
.. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
|
| 233 |
+
|
| 234 |
+
Similar to ``smart_str()``, except that lazy instances are resolved to
|
| 235 |
+
strings, rather than kept as lazy objects.
|
| 236 |
+
|
| 237 |
+
If ``strings_only`` is ``True``, don't convert (some) non-string-like
|
| 238 |
+
objects.
|
| 239 |
+
|
| 240 |
+
.. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
|
| 241 |
+
|
| 242 |
+
Returns a bytestring version of arbitrary object ``s``, encoded as
|
| 243 |
+
specified in ``encoding``.
|
| 244 |
+
|
| 245 |
+
If ``strings_only`` is ``True``, don't convert (some) non-string-like
|
| 246 |
+
objects.
|
| 247 |
+
|
| 248 |
+
.. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
|
| 249 |
+
|
| 250 |
+
Similar to ``smart_bytes``, except that lazy instances are resolved to
|
| 251 |
+
bytestrings, rather than kept as lazy objects.
|
| 252 |
+
|
| 253 |
+
If ``strings_only`` is ``True``, don't convert (some) non-string-like
|
| 254 |
+
objects.
|
| 255 |
+
|
| 256 |
+
.. function:: iri_to_uri(iri)
|
| 257 |
+
|
| 258 |
+
Convert an Internationalized Resource Identifier (IRI) portion to a URI
|
| 259 |
+
portion that is suitable for inclusion in a URL.
|
| 260 |
+
|
| 261 |
+
This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`, slightly
|
| 262 |
+
simplified since the input is assumed to be a string rather than an
|
| 263 |
+
arbitrary byte stream.
|
| 264 |
+
|
| 265 |
+
Takes an IRI (string or UTF-8 bytes) and returns a string containing the
|
| 266 |
+
encoded result.
|
| 267 |
+
|
| 268 |
+
.. function:: uri_to_iri(uri)
|
| 269 |
+
|
| 270 |
+
Converts a Uniform Resource Identifier into an Internationalized Resource
|
| 271 |
+
Identifier.
|
| 272 |
+
|
| 273 |
+
This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`.
|
| 274 |
+
|
| 275 |
+
Takes a URI in ASCII bytes and returns a string containing the encoded
|
| 276 |
+
result.
|
| 277 |
+
|
| 278 |
+
.. function:: filepath_to_uri(path)
|
| 279 |
+
|
| 280 |
+
Convert a file system path to a URI portion that is suitable for inclusion
|
| 281 |
+
in a URL. The path is assumed to be either UTF-8 bytes, string, or a
|
| 282 |
+
:class:`~pathlib.Path`.
|
| 283 |
+
|
| 284 |
+
This method will encode certain characters that would normally be
|
| 285 |
+
recognized as special characters for URIs. Note that this method does not
|
| 286 |
+
encode the ' character, as it is a valid character within URIs. See
|
| 287 |
+
``encodeURIComponent()`` JavaScript function for more details.
|
| 288 |
+
|
| 289 |
+
Returns an ASCII string containing the encoded result.
|
| 290 |
+
|
| 291 |
+
.. function:: escape_uri_path(path)
|
| 292 |
+
|
| 293 |
+
Escapes the unsafe characters from the path portion of a Uniform Resource
|
| 294 |
+
Identifier (URI).
|
| 295 |
+
|
| 296 |
+
``django.utils.feedgenerator``
|
| 297 |
+
==============================
|
| 298 |
+
|
| 299 |
+
.. module:: django.utils.feedgenerator
|
| 300 |
+
:synopsis: Syndication feed generation library -- used for generating RSS, etc.
|
| 301 |
+
|
| 302 |
+
Sample usage:
|
| 303 |
+
|
| 304 |
+
.. code-block:: pycon
|
| 305 |
+
|
| 306 |
+
>>> from django.utils import feedgenerator
|
| 307 |
+
>>> feed = feedgenerator.Rss201rev2Feed(
|
| 308 |
+
... title="Poynter E-Media Tidbits",
|
| 309 |
+
... link="http://www.poynter.org/column.asp?id=31",
|
| 310 |
+
... description="A group blog by the sharpest minds in online media/journalism/publishing.",
|
| 311 |
+
... language="en",
|
| 312 |
+
... )
|
| 313 |
+
>>> feed.add_item(
|
| 314 |
+
... title="Hello",
|
| 315 |
+
... link="http://www.holovaty.com/test/",
|
| 316 |
+
... description="Testing.",
|
| 317 |
+
... )
|
| 318 |
+
>>> with open("test.rss", "w") as fp:
|
| 319 |
+
... feed.write(fp, "utf-8")
|
| 320 |
+
...
|
| 321 |
+
|
| 322 |
+
For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
|
| 323 |
+
which is currently ``Rss201rev2Feed``
|
| 324 |
+
|
| 325 |
+
For definitions of the different versions of RSS, see:
|
| 326 |
+
https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
|
| 327 |
+
|
| 328 |
+
.. function:: get_tag_uri(url, date)
|
| 329 |
+
|
| 330 |
+
Creates a TagURI.
|
| 331 |
+
|
| 332 |
+
See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
|
| 333 |
+
|
| 334 |
+
``SyndicationFeed``
|
| 335 |
+
-------------------
|
| 336 |
+
|
| 337 |
+
.. class:: SyndicationFeed
|
| 338 |
+
|
| 339 |
+
Base class for all syndication feeds. Subclasses should provide
|
| 340 |
+
``write()``.
|
| 341 |
+
|
| 342 |
+
.. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)
|
| 343 |
+
|
| 344 |
+
Initialize the feed with the given dictionary of metadata, which applies
|
| 345 |
+
to the entire feed.
|
| 346 |
+
|
| 347 |
+
Any extra keyword arguments you pass to ``__init__`` will be stored in
|
| 348 |
+
``self.feed``.
|
| 349 |
+
|
| 350 |
+
All parameters should be strings, except ``categories``, which should
|
| 351 |
+
be a sequence of strings.
|
| 352 |
+
|
| 353 |
+
.. method:: add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)
|
| 354 |
+
|
| 355 |
+
Adds an item to the feed. All args are expected to be strings except
|
| 356 |
+
``pubdate`` and ``updateddate``, which are ``datetime.datetime``
|
| 357 |
+
objects, and ``enclosures``, which is a list of ``Enclosure`` instances.
|
| 358 |
+
|
| 359 |
+
.. method:: num_items()
|
| 360 |
+
|
| 361 |
+
.. method:: root_attributes()
|
| 362 |
+
|
| 363 |
+
Return extra attributes to place on the root (i.e. feed/channel)
|
| 364 |
+
element. Called from ``write()``.
|
| 365 |
+
|
| 366 |
+
.. method:: add_root_elements(handler)
|
| 367 |
+
|
| 368 |
+
Add elements in the root (i.e. feed/channel) element.
|
| 369 |
+
Called from ``write()``.
|
| 370 |
+
|
| 371 |
+
.. method:: item_attributes(item)
|
| 372 |
+
|
| 373 |
+
Return extra attributes to place on each item (i.e. item/entry)
|
| 374 |
+
element.
|
| 375 |
+
|
| 376 |
+
.. method:: add_item_elements(handler, item)
|
| 377 |
+
|
| 378 |
+
Add elements on each item (i.e. item/entry) element.
|
| 379 |
+
|
| 380 |
+
.. method:: write(outfile, encoding)
|
| 381 |
+
|
| 382 |
+
Outputs the feed in the given encoding to ``outfile``, which is a
|
| 383 |
+
file-like object. Subclasses should override this.
|
| 384 |
+
|
| 385 |
+
.. method:: writeString(encoding)
|
| 386 |
+
|
| 387 |
+
Returns the feed in the given encoding as a string.
|
| 388 |
+
|
| 389 |
+
.. method:: latest_post_date()
|
| 390 |
+
|
| 391 |
+
Returns the latest ``pubdate`` or ``updateddate`` for all items in the
|
| 392 |
+
feed. If no items have either of these attributes this returns the
|
| 393 |
+
current UTC date/time.
|
| 394 |
+
|
| 395 |
+
``Enclosure``
|
| 396 |
+
-------------
|
| 397 |
+
|
| 398 |
+
.. class:: Enclosure
|
| 399 |
+
|
| 400 |
+
Represents an RSS enclosure
|
| 401 |
+
|
| 402 |
+
``RssFeed``
|
| 403 |
+
-----------
|
| 404 |
+
|
| 405 |
+
.. class:: RssFeed(SyndicationFeed)
|
| 406 |
+
|
| 407 |
+
``Rss201rev2Feed``
|
| 408 |
+
------------------
|
| 409 |
+
|
| 410 |
+
.. class:: Rss201rev2Feed(RssFeed)
|
| 411 |
+
|
| 412 |
+
Spec: https://cyber.harvard.edu/rss/rss.html
|
| 413 |
+
|
| 414 |
+
``RssUserland091Feed``
|
| 415 |
+
----------------------
|
| 416 |
+
|
| 417 |
+
.. class:: RssUserland091Feed(RssFeed)
|
| 418 |
+
|
| 419 |
+
Spec: http://backend.userland.com/rss091
|
| 420 |
+
|
| 421 |
+
``Atom1Feed``
|
| 422 |
+
-------------
|
| 423 |
+
|
| 424 |
+
.. class:: Atom1Feed(SyndicationFeed)
|
| 425 |
+
|
| 426 |
+
Spec: :rfc:`4287`
|
| 427 |
+
|
| 428 |
+
``django.utils.functional``
|
| 429 |
+
===========================
|
| 430 |
+
|
| 431 |
+
.. module:: django.utils.functional
|
| 432 |
+
:synopsis: Functional programming tools.
|
| 433 |
+
|
| 434 |
+
.. class:: cached_property(func)
|
| 435 |
+
|
| 436 |
+
The ``@cached_property`` decorator caches the result of a method with a
|
| 437 |
+
single ``self`` argument as a property. The cached result will persist
|
| 438 |
+
as long as the instance does, so if the instance is passed around and the
|
| 439 |
+
function subsequently invoked, the cached result will be returned.
|
| 440 |
+
|
| 441 |
+
Consider a typical case, where a view might need to call a model's method
|
| 442 |
+
to perform some computation, before placing the model instance into the
|
| 443 |
+
context, where the template might invoke the method once more::
|
| 444 |
+
|
| 445 |
+
# the model
|
| 446 |
+
class Person(models.Model):
|
| 447 |
+
def friends(self):
|
| 448 |
+
# expensive computation
|
| 449 |
+
...
|
| 450 |
+
return friends
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
# in the view:
|
| 454 |
+
if person.friends():
|
| 455 |
+
...
|
| 456 |
+
|
| 457 |
+
And in the template you would have:
|
| 458 |
+
|
| 459 |
+
.. code-block:: html+django
|
| 460 |
+
|
| 461 |
+
{% for friend in person.friends %}
|
| 462 |
+
|
| 463 |
+
Here, ``friends()`` will be called twice. Since the instance ``person`` in
|
| 464 |
+
the view and the template are the same, decorating the ``friends()`` method
|
| 465 |
+
with ``@cached_property`` can avoid that::
|
| 466 |
+
|
| 467 |
+
from django.utils.functional import cached_property
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class Person(models.Model):
|
| 471 |
+
@cached_property
|
| 472 |
+
def friends(self):
|
| 473 |
+
...
|
| 474 |
+
|
| 475 |
+
Note that as the method is now a property, in Python code it will need to
|
| 476 |
+
be accessed appropriately::
|
| 477 |
+
|
| 478 |
+
# in the view:
|
| 479 |
+
if person.friends:
|
| 480 |
+
...
|
| 481 |
+
|
| 482 |
+
The cached value can be treated like an ordinary attribute of the instance::
|
| 483 |
+
|
| 484 |
+
# clear it, requiring re-computation next time it's called
|
| 485 |
+
del person.friends # or delattr(person, "friends")
|
| 486 |
+
|
| 487 |
+
# set a value manually, that will persist on the instance until cleared
|
| 488 |
+
person.friends = ["Huckleberry Finn", "Tom Sawyer"]
|
| 489 |
+
|
| 490 |
+
Because of the way the :py:ref:`descriptor protocol
|
| 491 |
+
<descriptor-invocation>` works, using ``del`` (or ``delattr``) on a
|
| 492 |
+
``cached_property`` that hasn't been accessed raises ``AttributeError``.
|
| 493 |
+
|
| 494 |
+
As well as offering potential performance advantages, ``@cached_property``
|
| 495 |
+
can ensure that an attribute's value does not change unexpectedly over the
|
| 496 |
+
life of an instance. This could occur with a method whose computation is
|
| 497 |
+
based on ``datetime.now()``, or if a change were saved to the database by
|
| 498 |
+
some other process in the brief interval between subsequent invocations of
|
| 499 |
+
a method on the same instance.
|
| 500 |
+
|
| 501 |
+
You can make cached properties of methods. For example, if you had an
|
| 502 |
+
expensive ``get_friends()`` method and wanted to allow calling it without
|
| 503 |
+
retrieving the cached value, you could write::
|
| 504 |
+
|
| 505 |
+
friends = cached_property(get_friends)
|
| 506 |
+
|
| 507 |
+
While ``person.get_friends()`` will recompute the friends on each call, the
|
| 508 |
+
value of the cached property will persist until you delete it as described
|
| 509 |
+
above::
|
| 510 |
+
|
| 511 |
+
x = person.friends # calls first time
|
| 512 |
+
y = person.get_friends() # calls again
|
| 513 |
+
z = person.friends # does not call
|
| 514 |
+
x is z # is True
|
| 515 |
+
|
| 516 |
+
.. class:: classproperty(method=None)
|
| 517 |
+
|
| 518 |
+
Similar to :py:func:`@classmethod <classmethod>`, the ``@classproperty``
|
| 519 |
+
decorator converts the result of a method with a single ``cls`` argument
|
| 520 |
+
into a property that can be accessed directly from the class.
|
| 521 |
+
|
| 522 |
+
.. function:: keep_lazy(func, *resultclasses)
|
| 523 |
+
|
| 524 |
+
Django offers many utility functions (particularly in ``django.utils``)
|
| 525 |
+
that take a string as their first argument and do something to that string.
|
| 526 |
+
These functions are used by template filters as well as directly in other
|
| 527 |
+
code.
|
| 528 |
+
|
| 529 |
+
If you write your own similar functions and deal with translations, you'll
|
| 530 |
+
face the problem of what to do when the first argument is a lazy
|
| 531 |
+
translation object. You don't want to convert it to a string immediately,
|
| 532 |
+
because you might be using this function outside of a view (and hence the
|
| 533 |
+
current thread's locale setting will not be correct).
|
| 534 |
+
|
| 535 |
+
For cases like this, use the ``django.utils.functional.keep_lazy()``
|
| 536 |
+
decorator. It modifies the function so that *if* it's called with a lazy
|
| 537 |
+
translation as one of its arguments, the function evaluation is delayed
|
| 538 |
+
until it needs to be converted to a string.
|
| 539 |
+
|
| 540 |
+
For example::
|
| 541 |
+
|
| 542 |
+
from django.utils.functional import keep_lazy, keep_lazy_text
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def fancy_utility_function(s, *args, **kwargs):
|
| 546 |
+
# Do some conversion on string 's'
|
| 547 |
+
...
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
fancy_utility_function = keep_lazy(str)(fancy_utility_function)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
# Or more succinctly:
|
| 554 |
+
@keep_lazy(str)
|
| 555 |
+
def fancy_utility_function(s, *args, **kwargs):
|
| 556 |
+
...
|
| 557 |
+
|
| 558 |
+
The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
|
| 559 |
+
specifying the type(s) that the original function can return. A common
|
| 560 |
+
use case is to have functions that return text. For these, you can pass the
|
| 561 |
+
``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator
|
| 562 |
+
described in the next section).
|
| 563 |
+
|
| 564 |
+
Using this decorator means you can write your function and assume that the
|
| 565 |
+
input is a proper string, then add support for lazy translation objects at
|
| 566 |
+
the end.
|
| 567 |
+
|
| 568 |
+
.. function:: keep_lazy_text(func)
|
| 569 |
+
|
| 570 |
+
A shortcut for ``keep_lazy(str)(func)``.
|
| 571 |
+
|
| 572 |
+
If you have a function that returns text and you want to be able to take
|
| 573 |
+
lazy arguments while delaying their evaluation, you can use this
|
| 574 |
+
decorator::
|
| 575 |
+
|
| 576 |
+
from django.utils.functional import keep_lazy, keep_lazy_text
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
# Our previous example was:
|
| 580 |
+
@keep_lazy(str)
|
| 581 |
+
def fancy_utility_function(s, *args, **kwargs):
|
| 582 |
+
...
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
# Which can be rewritten as:
|
| 586 |
+
@keep_lazy_text
|
| 587 |
+
def fancy_utility_function(s, *args, **kwargs):
|
| 588 |
+
...
|
| 589 |
+
|
| 590 |
+
``django.utils.html``
|
| 591 |
+
=====================
|
| 592 |
+
|
| 593 |
+
.. module:: django.utils.html
|
| 594 |
+
:synopsis: HTML helper functions
|
| 595 |
+
|
| 596 |
+
Usually you should build up HTML using Django's templates to make use of its
|
| 597 |
+
autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
|
| 598 |
+
where appropriate. This module provides some additional low level utilities for
|
| 599 |
+
escaping HTML.
|
| 600 |
+
|
| 601 |
+
.. function:: escape(text)
|
| 602 |
+
|
| 603 |
+
Returns the given text with ampersands, quotes and angle brackets encoded
|
| 604 |
+
for use in HTML. The input is first coerced to a string and the output has
|
| 605 |
+
:func:`~django.utils.safestring.mark_safe` applied.
|
| 606 |
+
|
| 607 |
+
.. function:: conditional_escape(text)
|
| 608 |
+
|
| 609 |
+
Similar to ``escape()``, except that it doesn't operate on preescaped
|
| 610 |
+
strings, so it will not double escape.
|
| 611 |
+
|
| 612 |
+
.. function:: format_html(format_string, *args, **kwargs)
|
| 613 |
+
|
| 614 |
+
This is similar to :meth:`str.format`, except that it is appropriate for
|
| 615 |
+
building up HTML fragments. The first argument ``format_string`` is not
|
| 616 |
+
escaped but all other args and kwargs are passed through
|
| 617 |
+
:func:`conditional_escape` before being passed to ``str.format()``.
|
| 618 |
+
Finally, the output has :func:`~django.utils.safestring.mark_safe` applied.
|
| 619 |
+
|
| 620 |
+
For the case of building up small HTML fragments, this function is to be
|
| 621 |
+
preferred over string interpolation using ``%`` or ``str.format()``
|
| 622 |
+
directly, because it applies escaping to all arguments - just like the
|
| 623 |
+
template system applies escaping by default.
|
| 624 |
+
|
| 625 |
+
So, instead of writing::
|
| 626 |
+
|
| 627 |
+
mark_safe(
|
| 628 |
+
"%s <b>%s</b> %s"
|
| 629 |
+
% (
|
| 630 |
+
some_html,
|
| 631 |
+
escape(some_text),
|
| 632 |
+
escape(some_other_text),
|
| 633 |
+
)
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
You should instead use::
|
| 637 |
+
|
| 638 |
+
format_html(
|
| 639 |
+
"{} <b>{}</b> {}",
|
| 640 |
+
mark_safe(some_html),
|
| 641 |
+
some_text,
|
| 642 |
+
some_other_text,
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
This has the advantage that you don't need to apply :func:`escape` to each
|
| 646 |
+
argument and risk a bug and an XSS vulnerability if you forget one.
|
| 647 |
+
|
| 648 |
+
Note that although this function uses ``str.format()`` to do the
|
| 649 |
+
interpolation, some of the formatting options provided by ``str.format()``
|
| 650 |
+
(e.g. number formatting) will not work, since all arguments are passed
|
| 651 |
+
through :func:`conditional_escape` which (ultimately) calls
|
| 652 |
+
:func:`~django.utils.encoding.force_str` on the values.
|
| 653 |
+
|
| 654 |
+
.. deprecated:: 5.0
|
| 655 |
+
|
| 656 |
+
Support for calling ``format_html()`` without passing args or kwargs is
|
| 657 |
+
deprecated.
|
| 658 |
+
|
| 659 |
+
.. function:: format_html_join(sep, format_string, args_generator)
|
| 660 |
+
|
| 661 |
+
A wrapper of :func:`format_html`, for the common case of a group of
|
| 662 |
+
arguments that need to be formatted using the same format string, and then
|
| 663 |
+
joined using ``sep``. ``sep`` is also passed through
|
| 664 |
+
:func:`conditional_escape`.
|
| 665 |
+
|
| 666 |
+
``args_generator`` should be an iterator that returns the sequence of
|
| 667 |
+
``args`` that will be passed to :func:`format_html`. For example::
|
| 668 |
+
|
| 669 |
+
format_html_join("\n", "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users))
|
| 670 |
+
|
| 671 |
+
.. function:: json_script(value, element_id=None, encoder=None)
|
| 672 |
+
|
| 673 |
+
Escapes all HTML/XML special characters with their Unicode escapes, so
|
| 674 |
+
value is safe for use with JavaScript. Also wraps the escaped JSON in a
|
| 675 |
+
``<script>`` tag. If the ``element_id`` parameter is not ``None``, the
|
| 676 |
+
``<script>`` tag is given the passed id. For example:
|
| 677 |
+
|
| 678 |
+
.. code-block:: pycon
|
| 679 |
+
|
| 680 |
+
>>> json_script({"hello": "world"}, element_id="hello-data")
|
| 681 |
+
'<script id="hello-data" type="application/json">{"hello": "world"}</script>'
|
| 682 |
+
|
| 683 |
+
The ``encoder``, which defaults to
|
| 684 |
+
:class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
|
| 685 |
+
serialize the data. See :ref:`JSON serialization
|
| 686 |
+
<serialization-formats-json>` for more details about this serializer.
|
| 687 |
+
|
| 688 |
+
.. versionchanged:: 4.2
|
| 689 |
+
|
| 690 |
+
The ``encoder`` argument was added.
|
| 691 |
+
|
| 692 |
+
.. function:: strip_tags(value)
|
| 693 |
+
|
| 694 |
+
Tries to remove anything that looks like an HTML tag from the string, that
|
| 695 |
+
is anything contained within ``<>``.
|
| 696 |
+
|
| 697 |
+
Absolutely NO guarantee is provided about the resulting string being
|
| 698 |
+
HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
|
| 699 |
+
escaping it first, for example with :func:`~django.utils.html.escape`.
|
| 700 |
+
|
| 701 |
+
For example::
|
| 702 |
+
|
| 703 |
+
strip_tags(value)
|
| 704 |
+
|
| 705 |
+
If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
|
| 706 |
+
the return value will be ``"Joel is a slug"``.
|
| 707 |
+
|
| 708 |
+
If you are looking for a more robust solution, consider using a third-party
|
| 709 |
+
HTML sanitizing tool.
|
| 710 |
+
|
| 711 |
+
.. function:: html_safe()
|
| 712 |
+
|
| 713 |
+
The ``__html__()`` method on a class helps non-Django templates detect
|
| 714 |
+
classes whose output doesn't require HTML escaping.
|
| 715 |
+
|
| 716 |
+
This decorator defines the ``__html__()`` method on the decorated class
|
| 717 |
+
by wrapping ``__str__()`` in :meth:`~django.utils.safestring.mark_safe`.
|
| 718 |
+
Ensure the ``__str__()`` method does indeed return text that doesn't
|
| 719 |
+
require HTML escaping.
|
| 720 |
+
|
| 721 |
+
``django.utils.http``
|
| 722 |
+
=====================
|
| 723 |
+
|
| 724 |
+
.. module:: django.utils.http
|
| 725 |
+
:synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
|
| 726 |
+
|
| 727 |
+
.. function:: urlencode(query, doseq=False)
|
| 728 |
+
|
| 729 |
+
A version of Python's :func:`urllib.parse.urlencode` function that can
|
| 730 |
+
operate on ``MultiValueDict`` and non-string values.
|
| 731 |
+
|
| 732 |
+
.. function:: http_date(epoch_seconds=None)
|
| 733 |
+
|
| 734 |
+
Formats the time to match the :rfc:`1123#section-5.2.14` date format as
|
| 735 |
+
specified by HTTP :rfc:`9110#section-5.6.7`.
|
| 736 |
+
|
| 737 |
+
Accepts a floating point number expressed in seconds since the epoch in
|
| 738 |
+
UTC--such as that outputted by ``time.time()``. If set to ``None``,
|
| 739 |
+
defaults to the current time.
|
| 740 |
+
|
| 741 |
+
Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
|
| 742 |
+
|
| 743 |
+
.. function:: content_disposition_header(as_attachment, filename)
|
| 744 |
+
|
| 745 |
+
.. versionadded:: 4.2
|
| 746 |
+
|
| 747 |
+
Constructs a ``Content-Disposition`` HTTP header value from the given
|
| 748 |
+
``filename`` as specified by :rfc:`6266`. Returns ``None`` if
|
| 749 |
+
``as_attachment`` is ``False`` and ``filename`` is ``None``, otherwise
|
| 750 |
+
returns a string suitable for the ``Content-Disposition`` HTTP header.
|
| 751 |
+
|
| 752 |
+
.. function:: base36_to_int(s)
|
| 753 |
+
|
| 754 |
+
Converts a base 36 string to an integer.
|
| 755 |
+
|
| 756 |
+
.. function:: int_to_base36(i)
|
| 757 |
+
|
| 758 |
+
Converts a positive integer to a base 36 string.
|
| 759 |
+
|
| 760 |
+
.. function:: urlsafe_base64_encode(s)
|
| 761 |
+
|
| 762 |
+
Encodes a bytestring to a base64 string for use in URLs, stripping any
|
| 763 |
+
trailing equal signs.
|
| 764 |
+
|
| 765 |
+
.. function:: urlsafe_base64_decode(s)
|
| 766 |
+
|
| 767 |
+
Decodes a base64 encoded string, adding back any trailing equal signs that
|
| 768 |
+
might have been stripped.
|
| 769 |
+
|
| 770 |
+
``django.utils.module_loading``
|
| 771 |
+
===============================
|
| 772 |
+
|
| 773 |
+
.. module:: django.utils.module_loading
|
| 774 |
+
:synopsis: Functions for working with Python modules.
|
| 775 |
+
|
| 776 |
+
Functions for working with Python modules.
|
| 777 |
+
|
| 778 |
+
.. function:: import_string(dotted_path)
|
| 779 |
+
|
| 780 |
+
Imports a dotted module path and returns the attribute/class designated by
|
| 781 |
+
the last name in the path. Raises ``ImportError`` if the import failed. For
|
| 782 |
+
example::
|
| 783 |
+
|
| 784 |
+
from django.utils.module_loading import import_string
|
| 785 |
+
|
| 786 |
+
ValidationError = import_string("django.core.exceptions.ValidationError")
|
| 787 |
+
|
| 788 |
+
is equivalent to::
|
| 789 |
+
|
| 790 |
+
from django.core.exceptions import ValidationError
|
| 791 |
+
|
| 792 |
+
``django.utils.safestring``
|
| 793 |
+
===========================
|
| 794 |
+
|
| 795 |
+
.. module:: django.utils.safestring
|
| 796 |
+
:synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
|
| 797 |
+
|
| 798 |
+
Functions and classes for working with "safe strings": strings that can be
|
| 799 |
+
displayed safely without further escaping in HTML. Marking something as a "safe
|
| 800 |
+
string" means that the producer of the string has already turned characters
|
| 801 |
+
that should not be interpreted by the HTML engine (e.g. '<') into the
|
| 802 |
+
appropriate entities.
|
| 803 |
+
|
| 804 |
+
.. class:: SafeString
|
| 805 |
+
|
| 806 |
+
A ``str`` subclass that has been specifically marked as "safe" (requires no
|
| 807 |
+
further escaping) for HTML output purposes.
|
| 808 |
+
|
| 809 |
+
.. function:: mark_safe(s)
|
| 810 |
+
|
| 811 |
+
Explicitly mark a string as safe for (HTML) output purposes. The returned
|
| 812 |
+
object can be used everywhere a string is appropriate.
|
| 813 |
+
|
| 814 |
+
Can be called multiple times on a single string.
|
| 815 |
+
|
| 816 |
+
Can also be used as a decorator.
|
| 817 |
+
|
| 818 |
+
For building up fragments of HTML, you should normally be using
|
| 819 |
+
:func:`django.utils.html.format_html` instead.
|
| 820 |
+
|
| 821 |
+
String marked safe will become unsafe again if modified. For example:
|
| 822 |
+
|
| 823 |
+
.. code-block:: pycon
|
| 824 |
+
|
| 825 |
+
>>> mystr = "<b>Hello World</b> "
|
| 826 |
+
>>> mystr = mark_safe(mystr)
|
| 827 |
+
>>> type(mystr)
|
| 828 |
+
<class 'django.utils.safestring.SafeString'>
|
| 829 |
+
|
| 830 |
+
>>> mystr = mystr.strip() # removing whitespace
|
| 831 |
+
>>> type(mystr)
|
| 832 |
+
<type 'str'>
|
| 833 |
+
|
| 834 |
+
``django.utils.text``
|
| 835 |
+
=====================
|
| 836 |
+
|
| 837 |
+
.. module:: django.utils.text
|
| 838 |
+
:synopsis: Text manipulation.
|
| 839 |
+
|
| 840 |
+
.. function:: format_lazy(format_string, *args, **kwargs)
|
| 841 |
+
|
| 842 |
+
A version of :meth:`str.format` for when ``format_string``, ``args``,
|
| 843 |
+
and/or ``kwargs`` contain lazy objects. The first argument is the string to
|
| 844 |
+
be formatted. For example::
|
| 845 |
+
|
| 846 |
+
from django.utils.text import format_lazy
|
| 847 |
+
from django.utils.translation import pgettext_lazy
|
| 848 |
+
|
| 849 |
+
urlpatterns = [
|
| 850 |
+
path(
|
| 851 |
+
format_lazy("{person}/<int:pk>/", person=pgettext_lazy("URL", "person")),
|
| 852 |
+
PersonDetailView.as_view(),
|
| 853 |
+
),
|
| 854 |
+
]
|
| 855 |
+
|
| 856 |
+
This example allows translators to translate part of the URL. If "person"
|
| 857 |
+
is translated to "persona", the regular expression will match
|
| 858 |
+
``persona/(?P<pk>\d+)/$``, e.g. ``persona/5/``.
|
| 859 |
+
|
| 860 |
+
.. function:: slugify(value, allow_unicode=False)
|
| 861 |
+
|
| 862 |
+
Converts a string to a URL slug by:
|
| 863 |
+
|
| 864 |
+
#. Converting to ASCII if ``allow_unicode`` is ``False`` (the default).
|
| 865 |
+
#. Converting to lowercase.
|
| 866 |
+
#. Removing characters that aren't alphanumerics, underscores, hyphens, or
|
| 867 |
+
whitespace.
|
| 868 |
+
#. Replacing any whitespace or repeated dashes with single dashes.
|
| 869 |
+
#. Removing leading and trailing whitespace, dashes, and underscores.
|
| 870 |
+
|
| 871 |
+
For example:
|
| 872 |
+
|
| 873 |
+
.. code-block:: pycon
|
| 874 |
+
|
| 875 |
+
>>> slugify(" Joel is a slug ")
|
| 876 |
+
'joel-is-a-slug'
|
| 877 |
+
|
| 878 |
+
If you want to allow Unicode characters, pass ``allow_unicode=True``. For
|
| 879 |
+
example:
|
| 880 |
+
|
| 881 |
+
.. code-block:: pycon
|
| 882 |
+
|
| 883 |
+
>>> slugify("你好 World", allow_unicode=True)
|
| 884 |
+
'你好-world'
|
| 885 |
+
|
| 886 |
+
.. _time-zone-selection-functions:
|
| 887 |
+
|
| 888 |
+
``django.utils.timezone``
|
| 889 |
+
=========================
|
| 890 |
+
|
| 891 |
+
.. module:: django.utils.timezone
|
| 892 |
+
:synopsis: Timezone support.
|
| 893 |
+
|
| 894 |
+
.. function:: get_fixed_timezone(offset)
|
| 895 |
+
|
| 896 |
+
Returns a :class:`~datetime.tzinfo` instance that represents a time zone
|
| 897 |
+
with a fixed offset from UTC.
|
| 898 |
+
|
| 899 |
+
``offset`` is a :class:`datetime.timedelta` or an integer number of
|
| 900 |
+
minutes. Use positive values for time zones east of UTC and negative
|
| 901 |
+
values for west of UTC.
|
| 902 |
+
|
| 903 |
+
.. function:: get_default_timezone()
|
| 904 |
+
|
| 905 |
+
Returns a :class:`~datetime.tzinfo` instance that represents the
|
| 906 |
+
:ref:`default time zone <default-current-time-zone>`.
|
| 907 |
+
|
| 908 |
+
.. function:: get_default_timezone_name()
|
| 909 |
+
|
| 910 |
+
Returns the name of the :ref:`default time zone
|
| 911 |
+
<default-current-time-zone>`.
|
| 912 |
+
|
| 913 |
+
.. function:: get_current_timezone()
|
| 914 |
+
|
| 915 |
+
Returns a :class:`~datetime.tzinfo` instance that represents the
|
| 916 |
+
:ref:`current time zone <default-current-time-zone>`.
|
| 917 |
+
|
| 918 |
+
.. function:: get_current_timezone_name()
|
| 919 |
+
|
| 920 |
+
Returns the name of the :ref:`current time zone
|
| 921 |
+
<default-current-time-zone>`.
|
| 922 |
+
|
| 923 |
+
.. function:: activate(timezone)
|
| 924 |
+
|
| 925 |
+
Sets the :ref:`current time zone <default-current-time-zone>`. The
|
| 926 |
+
``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
|
| 927 |
+
subclass or a time zone name.
|
| 928 |
+
|
| 929 |
+
.. function:: deactivate()
|
| 930 |
+
|
| 931 |
+
Unsets the :ref:`current time zone <default-current-time-zone>`.
|
| 932 |
+
|
| 933 |
+
.. function:: override(timezone)
|
| 934 |
+
|
| 935 |
+
This is a Python context manager that sets the :ref:`current time zone
|
| 936 |
+
<default-current-time-zone>` on entry with :func:`activate()`, and restores
|
| 937 |
+
the previously active time zone on exit. If the ``timezone`` argument is
|
| 938 |
+
``None``, the :ref:`current time zone <default-current-time-zone>` is unset
|
| 939 |
+
on entry with :func:`deactivate()` instead.
|
| 940 |
+
|
| 941 |
+
``override`` is also usable as a function decorator.
|
| 942 |
+
|
| 943 |
+
.. function:: localtime(value=None, timezone=None)
|
| 944 |
+
|
| 945 |
+
Converts an aware :class:`~datetime.datetime` to a different time zone,
|
| 946 |
+
by default the :ref:`current time zone <default-current-time-zone>`.
|
| 947 |
+
|
| 948 |
+
When ``value`` is omitted, it defaults to :func:`now`.
|
| 949 |
+
|
| 950 |
+
This function doesn't work on naive datetimes; use :func:`make_aware`
|
| 951 |
+
instead.
|
| 952 |
+
|
| 953 |
+
.. function:: localdate(value=None, timezone=None)
|
| 954 |
+
|
| 955 |
+
Uses :func:`localtime` to convert an aware :class:`~datetime.datetime` to a
|
| 956 |
+
:meth:`~datetime.datetime.date` in a different time zone, by default the
|
| 957 |
+
:ref:`current time zone <default-current-time-zone>`.
|
| 958 |
+
|
| 959 |
+
When ``value`` is omitted, it defaults to :func:`now`.
|
| 960 |
+
|
| 961 |
+
This function doesn't work on naive datetimes.
|
| 962 |
+
|
| 963 |
+
.. function:: now()
|
| 964 |
+
|
| 965 |
+
Returns a :class:`~datetime.datetime` that represents the
|
| 966 |
+
current point in time. Exactly what's returned depends on the value of
|
| 967 |
+
:setting:`USE_TZ`:
|
| 968 |
+
|
| 969 |
+
* If :setting:`USE_TZ` is ``False``, this will be a
|
| 970 |
+
:ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
|
| 971 |
+
without an associated timezone) that represents the current time
|
| 972 |
+
in the system's local timezone.
|
| 973 |
+
|
| 974 |
+
* If :setting:`USE_TZ` is ``True``, this will be an
|
| 975 |
+
:ref:`aware <naive_vs_aware_datetimes>` datetime representing the
|
| 976 |
+
current time in UTC. Note that :func:`now` will always return
|
| 977 |
+
times in UTC regardless of the value of :setting:`TIME_ZONE`;
|
| 978 |
+
you can use :func:`localtime` to get the time in the current time zone.
|
| 979 |
+
|
| 980 |
+
.. function:: is_aware(value)
|
| 981 |
+
|
| 982 |
+
Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
|
| 983 |
+
function assumes that ``value`` is a :class:`~datetime.datetime`.
|
| 984 |
+
|
| 985 |
+
.. function:: is_naive(value)
|
| 986 |
+
|
| 987 |
+
Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
|
| 988 |
+
function assumes that ``value`` is a :class:`~datetime.datetime`.
|
| 989 |
+
|
| 990 |
+
.. function:: make_aware(value, timezone=None)
|
| 991 |
+
|
| 992 |
+
Returns an aware :class:`~datetime.datetime` that represents the same
|
| 993 |
+
point in time as ``value`` in ``timezone``, ``value`` being a naive
|
| 994 |
+
:class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
|
| 995 |
+
defaults to the :ref:`current time zone <default-current-time-zone>`.
|
| 996 |
+
|
| 997 |
+
.. function:: make_naive(value, timezone=None)
|
| 998 |
+
|
| 999 |
+
Returns a naive :class:`~datetime.datetime` that represents in
|
| 1000 |
+
``timezone`` the same point in time as ``value``, ``value`` being an
|
| 1001 |
+
aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
|
| 1002 |
+
defaults to the :ref:`current time zone <default-current-time-zone>`.
|
| 1003 |
+
|
| 1004 |
+
``django.utils.translation``
|
| 1005 |
+
============================
|
| 1006 |
+
|
| 1007 |
+
.. module:: django.utils.translation
|
| 1008 |
+
:synopsis: Internationalization support.
|
| 1009 |
+
|
| 1010 |
+
For a complete discussion on the usage of the following see the
|
| 1011 |
+
:doc:`translation documentation </topics/i18n/translation>`.
|
| 1012 |
+
|
| 1013 |
+
.. function:: gettext(message)
|
| 1014 |
+
|
| 1015 |
+
Translates ``message`` and returns it as a string.
|
| 1016 |
+
|
| 1017 |
+
.. function:: pgettext(context, message)
|
| 1018 |
+
|
| 1019 |
+
Translates ``message`` given the ``context`` and returns it as a string.
|
| 1020 |
+
|
| 1021 |
+
For more information, see :ref:`contextual-markers`.
|
| 1022 |
+
|
| 1023 |
+
.. function:: gettext_lazy(message)
|
| 1024 |
+
.. function:: pgettext_lazy(context, message)
|
| 1025 |
+
|
| 1026 |
+
Same as the non-lazy versions above, but using lazy execution.
|
| 1027 |
+
|
| 1028 |
+
See :ref:`lazy translations documentation <lazy-translations>`.
|
| 1029 |
+
|
| 1030 |
+
.. function:: gettext_noop(message)
|
| 1031 |
+
|
| 1032 |
+
Marks strings for translation but doesn't translate them now. This can be
|
| 1033 |
+
used to store strings in global variables that should stay in the base
|
| 1034 |
+
language (because they might be used externally) and will be translated
|
| 1035 |
+
later.
|
| 1036 |
+
|
| 1037 |
+
.. function:: ngettext(singular, plural, number)
|
| 1038 |
+
|
| 1039 |
+
Translates ``singular`` and ``plural`` and returns the appropriate string
|
| 1040 |
+
based on ``number``.
|
| 1041 |
+
|
| 1042 |
+
.. function:: npgettext(context, singular, plural, number)
|
| 1043 |
+
|
| 1044 |
+
Translates ``singular`` and ``plural`` and returns the appropriate string
|
| 1045 |
+
based on ``number`` and the ``context``.
|
| 1046 |
+
|
| 1047 |
+
.. function:: ngettext_lazy(singular, plural, number)
|
| 1048 |
+
.. function:: npgettext_lazy(context, singular, plural, number)
|
| 1049 |
+
|
| 1050 |
+
Same as the non-lazy versions above, but using lazy execution.
|
| 1051 |
+
|
| 1052 |
+
See :ref:`lazy translations documentation <lazy-translations>`.
|
| 1053 |
+
|
| 1054 |
+
.. function:: activate(language)
|
| 1055 |
+
|
| 1056 |
+
Fetches the translation object for a given language and activates it as
|
| 1057 |
+
the current translation object for the current thread.
|
| 1058 |
+
|
| 1059 |
+
.. function:: deactivate()
|
| 1060 |
+
|
| 1061 |
+
Deactivates the currently active translation object so that further _ calls
|
| 1062 |
+
will resolve against the default translation object, again.
|
| 1063 |
+
|
| 1064 |
+
.. function:: deactivate_all()
|
| 1065 |
+
|
| 1066 |
+
Makes the active translation object a ``NullTranslations()`` instance.
|
| 1067 |
+
This is useful when we want delayed translations to appear as the original
|
| 1068 |
+
string for some reason.
|
| 1069 |
+
|
| 1070 |
+
.. function:: override(language, deactivate=False)
|
| 1071 |
+
|
| 1072 |
+
A Python context manager that uses
|
| 1073 |
+
:func:`django.utils.translation.activate` to fetch the translation object
|
| 1074 |
+
for a given language, activates it as the translation object for the
|
| 1075 |
+
current thread and reactivates the previous active language on exit.
|
| 1076 |
+
Optionally, it can deactivate the temporary translation on exit with
|
| 1077 |
+
:func:`django.utils.translation.deactivate` if the ``deactivate`` argument
|
| 1078 |
+
is ``True``. If you pass ``None`` as the language argument, a
|
| 1079 |
+
``NullTranslations()`` instance is activated within the context.
|
| 1080 |
+
|
| 1081 |
+
``override`` is also usable as a function decorator.
|
| 1082 |
+
|
| 1083 |
+
.. function:: check_for_language(lang_code)
|
| 1084 |
+
|
| 1085 |
+
Checks whether there is a global language file for the given language
|
| 1086 |
+
code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
|
| 1087 |
+
language is available.
|
| 1088 |
+
|
| 1089 |
+
.. function:: get_language()
|
| 1090 |
+
|
| 1091 |
+
Returns the currently selected language code. Returns ``None`` if
|
| 1092 |
+
translations are temporarily deactivated (by :func:`deactivate_all()` or
|
| 1093 |
+
when ``None`` is passed to :func:`override()`).
|
| 1094 |
+
|
| 1095 |
+
.. function:: get_language_bidi()
|
| 1096 |
+
|
| 1097 |
+
Returns selected language's BiDi layout:
|
| 1098 |
+
|
| 1099 |
+
* ``False`` = left-to-right layout
|
| 1100 |
+
* ``True`` = right-to-left layout
|
| 1101 |
+
|
| 1102 |
+
.. function:: get_language_from_request(request, check_path=False)
|
| 1103 |
+
|
| 1104 |
+
Analyzes the request to find what language the user wants the system to
|
| 1105 |
+
show. Only languages listed in settings.LANGUAGES are taken into account.
|
| 1106 |
+
If the user requests a sublanguage where we have a main language, we send
|
| 1107 |
+
out the main language.
|
| 1108 |
+
|
| 1109 |
+
If ``check_path`` is ``True``, the function first checks the requested URL
|
| 1110 |
+
for whether its path begins with a language code listed in the
|
| 1111 |
+
:setting:`LANGUAGES` setting.
|
| 1112 |
+
|
| 1113 |
+
.. function:: get_supported_language_variant(lang_code, strict=False)
|
| 1114 |
+
|
| 1115 |
+
Returns ``lang_code`` if it's in the :setting:`LANGUAGES` setting, possibly
|
| 1116 |
+
selecting a more generic variant. For example, ``'es'`` is returned if
|
| 1117 |
+
``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but
|
| 1118 |
+
``'es-ar'`` isn't.
|
| 1119 |
+
|
| 1120 |
+
If ``strict`` is ``False`` (the default), a country-specific variant may
|
| 1121 |
+
be returned when neither the language code nor its generic variant is found.
|
| 1122 |
+
For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's
|
| 1123 |
+
returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches
|
| 1124 |
+
aren't returned if ``strict=True``.
|
| 1125 |
+
|
| 1126 |
+
Raises :exc:`LookupError` if nothing is found.
|
| 1127 |
+
|
| 1128 |
+
.. function:: to_locale(language)
|
| 1129 |
+
|
| 1130 |
+
Turns a language name (en-us) into a locale name (en_US).
|
| 1131 |
+
|
| 1132 |
+
.. function:: templatize(src)
|
| 1133 |
+
|
| 1134 |
+
Turns a Django template into something that is understood by ``xgettext``.
|
| 1135 |
+
It does so by translating the Django translation tags into standard
|
| 1136 |
+
``gettext`` function invocations.
|
testbed/django__django/docs/ref/validators.txt
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
==========
|
| 2 |
+
Validators
|
| 3 |
+
==========
|
| 4 |
+
|
| 5 |
+
.. module:: django.core.validators
|
| 6 |
+
:synopsis: Validation utilities and base classes
|
| 7 |
+
|
| 8 |
+
Writing validators
|
| 9 |
+
==================
|
| 10 |
+
|
| 11 |
+
A validator is a callable that takes a value and raises a
|
| 12 |
+
:exc:`~django.core.exceptions.ValidationError` if it doesn't meet some
|
| 13 |
+
criteria. Validators can be useful for reusing validation logic between
|
| 14 |
+
different types of fields.
|
| 15 |
+
|
| 16 |
+
For example, here's a validator that only allows even numbers::
|
| 17 |
+
|
| 18 |
+
from django.core.exceptions import ValidationError
|
| 19 |
+
from django.utils.translation import gettext_lazy as _
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def validate_even(value):
|
| 23 |
+
if value % 2 != 0:
|
| 24 |
+
raise ValidationError(
|
| 25 |
+
_("%(value)s is not an even number"),
|
| 26 |
+
params={"value": value},
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
You can add this to a model field via the field's :attr:`~django.db.models.Field.validators`
|
| 30 |
+
argument::
|
| 31 |
+
|
| 32 |
+
from django.db import models
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class MyModel(models.Model):
|
| 36 |
+
even_field = models.IntegerField(validators=[validate_even])
|
| 37 |
+
|
| 38 |
+
Because values are converted to Python before validators are run, you can even
|
| 39 |
+
use the same validator with forms::
|
| 40 |
+
|
| 41 |
+
from django import forms
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class MyForm(forms.Form):
|
| 45 |
+
even_field = forms.IntegerField(validators=[validate_even])
|
| 46 |
+
|
| 47 |
+
You can also use a class with a ``__call__()`` method for more complex or
|
| 48 |
+
configurable validators. :class:`RegexValidator`, for example, uses this
|
| 49 |
+
technique. If a class-based validator is used in the
|
| 50 |
+
:attr:`~django.db.models.Field.validators` model field option, you should make
|
| 51 |
+
sure it is :ref:`serializable by the migration framework
|
| 52 |
+
<migration-serializing>` by adding :ref:`deconstruct()
|
| 53 |
+
<custom-deconstruct-method>` and ``__eq__()`` methods.
|
| 54 |
+
|
| 55 |
+
How validators are run
|
| 56 |
+
======================
|
| 57 |
+
|
| 58 |
+
See the :doc:`form validation </ref/forms/validation>` for more information on
|
| 59 |
+
how validators are run in forms, and :ref:`Validating objects
|
| 60 |
+
<validating-objects>` for how they're run in models. Note that validators will
|
| 61 |
+
not be run automatically when you save a model, but if you are using a
|
| 62 |
+
:class:`~django.forms.ModelForm`, it will run your validators on any fields
|
| 63 |
+
that are included in your form. See the
|
| 64 |
+
:doc:`ModelForm documentation </topics/forms/modelforms>` for information on
|
| 65 |
+
how model validation interacts with forms.
|
| 66 |
+
|
| 67 |
+
Built-in validators
|
| 68 |
+
===================
|
| 69 |
+
|
| 70 |
+
The :mod:`django.core.validators` module contains a collection of callable
|
| 71 |
+
validators for use with model and form fields. They're used internally but
|
| 72 |
+
are available for use with your own fields, too. They can be used in addition
|
| 73 |
+
to, or in lieu of custom ``field.clean()`` methods.
|
| 74 |
+
|
| 75 |
+
``RegexValidator``
|
| 76 |
+
------------------
|
| 77 |
+
|
| 78 |
+
.. class:: RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)
|
| 79 |
+
|
| 80 |
+
:param regex: If not ``None``, overrides :attr:`regex`. Can be a regular
|
| 81 |
+
expression string or a pre-compiled regular expression.
|
| 82 |
+
:param message: If not ``None``, overrides :attr:`.message`.
|
| 83 |
+
:param code: If not ``None``, overrides :attr:`code`.
|
| 84 |
+
:param inverse_match: If not ``None``, overrides :attr:`inverse_match`.
|
| 85 |
+
:param flags: If not ``None``, overrides :attr:`flags`. In that case,
|
| 86 |
+
:attr:`regex` must be a regular expression string, or
|
| 87 |
+
:exc:`TypeError` is raised.
|
| 88 |
+
|
| 89 |
+
A :class:`RegexValidator` searches the provided ``value`` for a given
|
| 90 |
+
regular expression with :func:`re.search`. By default, raises a
|
| 91 |
+
:exc:`~django.core.exceptions.ValidationError` with :attr:`message` and
|
| 92 |
+
:attr:`code` if a match **is not** found. Its behavior can be inverted by
|
| 93 |
+
setting :attr:`inverse_match` to ``True``, in which case the
|
| 94 |
+
:exc:`~django.core.exceptions.ValidationError` is raised when a match
|
| 95 |
+
**is** found.
|
| 96 |
+
|
| 97 |
+
.. attribute:: regex
|
| 98 |
+
|
| 99 |
+
The regular expression pattern to search for within the provided
|
| 100 |
+
``value``, using :func:`re.search`. This may be a string or a
|
| 101 |
+
pre-compiled regular expression created with :func:`re.compile`.
|
| 102 |
+
Defaults to the empty string, which will be found in every possible
|
| 103 |
+
``value``.
|
| 104 |
+
|
| 105 |
+
.. attribute:: message
|
| 106 |
+
|
| 107 |
+
The error message used by
|
| 108 |
+
:exc:`~django.core.exceptions.ValidationError` if validation fails.
|
| 109 |
+
Defaults to ``"Enter a valid value"``.
|
| 110 |
+
|
| 111 |
+
.. attribute:: code
|
| 112 |
+
|
| 113 |
+
The error code used by :exc:`~django.core.exceptions.ValidationError`
|
| 114 |
+
if validation fails. Defaults to ``"invalid"``.
|
| 115 |
+
|
| 116 |
+
.. attribute:: inverse_match
|
| 117 |
+
|
| 118 |
+
The match mode for :attr:`regex`. Defaults to ``False``.
|
| 119 |
+
|
| 120 |
+
.. attribute:: flags
|
| 121 |
+
|
| 122 |
+
The :ref:`regex flags <python:contents-of-module-re>` used when
|
| 123 |
+
compiling the regular expression string :attr:`regex`. If :attr:`regex`
|
| 124 |
+
is a pre-compiled regular expression, and :attr:`flags` is overridden,
|
| 125 |
+
:exc:`TypeError` is raised. Defaults to ``0``.
|
| 126 |
+
|
| 127 |
+
``EmailValidator``
|
| 128 |
+
------------------
|
| 129 |
+
|
| 130 |
+
.. class:: EmailValidator(message=None, code=None, allowlist=None)
|
| 131 |
+
|
| 132 |
+
:param message: If not ``None``, overrides :attr:`.message`.
|
| 133 |
+
:param code: If not ``None``, overrides :attr:`code`.
|
| 134 |
+
:param allowlist: If not ``None``, overrides :attr:`allowlist`.
|
| 135 |
+
|
| 136 |
+
An :class:`EmailValidator` ensures that a value looks like an email, and
|
| 137 |
+
raises a :exc:`~django.core.exceptions.ValidationError` with
|
| 138 |
+
:attr:`message` and :attr:`code` if it doesn't. Values longer than 320
|
| 139 |
+
characters are always considered invalid.
|
| 140 |
+
|
| 141 |
+
.. attribute:: message
|
| 142 |
+
|
| 143 |
+
The error message used by
|
| 144 |
+
:exc:`~django.core.exceptions.ValidationError` if validation fails.
|
| 145 |
+
Defaults to ``"Enter a valid email address"``.
|
| 146 |
+
|
| 147 |
+
.. attribute:: code
|
| 148 |
+
|
| 149 |
+
The error code used by :exc:`~django.core.exceptions.ValidationError`
|
| 150 |
+
if validation fails. Defaults to ``"invalid"``.
|
| 151 |
+
|
| 152 |
+
.. attribute:: allowlist
|
| 153 |
+
|
| 154 |
+
Allowlist of email domains. By default, a regular expression (the
|
| 155 |
+
``domain_regex`` attribute) is used to validate whatever appears after
|
| 156 |
+
the ``@`` sign. However, if that string appears in the ``allowlist``,
|
| 157 |
+
this validation is bypassed. If not provided, the default ``allowlist``
|
| 158 |
+
is ``['localhost']``. Other domains that don't contain a dot won't pass
|
| 159 |
+
validation, so you'd need to add them to the ``allowlist`` as
|
| 160 |
+
necessary.
|
| 161 |
+
|
| 162 |
+
.. versionchanged:: 3.2.20
|
| 163 |
+
|
| 164 |
+
In older versions, values longer than 320 characters could be
|
| 165 |
+
considered valid.
|
| 166 |
+
|
| 167 |
+
``URLValidator``
|
| 168 |
+
----------------
|
| 169 |
+
|
| 170 |
+
.. class:: URLValidator(schemes=None, regex=None, message=None, code=None)
|
| 171 |
+
|
| 172 |
+
A :class:`RegexValidator` subclass that ensures a value looks like a URL,
|
| 173 |
+
and raises an error code of ``'invalid'`` if it doesn't. Values longer than
|
| 174 |
+
:attr:`max_length` characters are always considered invalid.
|
| 175 |
+
|
| 176 |
+
Loopback addresses and reserved IP spaces are considered valid. Literal
|
| 177 |
+
IPv6 addresses (:rfc:`3986#section-3.2.2`) and Unicode domains are both
|
| 178 |
+
supported.
|
| 179 |
+
|
| 180 |
+
In addition to the optional arguments of its parent :class:`RegexValidator`
|
| 181 |
+
class, ``URLValidator`` accepts an extra optional attribute:
|
| 182 |
+
|
| 183 |
+
.. attribute:: schemes
|
| 184 |
+
|
| 185 |
+
URL/URI scheme list to validate against. If not provided, the default
|
| 186 |
+
list is ``['http', 'https', 'ftp', 'ftps']``. As a reference, the IANA
|
| 187 |
+
website provides a full list of `valid URI schemes`_.
|
| 188 |
+
|
| 189 |
+
.. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
|
| 190 |
+
|
| 191 |
+
.. attribute:: max_length
|
| 192 |
+
|
| 193 |
+
.. versionadded:: 3.2.20
|
| 194 |
+
|
| 195 |
+
The maximum length of values that could be considered valid. Defaults
|
| 196 |
+
to 2048 characters.
|
| 197 |
+
|
| 198 |
+
.. versionchanged:: 3.2.20
|
| 199 |
+
|
| 200 |
+
In older versions, values longer than 2048 characters could be
|
| 201 |
+
considered valid.
|
| 202 |
+
|
| 203 |
+
``validate_email``
|
| 204 |
+
------------------
|
| 205 |
+
|
| 206 |
+
.. data:: validate_email
|
| 207 |
+
|
| 208 |
+
An :class:`EmailValidator` instance without any customizations.
|
| 209 |
+
|
| 210 |
+
``validate_slug``
|
| 211 |
+
-----------------
|
| 212 |
+
|
| 213 |
+
.. data:: validate_slug
|
| 214 |
+
|
| 215 |
+
A :class:`RegexValidator` instance that ensures a value consists of only
|
| 216 |
+
letters, numbers, underscores or hyphens.
|
| 217 |
+
|
| 218 |
+
``validate_unicode_slug``
|
| 219 |
+
-------------------------
|
| 220 |
+
|
| 221 |
+
.. data:: validate_unicode_slug
|
| 222 |
+
|
| 223 |
+
A :class:`RegexValidator` instance that ensures a value consists of only
|
| 224 |
+
Unicode letters, numbers, underscores, or hyphens.
|
| 225 |
+
|
| 226 |
+
``validate_ipv4_address``
|
| 227 |
+
-------------------------
|
| 228 |
+
|
| 229 |
+
.. data:: validate_ipv4_address
|
| 230 |
+
|
| 231 |
+
A :class:`RegexValidator` instance that ensures a value looks like an IPv4
|
| 232 |
+
address.
|
| 233 |
+
|
| 234 |
+
``validate_ipv6_address``
|
| 235 |
+
-------------------------
|
| 236 |
+
|
| 237 |
+
.. data:: validate_ipv6_address
|
| 238 |
+
|
| 239 |
+
Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.
|
| 240 |
+
|
| 241 |
+
``validate_ipv46_address``
|
| 242 |
+
--------------------------
|
| 243 |
+
|
| 244 |
+
.. data:: validate_ipv46_address
|
| 245 |
+
|
| 246 |
+
Uses both ``validate_ipv4_address`` and ``validate_ipv6_address`` to
|
| 247 |
+
ensure a value is either a valid IPv4 or IPv6 address.
|
| 248 |
+
|
| 249 |
+
``validate_comma_separated_integer_list``
|
| 250 |
+
-----------------------------------------
|
| 251 |
+
|
| 252 |
+
.. data:: validate_comma_separated_integer_list
|
| 253 |
+
|
| 254 |
+
A :class:`RegexValidator` instance that ensures a value is a
|
| 255 |
+
comma-separated list of integers.
|
| 256 |
+
|
| 257 |
+
``int_list_validator``
|
| 258 |
+
----------------------
|
| 259 |
+
|
| 260 |
+
.. function:: int_list_validator(sep=',', message=None, code='invalid', allow_negative=False)
|
| 261 |
+
|
| 262 |
+
Returns a :class:`RegexValidator` instance that ensures a string consists
|
| 263 |
+
of integers separated by ``sep``. It allows negative integers when
|
| 264 |
+
``allow_negative`` is ``True``.
|
| 265 |
+
|
| 266 |
+
``MaxValueValidator``
|
| 267 |
+
---------------------
|
| 268 |
+
|
| 269 |
+
.. class:: MaxValueValidator(limit_value, message=None)
|
| 270 |
+
|
| 271 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 272 |
+
``'max_value'`` if ``value`` is greater than ``limit_value``, which may be
|
| 273 |
+
a callable.
|
| 274 |
+
|
| 275 |
+
``MinValueValidator``
|
| 276 |
+
---------------------
|
| 277 |
+
|
| 278 |
+
.. class:: MinValueValidator(limit_value, message=None)
|
| 279 |
+
|
| 280 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 281 |
+
``'min_value'`` if ``value`` is less than ``limit_value``, which may be a
|
| 282 |
+
callable.
|
| 283 |
+
|
| 284 |
+
``MaxLengthValidator``
|
| 285 |
+
----------------------
|
| 286 |
+
|
| 287 |
+
.. class:: MaxLengthValidator(limit_value, message=None)
|
| 288 |
+
|
| 289 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 290 |
+
``'max_length'`` if the length of ``value`` is greater than
|
| 291 |
+
``limit_value``, which may be a callable.
|
| 292 |
+
|
| 293 |
+
``MinLengthValidator``
|
| 294 |
+
----------------------
|
| 295 |
+
|
| 296 |
+
.. class:: MinLengthValidator(limit_value, message=None)
|
| 297 |
+
|
| 298 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 299 |
+
``'min_length'`` if the length of ``value`` is less than ``limit_value``,
|
| 300 |
+
which may be a callable.
|
| 301 |
+
|
| 302 |
+
``DecimalValidator``
|
| 303 |
+
--------------------
|
| 304 |
+
|
| 305 |
+
.. class:: DecimalValidator(max_digits, decimal_places)
|
| 306 |
+
|
| 307 |
+
Raises :exc:`~django.core.exceptions.ValidationError` with the following
|
| 308 |
+
codes:
|
| 309 |
+
|
| 310 |
+
- ``'max_digits'`` if the number of digits is larger than ``max_digits``.
|
| 311 |
+
- ``'max_decimal_places'`` if the number of decimals is larger than
|
| 312 |
+
``decimal_places``.
|
| 313 |
+
- ``'max_whole_digits'`` if the number of whole digits is larger than
|
| 314 |
+
the difference between ``max_digits`` and ``decimal_places``.
|
| 315 |
+
|
| 316 |
+
``FileExtensionValidator``
|
| 317 |
+
--------------------------
|
| 318 |
+
|
| 319 |
+
.. class:: FileExtensionValidator(allowed_extensions, message, code)
|
| 320 |
+
|
| 321 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 322 |
+
``'invalid_extension'`` if the extension of ``value.name`` (``value`` is
|
| 323 |
+
a :class:`~django.core.files.File`) isn't found in ``allowed_extensions``.
|
| 324 |
+
The extension is compared case-insensitively with ``allowed_extensions``.
|
| 325 |
+
|
| 326 |
+
.. warning::
|
| 327 |
+
|
| 328 |
+
Don't rely on validation of the file extension to determine a file's
|
| 329 |
+
type. Files can be renamed to have any extension no matter what data
|
| 330 |
+
they contain.
|
| 331 |
+
|
| 332 |
+
``validate_image_file_extension``
|
| 333 |
+
---------------------------------
|
| 334 |
+
|
| 335 |
+
.. data:: validate_image_file_extension
|
| 336 |
+
|
| 337 |
+
Uses Pillow to ensure that ``value.name`` (``value`` is a
|
| 338 |
+
:class:`~django.core.files.File`) has `a valid image extension
|
| 339 |
+
<https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html>`_.
|
| 340 |
+
|
| 341 |
+
``ProhibitNullCharactersValidator``
|
| 342 |
+
-----------------------------------
|
| 343 |
+
|
| 344 |
+
.. class:: ProhibitNullCharactersValidator(message=None, code=None)
|
| 345 |
+
|
| 346 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` if ``str(value)``
|
| 347 |
+
contains one or more null characters (``'\x00'``).
|
| 348 |
+
|
| 349 |
+
:param message: If not ``None``, overrides :attr:`.message`.
|
| 350 |
+
:param code: If not ``None``, overrides :attr:`code`.
|
| 351 |
+
|
| 352 |
+
.. attribute:: message
|
| 353 |
+
|
| 354 |
+
The error message used by
|
| 355 |
+
:exc:`~django.core.exceptions.ValidationError` if validation fails.
|
| 356 |
+
Defaults to ``"Null characters are not allowed."``.
|
| 357 |
+
|
| 358 |
+
.. attribute:: code
|
| 359 |
+
|
| 360 |
+
The error code used by :exc:`~django.core.exceptions.ValidationError`
|
| 361 |
+
if validation fails. Defaults to ``"null_characters_not_allowed"``.
|
| 362 |
+
|
| 363 |
+
``StepValueValidator``
|
| 364 |
+
----------------------
|
| 365 |
+
|
| 366 |
+
.. class:: StepValueValidator(limit_value, message=None, offset=None)
|
| 367 |
+
|
| 368 |
+
Raises a :exc:`~django.core.exceptions.ValidationError` with a code of
|
| 369 |
+
``'step_size'`` if ``value`` is not an integral multiple of
|
| 370 |
+
``limit_value``, which can be a float, integer or decimal value or a
|
| 371 |
+
callable. When ``offset`` is set, the validation occurs against
|
| 372 |
+
``limit_value`` plus ``offset``. For example, for
|
| 373 |
+
``StepValueValidator(3, offset=1.4)`` valid values include ``1.4``,
|
| 374 |
+
``4.4``, ``7.4``, ``10.4``, and so on.
|
| 375 |
+
|
| 376 |
+
.. versionchanged:: 5.0
|
| 377 |
+
|
| 378 |
+
The ``offset`` argument was added.
|
testbed/django__django/docs/releases/0.95.txt
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=================================
|
| 2 |
+
Django version 0.95 release notes
|
| 3 |
+
=================================
|
| 4 |
+
|
| 5 |
+
Welcome to the Django 0.95 release.
|
| 6 |
+
|
| 7 |
+
This represents a significant advance in Django development since the 0.91
|
| 8 |
+
release in January 2006. The details of every change in this release would be
|
| 9 |
+
too extensive to list in full, but a summary is presented below.
|
| 10 |
+
|
| 11 |
+
Suitability and API stability
|
| 12 |
+
=============================
|
| 13 |
+
|
| 14 |
+
This release is intended to provide a stable reference point for developers
|
| 15 |
+
wanting to work on production-level applications that use Django.
|
| 16 |
+
|
| 17 |
+
However, it's not the 1.0 release, and we'll be introducing further changes
|
| 18 |
+
before 1.0. For a clear look at which areas of the framework will change (and
|
| 19 |
+
which ones will *not* change) before 1.0, see the ``api-stability.txt`` file,
|
| 20 |
+
which lives in the docs/ directory of the distribution.
|
| 21 |
+
|
| 22 |
+
You may have a need to use some of the features that are marked as
|
| 23 |
+
"subject to API change" in that document, but that's OK with us as long as it's
|
| 24 |
+
OK with you, and as long as you understand APIs may change in the future.
|
| 25 |
+
|
| 26 |
+
Fortunately, most of Django's core APIs won't be changing before version 1.0.
|
| 27 |
+
There likely won't be as big of a change between 0.95 and 1.0 versions as there
|
| 28 |
+
was between 0.91 and 0.95.
|
| 29 |
+
|
| 30 |
+
Changes and new features
|
| 31 |
+
========================
|
| 32 |
+
|
| 33 |
+
The major changes in this release (for developers currently using the 0.91
|
| 34 |
+
release) are a result of merging the 'magic-removal' branch of development.
|
| 35 |
+
This branch removed a number of constraints in the way Django code had to be
|
| 36 |
+
written that were a consequence of decisions made in the early days of Django,
|
| 37 |
+
prior to its open-source release. It's now possible to write more natural,
|
| 38 |
+
Pythonic code that works as expected, and there's less "black magic" happening
|
| 39 |
+
behind the scenes.
|
| 40 |
+
|
| 41 |
+
Aside from that, another main theme of this release is a dramatic increase in
|
| 42 |
+
usability. We've made countless improvements in error messages, documentation,
|
| 43 |
+
etc., to improve developers' quality of life.
|
| 44 |
+
|
| 45 |
+
The new features and changes introduced in 0.95 include:
|
| 46 |
+
|
| 47 |
+
* Django now uses a more consistent and natural filtering interface for
|
| 48 |
+
retrieving objects from the database.
|
| 49 |
+
|
| 50 |
+
* User-defined models, functions and constants now appear in the module
|
| 51 |
+
namespace they were defined in. (Previously everything was magically
|
| 52 |
+
transferred to the ``django.models.*`` namespace.)
|
| 53 |
+
|
| 54 |
+
* Some optional applications, such as the FlatPage, Sites and Redirects
|
| 55 |
+
apps, have been decoupled and moved into ``django.contrib``. If you don't
|
| 56 |
+
want to use these applications, you no longer have to install their
|
| 57 |
+
database tables.
|
| 58 |
+
|
| 59 |
+
* Django now has support for managing database transactions.
|
| 60 |
+
|
| 61 |
+
* We've added the ability to write custom authentication and authorization
|
| 62 |
+
backends for authenticating users against alternate systems, such as
|
| 63 |
+
LDAP.
|
| 64 |
+
|
| 65 |
+
* We've made it easier to add custom table-level functions to models,
|
| 66 |
+
through a new "Manager" API.
|
| 67 |
+
|
| 68 |
+
* It's now possible to use Django without a database. This simply means
|
| 69 |
+
that the framework no longer requires you to have a working database set
|
| 70 |
+
up just to serve dynamic pages. In other words, you can just use
|
| 71 |
+
URLconfs/views on their own. Previously, the framework required that a
|
| 72 |
+
database be configured, regardless of whether you actually used it.
|
| 73 |
+
|
| 74 |
+
* It's now more explicit and natural to override ``save()`` and ``delete()``
|
| 75 |
+
methods on models, rather than needing to hook into the ``pre_save()`` and
|
| 76 |
+
``post_save()`` method hooks.
|
| 77 |
+
|
| 78 |
+
* Individual pieces of the framework now can be configured without
|
| 79 |
+
requiring the setting of an environment variable. This permits use of,
|
| 80 |
+
for example, the Django templating system inside other applications.
|
| 81 |
+
|
| 82 |
+
* More and more parts of the framework have been internationalized, as
|
| 83 |
+
we've expanded internationalization (i18n) support. The Django
|
| 84 |
+
codebase, including code and templates, has now been translated, at least
|
| 85 |
+
in part, into 31 languages. From Arabic to Chinese to Hungarian to Welsh,
|
| 86 |
+
it is now possible to use Django's admin site in your native language.
|
| 87 |
+
|
| 88 |
+
The number of changes required to port from 0.91-compatible code to the 0.95
|
| 89 |
+
code base are significant in some cases. However, they are, for the most part,
|
| 90 |
+
reasonably routine and only need to be done once. A list of the necessary
|
| 91 |
+
changes is described in the `Removing The Magic`_ wiki page. There is also an
|
| 92 |
+
easy checklist_ for reference when undertaking the porting operation.
|
| 93 |
+
|
| 94 |
+
.. _Removing The Magic: https://code.djangoproject.com/wiki/RemovingTheMagic
|
| 95 |
+
.. _checklist: https://code.djangoproject.com/wiki/MagicRemovalCheatSheet
|
| 96 |
+
|
| 97 |
+
Problem reports and getting help
|
| 98 |
+
================================
|
| 99 |
+
|
| 100 |
+
Need help resolving a problem with Django? The documentation in the
|
| 101 |
+
distribution is also available :doc:`online </index>` at the `Django website`_.
|
| 102 |
+
The :doc:`FAQ </faq/index>` document is especially recommended, as it contains
|
| 103 |
+
a number of issues that come up time and again.
|
| 104 |
+
|
| 105 |
+
For more personalized help, the `django-users`_ mailing list is a very active
|
| 106 |
+
list, with more than 2,000 subscribers who can help you solve any sort of
|
| 107 |
+
Django problem. We recommend you search the archives first, though, because
|
| 108 |
+
many common questions appear with some regularity, and any particular problem
|
| 109 |
+
may already have been answered.
|
| 110 |
+
|
| 111 |
+
Finally, for those who prefer the more immediate feedback offered by IRC,
|
| 112 |
+
there's a ``#django`` channel on ``irc.libera.chat`` that is regularly
|
| 113 |
+
populated by Django users and developers from around the world. Friendly people
|
| 114 |
+
are usually available at any hour of the day -- to help, or just to chat.
|
| 115 |
+
|
| 116 |
+
.. _Django website: https://www.djangoproject.com/
|
| 117 |
+
.. _django-users: https://groups.google.com/g/django-users
|
| 118 |
+
|
| 119 |
+
Thanks for using Django!
|
| 120 |
+
|
| 121 |
+
The Django Team
|
| 122 |
+
July 2006
|
testbed/django__django/docs/releases/1.0.1.txt
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
==========================
|
| 2 |
+
Django 1.0.1 release notes
|
| 3 |
+
==========================
|
| 4 |
+
|
| 5 |
+
Welcome to Django 1.0.1!
|
| 6 |
+
|
| 7 |
+
This is the first "bugfix" release in the Django 1.0 series, improving
|
| 8 |
+
the stability and performance of the Django 1.0 codebase. As such,
|
| 9 |
+
Django 1.0.1 contains no new features (and, pursuant to :doc:`our
|
| 10 |
+
compatibility policy </misc/api-stability/>`, maintains backwards
|
| 11 |
+
compatibility with Django 1.0), but does contain a number of fixes
|
| 12 |
+
and other improvements. Django 1.0.1 is a recommended upgrade for any
|
| 13 |
+
development or deployment currently using or targeting Django 1.0.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
Fixes and improvements in Django 1.0.1
|
| 17 |
+
======================================
|
| 18 |
+
|
| 19 |
+
Django 1.0.1 contains over two hundred fixes to the original Django
|
| 20 |
+
1.0 codebase; full details of every fix are available in `the
|
| 21 |
+
history of the 1.0.X branch`_, but here are some of the
|
| 22 |
+
highlights:
|
| 23 |
+
|
| 24 |
+
* Several fixes in ``django.contrib.comments``, pertaining to RSS
|
| 25 |
+
feeds of comments, default ordering of comments and the XHTML and
|
| 26 |
+
internationalization of the default templates for comments.
|
| 27 |
+
|
| 28 |
+
* Multiple fixes for Django's support of Oracle databases, including
|
| 29 |
+
pagination support for GIS QuerySets, more efficient slicing of
|
| 30 |
+
results and improved introspection of existing databases.
|
| 31 |
+
|
| 32 |
+
* Several fixes for query support in the Django object-relational
|
| 33 |
+
mapper, including repeated setting and resetting of ordering and
|
| 34 |
+
fixes for working with ``INSERT``-only queries.
|
| 35 |
+
|
| 36 |
+
* Multiple fixes for inline forms in formsets.
|
| 37 |
+
|
| 38 |
+
* Multiple fixes for ``unique`` and ``unique_together`` model
|
| 39 |
+
constraints in automatically-generated forms.
|
| 40 |
+
|
| 41 |
+
* Fixed support for custom callable ``upload_to`` declarations when
|
| 42 |
+
handling file uploads through automatically-generated forms.
|
| 43 |
+
|
| 44 |
+
* Fixed support for sorting an admin change list based on a callable
|
| 45 |
+
attributes in ``list_display``.
|
| 46 |
+
|
| 47 |
+
* A fix to the application of autoescaping for literal strings passed
|
| 48 |
+
to the ``join`` template filter. Previously, literal strings passed
|
| 49 |
+
to ``join`` were automatically escaped, contrary to :ref:`the
|
| 50 |
+
documented behavior for autoescaping and literal strings
|
| 51 |
+
<string-literals-and-automatic-escaping>`. Literal strings
|
| 52 |
+
passed to ``join`` are no longer automatically escaped, meaning you
|
| 53 |
+
must now manually escape them; this is an incompatibility if you
|
| 54 |
+
were relying on this bug, but not if you were relying on escaping
|
| 55 |
+
behaving as documented.
|
| 56 |
+
|
| 57 |
+
* Improved and expanded translation files for many of the languages
|
| 58 |
+
Django supports by default.
|
| 59 |
+
|
| 60 |
+
* And as always, a large number of improvements to Django's
|
| 61 |
+
documentation, including both corrections to existing documents and
|
| 62 |
+
expanded and new documentation.
|
| 63 |
+
|
| 64 |
+
.. _the history of the 1.0.X branch: https://github.com/django/django/commits/stable/1.0.x
|
testbed/django__django/docs/releases/1.1.3.txt
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
==========================
|
| 2 |
+
Django 1.1.3 release notes
|
| 3 |
+
==========================
|
| 4 |
+
|
| 5 |
+
Welcome to Django 1.1.3!
|
| 6 |
+
|
| 7 |
+
This is the third "bugfix" release in the Django 1.1 series,
|
| 8 |
+
improving the stability and performance of the Django 1.1 codebase.
|
| 9 |
+
|
| 10 |
+
With one exception, Django 1.1.3 maintains backwards compatibility
|
| 11 |
+
with Django 1.1.2. It also contains a number of fixes and other
|
| 12 |
+
improvements. Django 1.1.2 is a recommended upgrade for any
|
| 13 |
+
development or deployment currently using or targeting Django 1.1.
|
| 14 |
+
|
| 15 |
+
For full details on the new features, backwards incompatibilities, and
|
| 16 |
+
deprecated features in the 1.1 branch, see the :doc:`/releases/1.1`.
|
| 17 |
+
|
| 18 |
+
Backwards incompatible changes
|
| 19 |
+
==============================
|
| 20 |
+
|
| 21 |
+
Restricted filters in admin interface
|
| 22 |
+
-------------------------------------
|
| 23 |
+
|
| 24 |
+
The Django administrative interface, ``django.contrib.admin``, supports
|
| 25 |
+
filtering of displayed lists of objects by fields on the corresponding
|
| 26 |
+
models, including across database-level relationships. This is
|
| 27 |
+
implemented by passing lookup arguments in the querystring portion of
|
| 28 |
+
the URL, and options on the ModelAdmin class allow developers to
|
| 29 |
+
specify particular fields or relationships which will generate
|
| 30 |
+
automatic links for filtering.
|
| 31 |
+
|
| 32 |
+
One historically-undocumented and -unofficially-supported feature has
|
| 33 |
+
been the ability for a user with sufficient knowledge of a model's
|
| 34 |
+
structure and the format of these lookup arguments to invent useful
|
| 35 |
+
new filters on the fly by manipulating the querystring.
|
| 36 |
+
|
| 37 |
+
However, it has been demonstrated that this can be abused to gain
|
| 38 |
+
access to information outside of an admin user's permissions; for
|
| 39 |
+
example, an attacker with access to the admin and sufficient knowledge
|
| 40 |
+
of model structure and relations could construct query strings which --
|
| 41 |
+
with repeated use of regular-expression lookups supported by the
|
| 42 |
+
Django database API -- expose sensitive information such as users'
|
| 43 |
+
password hashes.
|
| 44 |
+
|
| 45 |
+
To remedy this, ``django.contrib.admin`` will now validate that
|
| 46 |
+
querystring lookup arguments either specify only fields on the model
|
| 47 |
+
being viewed, or cross relations which have been explicitly
|
| 48 |
+
allowed by the application developer using the preexisting
|
| 49 |
+
mechanism mentioned above. This is backwards-incompatible for any
|
| 50 |
+
users relying on the prior ability to insert arbitrary lookups.
|
testbed/django__django/docs/releases/1.1.4.txt
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
==========================
|
| 2 |
+
Django 1.1.4 release notes
|
| 3 |
+
==========================
|
| 4 |
+
|
| 5 |
+
Welcome to Django 1.1.4!
|
| 6 |
+
|
| 7 |
+
This is the fourth "bugfix" release in the Django 1.1 series,
|
| 8 |
+
improving the stability and performance of the Django 1.1 codebase.
|
| 9 |
+
|
| 10 |
+
With one exception, Django 1.1.4 maintains backwards compatibility
|
| 11 |
+
with Django 1.1.3. It also contains a number of fixes and other
|
| 12 |
+
improvements. Django 1.1.4 is a recommended upgrade for any
|
| 13 |
+
development or deployment currently using or targeting Django 1.1.
|
| 14 |
+
|
| 15 |
+
For full details on the new features, backwards incompatibilities, and
|
| 16 |
+
deprecated features in the 1.1 branch, see the :doc:`/releases/1.1`.
|
| 17 |
+
|
| 18 |
+
Backwards incompatible changes
|
| 19 |
+
==============================
|
| 20 |
+
|
| 21 |
+
CSRF exception for AJAX requests
|
| 22 |
+
--------------------------------
|
| 23 |
+
|
| 24 |
+
Django includes a CSRF-protection mechanism, which makes use of a
|
| 25 |
+
token inserted into outgoing forms. Middleware then checks for the
|
| 26 |
+
token's presence on form submission, and validates it.
|
| 27 |
+
|
| 28 |
+
Prior to Django 1.2.5, our CSRF protection made an exception for AJAX
|
| 29 |
+
requests, on the following basis:
|
| 30 |
+
|
| 31 |
+
* Many AJAX toolkits add an X-Requested-With header when using
|
| 32 |
+
XMLHttpRequest.
|
| 33 |
+
|
| 34 |
+
* Browsers have strict same-origin policies regarding
|
| 35 |
+
XMLHttpRequest.
|
| 36 |
+
|
| 37 |
+
* In the context of a browser, the only way that a custom header
|
| 38 |
+
of this nature can be added is with XMLHttpRequest.
|
| 39 |
+
|
| 40 |
+
Therefore, for ease of use, we did not apply CSRF checks to requests
|
| 41 |
+
that appeared to be AJAX on the basis of the X-Requested-With header.
|
| 42 |
+
The Ruby on Rails web framework had a similar exemption.
|
| 43 |
+
|
| 44 |
+
Recently, engineers at Google made members of the Ruby on Rails
|
| 45 |
+
development team aware of a combination of browser plugins and
|
| 46 |
+
redirects which can allow an attacker to provide custom HTTP headers
|
| 47 |
+
on a request to any website. This can allow a forged request to appear
|
| 48 |
+
to be an AJAX request, thereby defeating CSRF protection which trusts
|
| 49 |
+
the same-origin nature of AJAX requests.
|
| 50 |
+
|
| 51 |
+
Michael Koziarski of the Rails team brought this to our attention, and
|
| 52 |
+
we were able to produce a proof-of-concept demonstrating the same
|
| 53 |
+
vulnerability in Django's CSRF handling.
|
| 54 |
+
|
| 55 |
+
To remedy this, Django will now apply full CSRF validation to all
|
| 56 |
+
requests, regardless of apparent AJAX origin. This is technically
|
| 57 |
+
backwards-incompatible, but the security risks have been judged to
|
| 58 |
+
outweigh the compatibility concerns in this case.
|
| 59 |
+
|
| 60 |
+
Additionally, Django will now accept the CSRF token in the custom HTTP
|
| 61 |
+
header X-CSRFTOKEN, as well as in the form submission itself, for ease
|
| 62 |
+
of use with popular JavaScript toolkits which allow insertion of
|
| 63 |
+
custom headers into all AJAX requests.
|
| 64 |
+
|
| 65 |
+
Please see the :ref:`CSRF docs for example jQuery code <csrf-ajax>`
|
| 66 |
+
that demonstrates this technique, ensuring that you are looking at the
|
| 67 |
+
documentation for your version of Django, as the exact code necessary
|
| 68 |
+
is different for some older versions of Django.
|
testbed/django__django/docs/releases/1.10.1.txt
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.1 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*September 1, 2016*
|
| 6 |
+
|
| 7 |
+
Django 1.10.1 fixes several bugs in 1.10.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a crash in MySQL connections where ``SELECT @@SQL_AUTO_IS_NULL``
|
| 13 |
+
doesn't return a result (:ticket:`26991`).
|
| 14 |
+
|
| 15 |
+
* Allowed ``User.is_authenticated`` and ``User.is_anonymous`` properties to be
|
| 16 |
+
compared using ``==``, ``!=``, and ``|`` (:ticket:`26988`, :ticket:`27154`).
|
| 17 |
+
|
| 18 |
+
* Removed the broken ``BaseCommand.usage()`` method which was for
|
| 19 |
+
``optparse`` support (:ticket:`27000`).
|
| 20 |
+
|
| 21 |
+
* Fixed a checks framework crash with an empty ``Meta.default_permissions``
|
| 22 |
+
(:ticket:`26997`).
|
| 23 |
+
|
| 24 |
+
* Fixed a regression in the number of queries when using ``RadioSelect`` with a
|
| 25 |
+
``ModelChoiceField`` form field (:ticket:`27001`).
|
| 26 |
+
|
| 27 |
+
* Fixed a crash if ``request.META['CONTENT_LENGTH']`` is an empty string
|
| 28 |
+
(:ticket:`27005`).
|
| 29 |
+
|
| 30 |
+
* Fixed the ``isnull`` lookup on a ``ForeignKey`` with its ``to_field``
|
| 31 |
+
pointing to a ``CharField`` or pointing to a ``CharField`` defined with
|
| 32 |
+
``primary_key=True`` (:ticket:`26983`).
|
| 33 |
+
|
| 34 |
+
* Prevented the ``migrate`` command from raising
|
| 35 |
+
``InconsistentMigrationHistory`` in the presence of unapplied squashed
|
| 36 |
+
migrations (:ticket:`27004`).
|
| 37 |
+
|
| 38 |
+
* Fixed a regression in ``Client.force_login()`` which required specifying a
|
| 39 |
+
``backend`` rather than automatically using the first one if multiple
|
| 40 |
+
backends are configured (:ticket:`27027`).
|
| 41 |
+
|
| 42 |
+
* Made ``QuerySet.bulk_create()`` properly initialize model instances on
|
| 43 |
+
backends, such as PostgreSQL, that support returning the IDs of the created
|
| 44 |
+
records so that many-to-many relationships can be used on the new objects
|
| 45 |
+
(:ticket:`27026`).
|
| 46 |
+
|
| 47 |
+
* Fixed crash of ``django.views.static.serve()`` with ``show_indexes`` enabled
|
| 48 |
+
(:ticket:`26973`).
|
| 49 |
+
|
| 50 |
+
* Fixed ``ClearableFileInput`` to avoid the ``required`` HTML attribute when
|
| 51 |
+
initial data exists (:ticket:`27037`).
|
| 52 |
+
|
| 53 |
+
* Fixed annotations with database functions when combined with lookups on
|
| 54 |
+
PostGIS (:ticket:`27014`).
|
| 55 |
+
|
| 56 |
+
* Reallowed the ``{% for %}`` tag to unpack any iterable (:ticket:`27058`).
|
| 57 |
+
|
| 58 |
+
* Made ``makemigrations`` skip inconsistent history checks on non-default
|
| 59 |
+
databases if database routers aren't in use or if no apps can be migrated
|
| 60 |
+
to the database (:ticket:`27054`, :ticket:`27110`, :ticket:`27142`).
|
| 61 |
+
|
| 62 |
+
* Removed duplicated managers in ``Model._meta.managers`` (:ticket:`27073`).
|
| 63 |
+
|
| 64 |
+
* Fixed ``contrib.admindocs`` crash when a view is in a class, such as some of
|
| 65 |
+
the admin views (:ticket:`27018`).
|
| 66 |
+
|
| 67 |
+
* Reverted a few admin checks that checked ``field.many_to_many`` back to
|
| 68 |
+
``isinstance(field, models.ManyToManyField)`` since it turned out the checks
|
| 69 |
+
weren't suitable to be generalized like that (:ticket:`26998`).
|
| 70 |
+
|
| 71 |
+
* Added the database alias to the ``InconsistentMigrationHistory`` message
|
| 72 |
+
raised by ``makemigrations`` and ``migrate`` (:ticket:`27089`).
|
| 73 |
+
|
| 74 |
+
* Fixed the creation of ``ContentType`` and ``Permission`` objects for models
|
| 75 |
+
of applications without migrations when calling the ``migrate`` command with
|
| 76 |
+
no migrations to apply (:ticket:`27044`).
|
| 77 |
+
|
| 78 |
+
* Included the already applied migration state changes in the ``Apps`` instance
|
| 79 |
+
provided to the ``pre_migrate`` signal receivers to allow ``ContentType``
|
| 80 |
+
renaming to be performed on model rename (:ticket:`27100`).
|
| 81 |
+
|
| 82 |
+
* Reallowed subclassing ``UserCreationForm`` without ``USERNAME_FIELD`` in
|
| 83 |
+
``Meta.fields`` (:ticket:`27111`).
|
| 84 |
+
|
| 85 |
+
* Fixed a regression in model forms where model fields with a ``default`` that
|
| 86 |
+
didn't appear in POST data no longer used the ``default`` (:ticket:`27039`).
|
testbed/django__django/docs/releases/1.10.2.txt
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.2 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*October 1, 2016*
|
| 6 |
+
|
| 7 |
+
Django 1.10.2 fixes several bugs in 1.10.1.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a crash in MySQL database validation where ``SELECT @@sql_mode``
|
| 13 |
+
doesn't return a result (:ticket:`27180`).
|
| 14 |
+
|
| 15 |
+
* Allowed combining ``contrib.postgres.search.SearchQuery`` with more than one
|
| 16 |
+
``&`` or ``|`` operators (:ticket:`27143`).
|
| 17 |
+
|
| 18 |
+
* Disabled system check for URL patterns beginning with a '/' when
|
| 19 |
+
``APPEND_SLASH=False`` (:ticket:`27238`).
|
| 20 |
+
|
| 21 |
+
* Fixed model form ``default`` fallback for ``CheckboxSelectMultiple``,
|
| 22 |
+
``MultiWidget``, ``FileInput``, ``SplitDateTimeWidget``, ``SelectDateWidget``,
|
| 23 |
+
and ``SplitArrayWidget`` (:ticket:`27186`). Custom widgets affected by this
|
| 24 |
+
issue should implement :meth:`~django.forms.Widget.value_omitted_from_data`.
|
| 25 |
+
|
| 26 |
+
* Fixed a crash in ``runserver`` logging during a "Broken pipe" error
|
| 27 |
+
(:ticket:`27271`).
|
| 28 |
+
|
| 29 |
+
* Fixed a regression where unchanged localized date/time fields were listed as
|
| 30 |
+
changed in the admin's model history messages (:ticket:`27302`).
|
testbed/django__django/docs/releases/1.10.4.txt
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.4 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*December 1, 2016*
|
| 6 |
+
|
| 7 |
+
Django 1.10.4 fixes several bugs in 1.10.3.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Quoted the Oracle test user's password in queries to fix the "ORA-00922:
|
| 13 |
+
missing or invalid option" error when the password starts with a number or
|
| 14 |
+
special character (:ticket:`27420`).
|
| 15 |
+
|
| 16 |
+
* Fixed incorrect ``app_label`` / ``model_name`` arguments for
|
| 17 |
+
``allow_migrate()`` in ``makemigrations`` migration consistency checks
|
| 18 |
+
(:ticket:`27461`).
|
| 19 |
+
|
| 20 |
+
* Made ``Model.delete(keep_parents=True)`` preserve parent reverse
|
| 21 |
+
relationships in multi-table inheritance (:ticket:`27407`).
|
| 22 |
+
|
| 23 |
+
* Fixed a ``QuerySet.update()`` crash on SQLite when updating a
|
| 24 |
+
``DateTimeField`` with an ``F()`` expression and a ``timedelta``
|
| 25 |
+
(:ticket:`27544`).
|
| 26 |
+
|
| 27 |
+
* Prevented ``LocaleMiddleware`` from redirecting on URLs that should return
|
| 28 |
+
404 when using ``prefix_default_language=False`` (:ticket:`27402`).
|
| 29 |
+
|
| 30 |
+
* Prevented an unnecessary index from being created on an InnoDB ``ForeignKey``
|
| 31 |
+
when the field was added after the model was created (:ticket:`27558`).
|
testbed/django__django/docs/releases/1.10.5.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.5 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*January 4, 2017*
|
| 6 |
+
|
| 7 |
+
Django 1.10.5 fixes several bugs in 1.10.4.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a crash in the debug view if ``request.user`` can't be retrieved, such
|
| 13 |
+
as if the database is unavailable (:ticket:`27567`).
|
| 14 |
+
|
| 15 |
+
* Fixed occasional missing plural forms in ``JavaScriptCatalog``
|
| 16 |
+
(:ticket:`27418`).
|
| 17 |
+
|
| 18 |
+
* Fixed a regression in the ``timesince`` and ``timeuntil`` filters that caused
|
| 19 |
+
incorrect results for dates in a leap year (:ticket:`27637`).
|
| 20 |
+
|
| 21 |
+
* Fixed a regression where ``collectstatic`` overwrote newer files in remote
|
| 22 |
+
storages (:ticket:`27658`).
|
testbed/django__django/docs/releases/1.10.6.txt
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.6 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*March 1, 2017*
|
| 6 |
+
|
| 7 |
+
Django 1.10.6 fixes several bugs in 1.10.5.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed ``ClearableFileInput``’s "Clear" checkbox on model form fields where
|
| 13 |
+
the model field has a ``default`` (:ticket:`27805`).
|
| 14 |
+
|
| 15 |
+
* Fixed ``RequestDataTooBig`` and ``TooManyFieldsSent`` exceptions crashing
|
| 16 |
+
rather than generating a bad request response (:ticket:`27820`).
|
| 17 |
+
|
| 18 |
+
* Fixed a crash on Oracle and PostgreSQL when subtracting ``DurationField``
|
| 19 |
+
or ``IntegerField`` from ``DateField`` (:ticket:`27828`).
|
| 20 |
+
|
| 21 |
+
* Fixed query expression date subtraction accuracy on PostgreSQL for
|
| 22 |
+
differences larger than a month (:ticket:`27856`).
|
| 23 |
+
|
| 24 |
+
* Fixed a ``GDALException`` raised by ``GDALClose`` on GDAL ≥ 2.0
|
| 25 |
+
(:ticket:`27479`).
|
testbed/django__django/docs/releases/1.10.7.txt
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.7 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*April 4, 2017*
|
| 6 |
+
|
| 7 |
+
Django 1.10.7 fixes two security issues and a bug in 1.10.6.
|
| 8 |
+
|
| 9 |
+
CVE-2017-7233: Open redirect and possible XSS attack via user-supplied numeric redirect URLs
|
| 10 |
+
============================================================================================
|
| 11 |
+
|
| 12 |
+
Django relies on user input in some cases (e.g.
|
| 13 |
+
``django.contrib.auth.views.login()`` and :doc:`i18n </topics/i18n/index>`)
|
| 14 |
+
to redirect the user to an "on success" URL. The security check for these
|
| 15 |
+
redirects (namely ``django.utils.http.is_safe_url()``) considered some numeric
|
| 16 |
+
URLs (e.g. ``http:999999999``) "safe" when they shouldn't be.
|
| 17 |
+
|
| 18 |
+
Also, if a developer relies on ``is_safe_url()`` to provide safe redirect
|
| 19 |
+
targets and puts such a URL into a link, they could suffer from an XSS attack.
|
| 20 |
+
|
| 21 |
+
CVE-2017-7234: Open redirect vulnerability in ``django.views.static.serve()``
|
| 22 |
+
=============================================================================
|
| 23 |
+
|
| 24 |
+
A maliciously crafted URL to a Django site using the
|
| 25 |
+
:func:`~django.views.static.serve` view could redirect to any other domain. The
|
| 26 |
+
view no longer does any redirects as they don't provide any known, useful
|
| 27 |
+
functionality.
|
| 28 |
+
|
| 29 |
+
Note, however, that this view has always carried a warning that it is not
|
| 30 |
+
hardened for production use and should be used only as a development aid.
|
| 31 |
+
|
| 32 |
+
Bugfixes
|
| 33 |
+
========
|
| 34 |
+
|
| 35 |
+
* Made admin's ``RelatedFieldWidgetWrapper`` use the wrapped widget's
|
| 36 |
+
``value_omitted_from_data()`` method (:ticket:`27905`).
|
| 37 |
+
|
| 38 |
+
* Fixed model form ``default`` fallback for ``SelectMultiple``
|
| 39 |
+
(:ticket:`27993`).
|
testbed/django__django/docs/releases/1.10.8.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.10.8 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*September 5, 2017*
|
| 6 |
+
|
| 7 |
+
Django 1.10.8 fixes a security issue in 1.10.7.
|
| 8 |
+
|
| 9 |
+
CVE-2017-12794: Possible XSS in traceback section of technical 500 debug page
|
| 10 |
+
=============================================================================
|
| 11 |
+
|
| 12 |
+
In older versions, HTML autoescaping was disabled in a portion of the template
|
| 13 |
+
for the technical 500 debug page. Given the right circumstances, this allowed
|
| 14 |
+
a cross-site scripting attack. This vulnerability shouldn't affect most
|
| 15 |
+
production sites since you shouldn't run with ``DEBUG = True`` (which makes
|
| 16 |
+
this page accessible) in your production settings.
|
testbed/django__django/docs/releases/1.11.10.txt
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.10 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*February 1, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.10 fixes a security issue and several bugs in 1.11.9.
|
| 8 |
+
|
| 9 |
+
CVE-2018-6188: Information leakage in ``AuthenticationForm``
|
| 10 |
+
============================================================
|
| 11 |
+
|
| 12 |
+
A regression in Django 1.11.8 made
|
| 13 |
+
:class:`~django.contrib.auth.forms.AuthenticationForm` run its
|
| 14 |
+
``confirm_login_allowed()`` method even if an incorrect password is entered.
|
| 15 |
+
This can leak information about a user, depending on what messages
|
| 16 |
+
``confirm_login_allowed()`` raises. If ``confirm_login_allowed()`` isn't
|
| 17 |
+
overridden, an attacker enter an arbitrary username and see if that user has
|
| 18 |
+
been set to ``is_active=False``. If ``confirm_login_allowed()`` is overridden,
|
| 19 |
+
more sensitive details could be leaked.
|
| 20 |
+
|
| 21 |
+
This issue is fixed with the caveat that ``AuthenticationForm`` can no longer
|
| 22 |
+
raise the "This account is inactive." error if the authentication backend
|
| 23 |
+
rejects inactive users (the default authentication backend, ``ModelBackend``,
|
| 24 |
+
has done that since Django 1.10). This issue will be revisited for Django 2.1
|
| 25 |
+
as a fix to address the caveat will likely be too invasive for inclusion in
|
| 26 |
+
older versions.
|
| 27 |
+
|
| 28 |
+
Bugfixes
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
* Fixed incorrect foreign key nullification if a model has two foreign keys to
|
| 32 |
+
the same model and a target model is deleted (:ticket:`29016`).
|
| 33 |
+
|
| 34 |
+
* Fixed a regression where ``contrib.auth.authenticate()`` crashes if an
|
| 35 |
+
authentication backend doesn't accept ``request`` and a later one does
|
| 36 |
+
(:ticket:`29071`).
|
| 37 |
+
|
| 38 |
+
* Fixed crash when entering an invalid uuid in ``ModelAdmin.raw_id_fields``
|
| 39 |
+
(:ticket:`29094`).
|
testbed/django__django/docs/releases/1.11.11.txt
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.11 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*March 6, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.11 fixes two security issues in 1.11.10.
|
| 8 |
+
|
| 9 |
+
CVE-2018-7536: Denial-of-service possibility in ``urlize`` and ``urlizetrunc`` template filters
|
| 10 |
+
===============================================================================================
|
| 11 |
+
|
| 12 |
+
The ``django.utils.html.urlize()`` function was extremely slow to evaluate
|
| 13 |
+
certain inputs due to catastrophic backtracking vulnerabilities in two regular
|
| 14 |
+
expressions. The ``urlize()`` function is used to implement the ``urlize`` and
|
| 15 |
+
``urlizetrunc`` template filters, which were thus vulnerable.
|
| 16 |
+
|
| 17 |
+
The problematic regular expressions are replaced with parsing logic that
|
| 18 |
+
behaves similarly.
|
| 19 |
+
|
| 20 |
+
CVE-2018-7537: Denial-of-service possibility in ``truncatechars_html`` and ``truncatewords_html`` template filters
|
| 21 |
+
==================================================================================================================
|
| 22 |
+
|
| 23 |
+
If ``django.utils.text.Truncator``'s ``chars()`` and ``words()`` methods were
|
| 24 |
+
passed the ``html=True`` argument, they were extremely slow to evaluate certain
|
| 25 |
+
inputs due to a catastrophic backtracking vulnerability in a regular
|
| 26 |
+
expression. The ``chars()`` and ``words()`` methods are used to implement the
|
| 27 |
+
``truncatechars_html`` and ``truncatewords_html`` template filters, which were
|
| 28 |
+
thus vulnerable.
|
| 29 |
+
|
| 30 |
+
The backtracking problem in the regular expression is fixed.
|
testbed/django__django/docs/releases/1.11.12.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.12 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*April 2, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.12 fixes two bugs in 1.11.11.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a regression in Django 1.11.8 where combining two annotated
|
| 13 |
+
``values_list()`` querysets with ``union()``, ``difference()``, or
|
| 14 |
+
``intersection()`` crashed due to mismatching columns (:ticket:`29229`).
|
| 15 |
+
|
| 16 |
+
* Fixed a regression in Django 1.11 where an empty choice could be initially
|
| 17 |
+
selected for the ``SelectMultiple`` and ``CheckboxSelectMultiple`` widgets
|
| 18 |
+
(:ticket:`29273`).
|
testbed/django__django/docs/releases/1.11.14.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.14 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*July 2, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.14 fixes several bugs in 1.11.13.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed ``WKBWriter.write()`` and ``write_hex()`` for empty polygons on
|
| 13 |
+
GEOS 3.6.1+ (:ticket:`29460`).
|
| 14 |
+
|
| 15 |
+
* Fixed a regression in Django 1.10 that could result in large memory usage
|
| 16 |
+
when making edits using ``ModelAdmin.list_editable`` (:ticket:`28462`).
|
testbed/django__django/docs/releases/1.11.15.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.15 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*August 1, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.15 fixes a security issue in 1.11.14.
|
| 8 |
+
|
| 9 |
+
CVE-2018-14574: Open redirect possibility in ``CommonMiddleware``
|
| 10 |
+
=================================================================
|
| 11 |
+
|
| 12 |
+
If the :class:`~django.middleware.common.CommonMiddleware` and the
|
| 13 |
+
:setting:`APPEND_SLASH` setting are both enabled, and if the project has a
|
| 14 |
+
URL pattern that accepts any path ending in a slash (many content management
|
| 15 |
+
systems have such a pattern), then a request to a maliciously crafted URL of
|
| 16 |
+
that site could lead to a redirect to another site, enabling phishing and other
|
| 17 |
+
attacks.
|
| 18 |
+
|
| 19 |
+
``CommonMiddleware`` now escapes leading slashes to prevent redirects to other
|
| 20 |
+
domains.
|
testbed/django__django/docs/releases/1.11.16.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.16 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*October 1, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.16 fixes a data loss bug in 1.11.15.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a race condition in ``QuerySet.update_or_create()`` that could result
|
| 13 |
+
in data loss (:ticket:`29499`).
|
testbed/django__django/docs/releases/1.11.17.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.17 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*December 3, 2018*
|
| 6 |
+
|
| 7 |
+
Django 1.11.17 fixes several bugs in 1.11.16 and adds compatibility with
|
| 8 |
+
Python 3.7.
|
| 9 |
+
|
| 10 |
+
Bugfixes
|
| 11 |
+
========
|
| 12 |
+
|
| 13 |
+
* Prevented repetitive calls to ``geos_version_tuple()`` in the ``WKBWriter``
|
| 14 |
+
class in an attempt to fix a random crash involving ``LooseVersion`` since
|
| 15 |
+
Django 1.11.14 (:ticket:`29959`).
|
testbed/django__django/docs/releases/1.11.18.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.18 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*January 4, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.18 fixes a security issue in 1.11.17.
|
| 8 |
+
|
| 9 |
+
CVE-2019-3498: Content spoofing possibility in the default 404 page
|
| 10 |
+
-------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
An attacker could craft a malicious URL that could make spoofed content appear
|
| 13 |
+
on the default page generated by the ``django.views.defaults.page_not_found()``
|
| 14 |
+
view.
|
| 15 |
+
|
| 16 |
+
The URL path is no longer displayed in the default 404 template and the
|
| 17 |
+
``request_path`` context variable is now quoted to fix the issue for custom
|
| 18 |
+
templates that use the path.
|
testbed/django__django/docs/releases/1.11.19.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.19 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*February 11, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.19 fixes a security issue in 1.11.18.
|
| 8 |
+
|
| 9 |
+
CVE-2019-6975: Memory exhaustion in ``django.utils.numberformat.format()``
|
| 10 |
+
--------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
If ``django.utils.numberformat.format()`` -- used by ``contrib.admin`` as well
|
| 13 |
+
as the ``floatformat``, ``filesizeformat``, and ``intcomma`` templates filters
|
| 14 |
+
-- received a ``Decimal`` with a large number of digits or a large exponent, it
|
| 15 |
+
could lead to significant memory usage due to a call to ``'{:f}'.format()``.
|
| 16 |
+
|
| 17 |
+
To avoid this, decimals with more than 200 digits are now formatted using
|
| 18 |
+
scientific notation.
|
testbed/django__django/docs/releases/1.11.2.txt
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
===========================
|
| 2 |
+
Django 1.11.2 release notes
|
| 3 |
+
===========================
|
| 4 |
+
|
| 5 |
+
*June 1, 2017*
|
| 6 |
+
|
| 7 |
+
Django 1.11.2 adds a minor feature and fixes several bugs in 1.11.1. Also, the
|
| 8 |
+
latest string translations from Transifex are incorporated.
|
| 9 |
+
|
| 10 |
+
Minor feature
|
| 11 |
+
=============
|
| 12 |
+
|
| 13 |
+
The new ``LiveServerTestCase.port`` attribute reallows the use case of binding
|
| 14 |
+
to a specific port following the :ref:`bind to port zero
|
| 15 |
+
<liveservertestcase-port-zero-change>` change in Django 1.11.
|
| 16 |
+
|
| 17 |
+
Bugfixes
|
| 18 |
+
========
|
| 19 |
+
|
| 20 |
+
* Added detection for GDAL 2.1 and 2.0, and removed detection for unsupported
|
| 21 |
+
versions 1.7 and 1.8 (:ticket:`28181`).
|
| 22 |
+
|
| 23 |
+
* Changed ``contrib.gis`` to raise ``ImproperlyConfigured`` rather than
|
| 24 |
+
``GDALException`` if ``gdal`` isn't installed, to allow third-party apps to
|
| 25 |
+
catch that exception (:ticket:`28178`).
|
| 26 |
+
|
| 27 |
+
* Fixed ``django.utils.http.is_safe_url()`` crash on invalid IPv6 URLs
|
| 28 |
+
(:ticket:`28142`).
|
| 29 |
+
|
| 30 |
+
* Fixed regression causing pickling of model fields to crash (:ticket:`28188`).
|
| 31 |
+
|
| 32 |
+
* Fixed ``django.contrib.auth.authenticate()`` when multiple authentication
|
| 33 |
+
backends don't accept a positional ``request`` argument (:ticket:`28207`).
|
| 34 |
+
|
| 35 |
+
* Fixed introspection of index field ordering on PostgreSQL (:ticket:`28197`).
|
| 36 |
+
|
| 37 |
+
* Fixed a regression where ``Model._state.adding`` wasn't set correctly on
|
| 38 |
+
multi-table inheritance parent models after saving a child model
|
| 39 |
+
(:ticket:`28210`).
|
| 40 |
+
|
| 41 |
+
* Allowed ``DjangoJSONEncoder`` to serialize
|
| 42 |
+
``django.utils.deprecation.CallableBool`` (:ticket:`28230`).
|
| 43 |
+
|
| 44 |
+
* Relaxed the validation added in Django 1.11 of the fields in the ``defaults``
|
| 45 |
+
argument of ``QuerySet.get_or_create()`` and ``update_or_create()`` to
|
| 46 |
+
reallow settable model properties (:ticket:`28222`).
|
| 47 |
+
|
| 48 |
+
* Fixed ``MultipleObjectMixin.paginate_queryset()`` crash on Python 2 if the
|
| 49 |
+
``InvalidPage`` message contains non-ASCII (:ticket:`28204`).
|
| 50 |
+
|
| 51 |
+
* Prevented ``Subquery`` from adding an unnecessary ``CAST`` which resulted in
|
| 52 |
+
invalid SQL (:ticket:`28199`).
|
| 53 |
+
|
| 54 |
+
* Corrected detection of GDAL 2.1 on Windows (:ticket:`28181`).
|
| 55 |
+
|
| 56 |
+
* Made date-based generic views return a 404 rather than crash when given an
|
| 57 |
+
out of range date (:ticket:`28209`).
|
| 58 |
+
|
| 59 |
+
* Fixed a regression where ``file_move_safe()`` crashed when moving files to a
|
| 60 |
+
CIFS mount (:ticket:`28170`).
|
| 61 |
+
|
| 62 |
+
* Moved the ``ImageField`` file extension validation added in Django 1.11 from
|
| 63 |
+
the model field to the form field to reallow the use case of storing images
|
| 64 |
+
without an extension (:ticket:`28242`).
|
testbed/django__django/docs/releases/1.11.20.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.20 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*February 11, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.20 fixes a packaging error in 1.11.19.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Corrected packaging error from 1.11.19 (:ticket:`30175`).
|
testbed/django__django/docs/releases/1.11.21.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.21 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*June 3, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.21 fixes a security issue in 1.11.20.
|
| 8 |
+
|
| 9 |
+
CVE-2019-12308: AdminURLFieldWidget XSS
|
| 10 |
+
---------------------------------------
|
| 11 |
+
|
| 12 |
+
The clickable "Current URL" link generated by ``AdminURLFieldWidget`` displayed
|
| 13 |
+
the provided value without validating it as a safe URL. Thus, an unvalidated
|
| 14 |
+
value stored in the database, or a value provided as a URL query parameter
|
| 15 |
+
payload, could result in an clickable JavaScript link.
|
| 16 |
+
|
| 17 |
+
``AdminURLFieldWidget`` now validates the provided value using
|
| 18 |
+
:class:`~django.core.validators.URLValidator` before displaying the clickable
|
| 19 |
+
link. You may customize the validator by passing a ``validator_class`` kwarg to
|
| 20 |
+
``AdminURLFieldWidget.__init__()``, e.g. when using
|
| 21 |
+
:attr:`~django.contrib.admin.ModelAdmin.formfield_overrides`.
|
testbed/django__django/docs/releases/1.11.22.txt
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.22 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*July 1, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.22 fixes a security issue in 1.11.21.
|
| 8 |
+
|
| 9 |
+
CVE-2019-12781: Incorrect HTTP detection with reverse-proxy connecting via HTTPS
|
| 10 |
+
--------------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
When deployed behind a reverse-proxy connecting to Django via HTTPS,
|
| 13 |
+
:attr:`django.http.HttpRequest.scheme` would incorrectly detect client
|
| 14 |
+
requests made via HTTP as using HTTPS. This entails incorrect results for
|
| 15 |
+
:meth:`~django.http.HttpRequest.is_secure`, and
|
| 16 |
+
:meth:`~django.http.HttpRequest.build_absolute_uri`, and that HTTP
|
| 17 |
+
requests would not be redirected to HTTPS in accordance with
|
| 18 |
+
:setting:`SECURE_SSL_REDIRECT`.
|
| 19 |
+
|
| 20 |
+
``HttpRequest.scheme`` now respects :setting:`SECURE_PROXY_SSL_HEADER`, if it
|
| 21 |
+
is configured, and the appropriate header is set on the request, for both HTTP
|
| 22 |
+
and HTTPS requests.
|
| 23 |
+
|
| 24 |
+
If you deploy Django behind a reverse-proxy that forwards HTTP requests, and
|
| 25 |
+
that connects to Django via HTTPS, be sure to verify that your application
|
| 26 |
+
correctly handles code paths relying on ``scheme``, ``is_secure()``,
|
| 27 |
+
``build_absolute_uri()``, and ``SECURE_SSL_REDIRECT``.
|
testbed/django__django/docs/releases/1.11.23.txt
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.23 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*August 1, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.23 fixes security issues in 1.11.22.
|
| 8 |
+
|
| 9 |
+
CVE-2019-14232: Denial-of-service possibility in ``django.utils.text.Truncator``
|
| 10 |
+
================================================================================
|
| 11 |
+
|
| 12 |
+
If ``django.utils.text.Truncator``'s ``chars()`` and ``words()`` methods
|
| 13 |
+
were passed the ``html=True`` argument, they were extremely slow to evaluate
|
| 14 |
+
certain inputs due to a catastrophic backtracking vulnerability in a regular
|
| 15 |
+
expression. The ``chars()`` and ``words()`` methods are used to implement the
|
| 16 |
+
:tfilter:`truncatechars_html` and :tfilter:`truncatewords_html` template
|
| 17 |
+
filters, which were thus vulnerable.
|
| 18 |
+
|
| 19 |
+
The regular expressions used by ``Truncator`` have been simplified in order to
|
| 20 |
+
avoid potential backtracking issues. As a consequence, trailing punctuation may
|
| 21 |
+
now at times be included in the truncated output.
|
| 22 |
+
|
| 23 |
+
CVE-2019-14233: Denial-of-service possibility in ``strip_tags()``
|
| 24 |
+
=================================================================
|
| 25 |
+
|
| 26 |
+
Due to the behavior of the underlying ``HTMLParser``,
|
| 27 |
+
:func:`django.utils.html.strip_tags` would be extremely slow to evaluate
|
| 28 |
+
certain inputs containing large sequences of nested incomplete HTML entities.
|
| 29 |
+
The ``strip_tags()`` method is used to implement the corresponding
|
| 30 |
+
:tfilter:`striptags` template filter, which was thus also vulnerable.
|
| 31 |
+
|
| 32 |
+
``strip_tags()`` now avoids recursive calls to ``HTMLParser`` when progress
|
| 33 |
+
removing tags, but necessarily incomplete HTML entities, stops being made.
|
| 34 |
+
|
| 35 |
+
Remember that absolutely NO guarantee is provided about the results of
|
| 36 |
+
``strip_tags()`` being HTML safe. So NEVER mark safe the result of a
|
| 37 |
+
``strip_tags()`` call without escaping it first, for example with
|
| 38 |
+
:func:`django.utils.html.escape`.
|
| 39 |
+
|
| 40 |
+
CVE-2019-14234: SQL injection possibility in key and index lookups for ``JSONField``/``HStoreField``
|
| 41 |
+
====================================================================================================
|
| 42 |
+
|
| 43 |
+
:lookup:`Key and index lookups <jsonfield.key>` for
|
| 44 |
+
``django.contrib.postgres.fields.JSONField`` and :lookup:`key lookups
|
| 45 |
+
<hstorefield.key>` for :class:`~django.contrib.postgres.fields.HStoreField`
|
| 46 |
+
were subject to SQL injection, using a suitably crafted dictionary, with
|
| 47 |
+
dictionary expansion, as the ``**kwargs`` passed to ``QuerySet.filter()``.
|
| 48 |
+
|
| 49 |
+
CVE-2019-14235: Potential memory exhaustion in ``django.utils.encoding.uri_to_iri()``
|
| 50 |
+
=====================================================================================
|
| 51 |
+
|
| 52 |
+
If passed certain inputs, :func:`django.utils.encoding.uri_to_iri` could lead
|
| 53 |
+
to significant memory usage due to excessive recursion when re-percent-encoding
|
| 54 |
+
invalid UTF-8 octet sequences.
|
| 55 |
+
|
| 56 |
+
``uri_to_iri()`` now avoids recursion when re-percent-encoding invalid UTF-8
|
| 57 |
+
octet sequences.
|
testbed/django__django/docs/releases/1.11.24.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.24 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*September 2, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.24 fixes a regression in 1.11.23.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed crash of ``KeyTransform()`` for
|
| 13 |
+
``django.contrib.postgres.fields.JSONField`` and
|
| 14 |
+
:class:`~django.contrib.postgres.fields.HStoreField` when using on
|
| 15 |
+
expressions with params (:ticket:`30672`).
|
testbed/django__django/docs/releases/1.11.25.txt
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.25 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*October 1, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.25 fixes a regression in 1.11.23.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a crash when filtering with a ``Subquery()`` annotation of a queryset
|
| 13 |
+
containing ``django.contrib.postgres.fields.JSONField`` or
|
| 14 |
+
:class:`~django.contrib.postgres.fields.HStoreField` (:ticket:`30769`).
|
testbed/django__django/docs/releases/1.11.26.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.26 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*November 4, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.26 fixes a regression in 1.11.25.
|
| 8 |
+
|
| 9 |
+
Bugfixes
|
| 10 |
+
========
|
| 11 |
+
|
| 12 |
+
* Fixed a crash when using a ``contains``, ``contained_by``, ``has_key``,
|
| 13 |
+
``has_keys``, or ``has_any_keys`` lookup on
|
| 14 |
+
``django.contrib.postgres.fields.JSONField``, if the right or left hand
|
| 15 |
+
side of an expression is a key transform (:ticket:`30826`).
|
testbed/django__django/docs/releases/1.11.27.txt
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.27 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*December 18, 2019*
|
| 6 |
+
|
| 7 |
+
Django 1.11.27 fixes a security issue and a data loss bug in 1.11.26.
|
| 8 |
+
|
| 9 |
+
CVE-2019-19844: Potential account hijack via password reset form
|
| 10 |
+
================================================================
|
| 11 |
+
|
| 12 |
+
By submitting a suitably crafted email address making use of Unicode
|
| 13 |
+
characters, that compared equal to an existing user email when lower-cased for
|
| 14 |
+
comparison, an attacker could be sent a password reset token for the matched
|
| 15 |
+
account.
|
| 16 |
+
|
| 17 |
+
In order to avoid this vulnerability, password reset requests now compare the
|
| 18 |
+
submitted email using the stricter, recommended algorithm for case-insensitive
|
| 19 |
+
comparison of two identifiers from `Unicode Technical Report 36, section
|
| 20 |
+
2.11.2(B)(2)`__. Upon a match, the email containing the reset token will be
|
| 21 |
+
sent to the email address on record rather than the submitted address.
|
| 22 |
+
|
| 23 |
+
.. __: https://www.unicode.org/reports/tr36/#Recommendations_General
|
| 24 |
+
|
| 25 |
+
Bugfixes
|
| 26 |
+
========
|
| 27 |
+
|
| 28 |
+
* Fixed a data loss possibility in
|
| 29 |
+
:class:`~django.contrib.postgres.forms.SplitArrayField`. When using with
|
| 30 |
+
``ArrayField(BooleanField())``, all values after the first ``True`` value
|
| 31 |
+
were marked as checked instead of preserving passed values (:ticket:`31073`).
|
testbed/django__django/docs/releases/1.11.28.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.28 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*February 3, 2020*
|
| 6 |
+
|
| 7 |
+
Django 1.11.28 fixes a security issue in 1.11.27.
|
| 8 |
+
|
| 9 |
+
CVE-2020-7471: Potential SQL injection via ``StringAgg(delimiter)``
|
| 10 |
+
===================================================================
|
| 11 |
+
|
| 12 |
+
:class:`~django.contrib.postgres.aggregates.StringAgg` aggregation function was
|
| 13 |
+
subject to SQL injection, using a suitably crafted ``delimiter``.
|
testbed/django__django/docs/releases/1.11.29.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
============================
|
| 2 |
+
Django 1.11.29 release notes
|
| 3 |
+
============================
|
| 4 |
+
|
| 5 |
+
*March 4, 2020*
|
| 6 |
+
|
| 7 |
+
Django 1.11.29 fixes a security issue in 1.11.28.
|
| 8 |
+
|
| 9 |
+
CVE-2020-9402: Potential SQL injection via ``tolerance`` parameter in GIS functions and aggregates on Oracle
|
| 10 |
+
============================================================================================================
|
| 11 |
+
|
| 12 |
+
GIS functions and aggregates on Oracle were subject to SQL injection,
|
| 13 |
+
using a suitably crafted ``tolerance``.
|