mirror of
https://github.com/django/django.git
synced 2025-10-23 21:59:11 +00:00
Refs #36485 -- Rewrapped docs to 79 columns line length.
Lines in the docs files were manually adjusted to conform to the 79 columns limit per line (plus newline), improving readability and consistency across the content.
This commit is contained in:
@@ -37,9 +37,9 @@ Using CSRF protection with AJAX
|
||||
===============================
|
||||
|
||||
While the above method can be used for AJAX POST requests, it has some
|
||||
inconveniences: you have to remember to pass the CSRF token in as POST data with
|
||||
every POST request. For this reason, there is an alternative method: on each
|
||||
XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
|
||||
inconveniences: you have to remember to pass the CSRF token in as POST data
|
||||
with every POST request. For this reason, there is an alternative method: on
|
||||
each XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
|
||||
:setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is
|
||||
often easier because many JavaScript frameworks provide hooks that allow
|
||||
headers to be set on every request.
|
||||
@@ -217,11 +217,11 @@ Testing and CSRF protection
|
||||
===========================
|
||||
|
||||
The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
|
||||
functions, due to the need for the CSRF token which must be sent with every POST
|
||||
request. For this reason, Django's HTTP client for tests has been modified to
|
||||
set a flag on requests which relaxes the middleware and the ``csrf_protect``
|
||||
decorator so that they no longer rejects requests. In every other respect
|
||||
(e.g. sending cookies etc.), they behave the same.
|
||||
functions, due to the need for the CSRF token which must be sent with every
|
||||
POST request. For this reason, Django's HTTP client for tests has been modified
|
||||
to set a flag on requests which relaxes the middleware and the ``csrf_protect``
|
||||
decorator so that they no longer rejects requests. In every other respect (e.g.
|
||||
sending cookies etc.), they behave the same.
|
||||
|
||||
If, for some reason, you *want* the test client to perform CSRF
|
||||
checks, you can create an instance of the test client that enforces
|
||||
@@ -237,8 +237,8 @@ Edge cases
|
||||
|
||||
Certain views can have unusual requirements that mean they don't fit the normal
|
||||
pattern envisaged here. A number of utilities can be useful in these
|
||||
situations. The scenarios they might be needed in are described in the following
|
||||
section.
|
||||
situations. The scenarios they might be needed in are described in the
|
||||
following section.
|
||||
|
||||
Disabling CSRF protection for just a few views
|
||||
----------------------------------------------
|
||||
@@ -265,8 +265,8 @@ There may be some views that are unprotected and have been exempted by
|
||||
``csrf_exempt``, but still need to include the CSRF token.
|
||||
|
||||
Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
|
||||
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
|
||||
should be the innermost decorator).
|
||||
:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e.
|
||||
``requires_csrf_token`` should be the innermost decorator).
|
||||
|
||||
Protecting a view for only one path
|
||||
-----------------------------------
|
||||
@@ -304,8 +304,8 @@ view that sends the page.
|
||||
CSRF protection in reusable applications
|
||||
========================================
|
||||
|
||||
Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
|
||||
all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
|
||||
the security of these applications against CSRF. It is recommended that the
|
||||
developers of other reusable apps that want the same guarantees also use the
|
||||
``csrf_protect`` decorator on their views.
|
||||
Because it is possible for the developer to turn off the
|
||||
``CsrfViewMiddleware``, all relevant views in contrib apps use the
|
||||
``csrf_protect`` decorator to ensure the security of these applications against
|
||||
CSRF. It is recommended that the developers of other reusable apps that want
|
||||
the same guarantees also use the ``csrf_protect`` decorator on their views.
|
||||
|
||||
@@ -16,8 +16,9 @@ You'll need to follow these steps:
|
||||
|
||||
class MyStorage(Storage): ...
|
||||
|
||||
#. Django must be able to instantiate your storage system without any arguments.
|
||||
This means that any settings should be taken from ``django.conf.settings``::
|
||||
#. Django must be able to instantiate your storage system without any
|
||||
arguments. This means that any settings should be taken from
|
||||
``django.conf.settings``::
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.files.storage import Storage
|
||||
@@ -36,10 +37,10 @@ You'll need to follow these steps:
|
||||
In addition, if your class provides local file storage, it must override
|
||||
the ``path()`` method.
|
||||
|
||||
#. Your storage class must be :ref:`deconstructible <custom-deconstruct-method>`
|
||||
so it can be serialized when it's used on a field in a migration. As long
|
||||
as your field has arguments that are themselves
|
||||
:ref:`serializable <migration-serializing>`, you can use the
|
||||
#. Your storage class must be :ref:`deconstructible
|
||||
<custom-deconstruct-method>` so it can be serialized when it's used on a
|
||||
field in a migration. As long as your field has arguments that are
|
||||
themselves :ref:`serializable <migration-serializing>`, you can use the
|
||||
``django.utils.deconstruct.deconstructible`` class decorator for this
|
||||
(that's what Django uses on FileSystemStorage).
|
||||
|
||||
@@ -73,16 +74,16 @@ objects. These are:
|
||||
**Required**.
|
||||
|
||||
Called by ``Storage.open()``, this is the actual mechanism the storage class
|
||||
uses to open the file. This must return a ``File`` object, though in most cases,
|
||||
you'll want to return some subclass here that implements logic specific to the
|
||||
backend storage system. The :exc:`FileNotFoundError` exception should be raised
|
||||
when a file doesn't exist.
|
||||
uses to open the file. This must return a ``File`` object, though in most
|
||||
cases, you'll want to return some subclass here that implements logic specific
|
||||
to the backend storage system. The :exc:`FileNotFoundError` exception should be
|
||||
raised when a file doesn't exist.
|
||||
|
||||
.. method:: _save(name, content)
|
||||
|
||||
Called by ``Storage.save()``. The ``name`` will already have gone through
|
||||
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
|
||||
``File`` object itself.
|
||||
``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be
|
||||
a ``File`` object itself.
|
||||
|
||||
Should return the actual name of the file saved (usually the ``name`` passed
|
||||
in, but if the storage needs to change the file name return the new name
|
||||
|
||||
@@ -39,9 +39,9 @@ lookup, then we need to tell Django about it::
|
||||
return "%s <> %s" % (lhs, rhs), params
|
||||
|
||||
To register the ``NotEqual`` lookup we will need to call ``register_lookup`` on
|
||||
the field class we want the lookup to be available for. In this case, the lookup
|
||||
makes sense on all ``Field`` subclasses, so we register it with ``Field``
|
||||
directly::
|
||||
the field class we want the lookup to be available for. In this case, the
|
||||
lookup makes sense on all ``Field`` subclasses, so we register it with
|
||||
``Field`` directly::
|
||||
|
||||
from django.db.models import Field
|
||||
|
||||
@@ -61,10 +61,10 @@ could place the implementation in a ``models.py`` file, or register the lookup
|
||||
in the ``ready()`` method of an ``AppConfig``.
|
||||
|
||||
Taking a closer look at the implementation, the first required attribute is
|
||||
``lookup_name``. This allows the ORM to understand how to interpret ``name__ne``
|
||||
and use ``NotEqual`` to generate the SQL. By convention, these names are always
|
||||
lowercase strings containing only letters, but the only hard requirement is
|
||||
that it must not contain the string ``__``.
|
||||
``lookup_name``. This allows the ORM to understand how to interpret
|
||||
``name__ne`` and use ``NotEqual`` to generate the SQL. By convention, these
|
||||
names are always lowercase strings containing only letters, but the only hard
|
||||
requirement is that it must not contain the string ``__``.
|
||||
|
||||
We then need to define the ``as_sql`` method. This takes a ``SQLCompiler``
|
||||
object, called ``compiler``, and the active database connection.
|
||||
@@ -112,8 +112,8 @@ or where it did not exceed a certain amount
|
||||
functionality which is possible in a database backend independent manner,
|
||||
and without duplicating functionality already in Django.
|
||||
|
||||
We will start by writing an ``AbsoluteValue`` transformer. This will use the SQL
|
||||
function ``ABS()`` to transform the value before comparison::
|
||||
We will start by writing an ``AbsoluteValue`` transformer. This will use the
|
||||
SQL function ``ABS()`` to transform the value before comparison::
|
||||
|
||||
from django.db.models import Transform
|
||||
|
||||
@@ -227,16 +227,16 @@ Notice also that as both sides are used multiple times in the query the params
|
||||
need to contain ``lhs_params`` and ``rhs_params`` multiple times.
|
||||
|
||||
The final query does the inversion (``27`` to ``-27``) directly in the
|
||||
database. The reason for doing this is that if the ``self.rhs`` is something else
|
||||
than a plain integer value (for example an ``F()`` reference) we can't do the
|
||||
transformations in Python.
|
||||
database. The reason for doing this is that if the ``self.rhs`` is something
|
||||
else than a plain integer value (for example an ``F()`` reference) we can't do
|
||||
the transformations in Python.
|
||||
|
||||
.. note::
|
||||
In fact, most lookups with ``__abs`` could be implemented as range queries
|
||||
like this, and on most database backends it is likely to be more sensible to
|
||||
do so as you can make use of the indexes. However with PostgreSQL you may
|
||||
want to add an index on ``abs(change)`` which would allow these queries to
|
||||
be very efficient.
|
||||
like this, and on most database backends it is likely to be more sensible
|
||||
to do so as you can make use of the indexes. However with PostgreSQL you
|
||||
may want to add an index on ``abs(change)`` which would allow these queries
|
||||
to be very efficient.
|
||||
|
||||
A bilateral transformer example
|
||||
===============================
|
||||
@@ -252,10 +252,10 @@ very useful in practice as Django already comes with a bunch of built-in
|
||||
case-insensitive lookups, but it will be a nice demonstration of bilateral
|
||||
transformations in a database-agnostic way.
|
||||
|
||||
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to
|
||||
transform the values before comparison. We define
|
||||
:attr:`bilateral = True <django.db.models.Transform.bilateral>` to indicate that
|
||||
this transformation should apply to both ``lhs`` and ``rhs``::
|
||||
We define an ``UpperCase`` transformer which uses the SQL function ``UPPER()``
|
||||
to transform the values before comparison. We define :attr:`bilateral = True
|
||||
<django.db.models.Transform.bilateral>` to indicate that this transformation
|
||||
should apply to both ``lhs`` and ``rhs``::
|
||||
|
||||
from django.db.models import Transform
|
||||
|
||||
@@ -272,8 +272,8 @@ Next, let's register it::
|
||||
CharField.register_lookup(UpperCase)
|
||||
TextField.register_lookup(UpperCase)
|
||||
|
||||
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a case
|
||||
insensitive query like this:
|
||||
Now, the queryset ``Author.objects.filter(name__upper="doe")`` will generate a
|
||||
case insensitive query like this:
|
||||
|
||||
.. code-block:: sql
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ whose name doesn't begin with an underscore. For example:
|
||||
tests.py
|
||||
views.py
|
||||
|
||||
In this example, the ``closepoll`` command will be made available to any project
|
||||
that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
|
||||
In this example, the ``closepoll`` command will be made available to any
|
||||
project that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
|
||||
|
||||
The ``_private.py`` module will not be available as a management command.
|
||||
|
||||
@@ -73,13 +73,12 @@ look like this::
|
||||
.. _management-commands-output:
|
||||
|
||||
.. note::
|
||||
When you are using management commands and wish to provide console
|
||||
output, you should write to ``self.stdout`` and ``self.stderr``,
|
||||
instead of printing to ``stdout`` and ``stderr`` directly. By
|
||||
using these proxies, it becomes much easier to test your custom
|
||||
command. Note also that you don't need to end messages with a newline
|
||||
character, it will be added automatically, unless you specify the ``ending``
|
||||
parameter::
|
||||
When you are using management commands and wish to provide console output,
|
||||
you should write to ``self.stdout`` and ``self.stderr``, instead of
|
||||
printing to ``stdout`` and ``stderr`` directly. By using these proxies, it
|
||||
becomes much easier to test your custom command. Note also that you don't
|
||||
need to end messages with a newline character, it will be added
|
||||
automatically, unless you specify the ``ending`` parameter::
|
||||
|
||||
self.stdout.write("Unterminated line", ending="")
|
||||
|
||||
@@ -99,7 +98,8 @@ Accepting optional arguments
|
||||
|
||||
The same ``closepoll`` could be easily modified to delete a given poll instead
|
||||
of closing it by accepting additional command line options. These custom
|
||||
options can be added in the :meth:`~BaseCommand.add_arguments` method like this::
|
||||
options can be added in the :meth:`~BaseCommand.add_arguments` method like
|
||||
this::
|
||||
|
||||
class Command(BaseCommand):
|
||||
def add_arguments(self, parser):
|
||||
@@ -273,7 +273,8 @@ the :meth:`~BaseCommand.handle` method must be implemented.
|
||||
Django.
|
||||
|
||||
You can customize the instance by overriding this method and calling
|
||||
``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters.
|
||||
``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser`
|
||||
parameters.
|
||||
|
||||
.. method:: BaseCommand.add_arguments(parser)
|
||||
|
||||
|
||||
@@ -7,17 +7,18 @@ How to create custom model fields
|
||||
Introduction
|
||||
============
|
||||
|
||||
The :doc:`model reference </topics/db/models>` documentation explains how to use
|
||||
Django's standard field classes -- :class:`~django.db.models.CharField`,
|
||||
The :doc:`model reference </topics/db/models>` documentation explains how to
|
||||
use Django's standard field classes -- :class:`~django.db.models.CharField`,
|
||||
:class:`~django.db.models.DateField`, etc. For many purposes, those classes are
|
||||
all you'll need. Sometimes, though, the Django version won't meet your precise
|
||||
requirements, or you'll want to use a field that is entirely different from
|
||||
those shipped with Django.
|
||||
|
||||
Django's built-in field types don't cover every possible database column type --
|
||||
only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
|
||||
Django's built-in field types don't cover every possible database column type
|
||||
-- only the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure
|
||||
column types, such as geographic polygons or even user-created types such as
|
||||
`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.
|
||||
`PostgreSQL custom types`_, you can define your own Django ``Field``
|
||||
subclasses.
|
||||
|
||||
.. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html
|
||||
|
||||
@@ -106,13 +107,13 @@ What does a field class do?
|
||||
---------------------------
|
||||
|
||||
All of Django's fields (and when we say *fields* in this document, we always
|
||||
mean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses
|
||||
of :class:`django.db.models.Field`. Most of the information that Django records
|
||||
about a field is common to all fields -- name, help text, uniqueness and so
|
||||
forth. Storing all that information is handled by ``Field``. We'll get into the
|
||||
precise details of what ``Field`` can do later on; for now, suffice it to say
|
||||
that everything descends from ``Field`` and then customizes key pieces of the
|
||||
class behavior.
|
||||
mean model fields and not :doc:`form fields </ref/forms/fields>`) are
|
||||
subclasses of :class:`django.db.models.Field`. Most of the information that
|
||||
Django records about a field is common to all fields -- name, help text,
|
||||
uniqueness and so forth. Storing all that information is handled by ``Field``.
|
||||
We'll get into the precise details of what ``Field`` can do later on; for now,
|
||||
suffice it to say that everything descends from ``Field`` and then customizes
|
||||
key pieces of the class behavior.
|
||||
|
||||
It's important to realize that a Django field class is not what is stored in
|
||||
your model attributes. The model attributes contain normal Python objects. The
|
||||
@@ -149,9 +150,9 @@ is most similar to. Can you subclass an existing Django field and save yourself
|
||||
some work? If not, you should subclass the :class:`~django.db.models.Field`
|
||||
class, from which everything is descended.
|
||||
|
||||
Initializing your new field is a matter of separating out any arguments that are
|
||||
specific to your case from the common arguments and passing the latter to the
|
||||
``__init__()`` method of :class:`~django.db.models.Field` (or your parent
|
||||
Initializing your new field is a matter of separating out any arguments that
|
||||
are specific to your case from the common arguments and passing the latter to
|
||||
the ``__init__()`` method of :class:`~django.db.models.Field` (or your parent
|
||||
class).
|
||||
|
||||
In our example, we'll call our field ``HandField``. (It's a good idea to call
|
||||
@@ -214,9 +215,9 @@ The ``Field.__init__()`` method takes the following parameters:
|
||||
* :attr:`~django.db.models.Field.choices`
|
||||
* :attr:`~django.db.models.Field.help_text`
|
||||
* :attr:`~django.db.models.Field.db_column`
|
||||
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
|
||||
backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
|
||||
ignore this option.
|
||||
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if
|
||||
the backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can
|
||||
usually ignore this option.
|
||||
* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was
|
||||
automatically created, as for the :class:`~django.db.models.OneToOneField`
|
||||
used by model inheritance. For advanced use only.
|
||||
@@ -253,9 +254,9 @@ name and import path. You do, however, have to care about the positional
|
||||
and keyword arguments, as these are likely the things you are changing.
|
||||
|
||||
For example, in our ``HandField`` class we're always forcibly setting
|
||||
max_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``
|
||||
class will see this and try to return it in the keyword arguments; thus,
|
||||
we can drop it from the keyword arguments for readability::
|
||||
max_length in ``__init__()``. The ``deconstruct()`` method on the base
|
||||
``Field`` class will see this and try to return it in the keyword arguments;
|
||||
thus, we can drop it from the keyword arguments for readability::
|
||||
|
||||
from django.db import models
|
||||
|
||||
@@ -471,10 +472,11 @@ over this field. You are then responsible for creating the column in the right
|
||||
table in some other way, but this gives you a way to tell Django to get out of
|
||||
the way.
|
||||
|
||||
The :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``
|
||||
and ``OneToOneField`` that point to another field to determine their database
|
||||
column data types. For example, if you have an ``UnsignedAutoField``, you also
|
||||
need the foreign keys that point to that field to use the same data type::
|
||||
The :meth:`~Field.rel_db_type` method is called by fields such as
|
||||
``ForeignKey`` and ``OneToOneField`` that point to another field to determine
|
||||
their database column data types. For example, if you have an
|
||||
``UnsignedAutoField``, you also need the foreign keys that point to that field
|
||||
to use the same data type::
|
||||
|
||||
# MySQL unsigned integer (range 0 to 4294967295).
|
||||
class UnsignedAutoField(models.AutoField):
|
||||
@@ -648,8 +650,8 @@ a custom form field (and even a form widget). See the :doc:`forms documentation
|
||||
If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you
|
||||
can override the :meth:`~Field.formfield` method to return ``None``.
|
||||
|
||||
Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
|
||||
as::
|
||||
Continuing our ongoing example, we can write the :meth:`~Field.formfield`
|
||||
method as::
|
||||
|
||||
class HandField(models.Field):
|
||||
# ...
|
||||
|
||||
@@ -285,13 +285,13 @@ Template filter code falls into one of two situations:
|
||||
order to make things easier for your template authors.
|
||||
|
||||
In order for your filter to know the current auto-escaping state, set the
|
||||
``needs_autoescape`` flag to ``True`` when you register your filter function.
|
||||
(If you don't specify this flag, it defaults to ``False``). This flag tells
|
||||
Django that your filter function wants to be passed an extra keyword
|
||||
argument, called ``autoescape``, that is ``True`` if auto-escaping is in
|
||||
effect and ``False`` otherwise. It is recommended to set the default of the
|
||||
``autoescape`` parameter to ``True``, so that if you call the function
|
||||
from Python code it will have escaping enabled by default.
|
||||
``needs_autoescape`` flag to ``True`` when you register your filter
|
||||
function. (If you don't specify this flag, it defaults to ``False``). This
|
||||
flag tells Django that your filter function wants to be passed an extra
|
||||
keyword argument, called ``autoescape``, that is ``True`` if auto-escaping
|
||||
is in effect and ``False`` otherwise. It is recommended to set the default
|
||||
of the ``autoescape`` parameter to ``True``, so that if you call the
|
||||
function from Python code it will have escaping enabled by default.
|
||||
|
||||
For example, let's write a filter that emphasizes the first character of
|
||||
a string::
|
||||
@@ -827,8 +827,8 @@ Advanced custom template tags
|
||||
-----------------------------
|
||||
|
||||
Sometimes the basic features for custom template tag creation aren't enough.
|
||||
Don't worry, Django gives you complete access to the internals required to build
|
||||
a template tag from the ground up.
|
||||
Don't worry, Django gives you complete access to the internals required to
|
||||
build a template tag from the ground up.
|
||||
|
||||
A quick overview
|
||||
----------------
|
||||
@@ -856,10 +856,10 @@ function with the tag contents and the parser object itself. This function is
|
||||
responsible for returning a ``Node`` instance based on the contents of the tag.
|
||||
|
||||
For example, let's write a full implementation of our template tag,
|
||||
``{% current_time %}``, that displays the current date/time, formatted according
|
||||
to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good
|
||||
idea to decide the tag syntax before anything else. In our case, let's say the
|
||||
tag should be used like this:
|
||||
``{% current_time %}``, that displays the current date/time, formatted
|
||||
according to a parameter given in the tag, in :func:`~time.strftime` syntax.
|
||||
It's a good idea to decide the tag syntax before anything else. In our case,
|
||||
let's say the tag should be used like this:
|
||||
|
||||
.. code-block:: html+django
|
||||
|
||||
@@ -1300,9 +1300,10 @@ Here's how a simplified ``{% comment %}`` tag might be implemented::
|
||||
The actual implementation of :ttag:`{% comment %}<comment>` is slightly
|
||||
different in that it allows broken template tags to appear between
|
||||
``{% comment %}`` and ``{% endcomment %}``. It does so by calling
|
||||
``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))``
|
||||
followed by ``parser.delete_first_token()``, thus avoiding the generation of a
|
||||
node list.
|
||||
``parser.skip_past('endcomment')`` instead of
|
||||
``parser.parse(('endcomment',))`` followed by
|
||||
``parser.delete_first_token()``, thus avoiding the generation of a node
|
||||
list.
|
||||
|
||||
``parser.parse()`` takes a tuple of names of block tags *to parse until*. It
|
||||
returns an instance of ``django.template.NodeList``, which is a list of
|
||||
|
||||
@@ -40,8 +40,9 @@ For more advanced usage, please read the `Uvicorn documentation <Uvicorn_>`_.
|
||||
Deploying Django using Uvicorn and Gunicorn
|
||||
===========================================
|
||||
|
||||
Gunicorn_ is a robust web server that implements process monitoring and automatic
|
||||
restarts. This can be useful when running Uvicorn in a production environment.
|
||||
Gunicorn_ is a robust web server that implements process monitoring and
|
||||
automatic restarts. This can be useful when running Uvicorn in a production
|
||||
environment.
|
||||
|
||||
To install Uvicorn and Gunicorn, use the following:
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
How to authenticate against Django's user database from Apache
|
||||
==============================================================
|
||||
|
||||
Since keeping multiple authentication databases in sync is a common problem when
|
||||
dealing with Apache, you can configure Apache to authenticate against Django's
|
||||
:doc:`authentication system </topics/auth/index>` directly. This requires Apache
|
||||
version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
|
||||
Since keeping multiple authentication databases in sync is a common problem
|
||||
when dealing with Apache, you can configure Apache to authenticate against
|
||||
Django's :doc:`authentication system </topics/auth/index>` directly. This
|
||||
requires Apache version >= 2.2 and mod_wsgi >= 2.0. For example, you could:
|
||||
|
||||
* Serve static/media files directly from Apache only to authenticated users.
|
||||
|
||||
|
||||
@@ -37,9 +37,9 @@ deployments.
|
||||
|
||||
WSGI servers obtain the path to the ``application`` callable from their
|
||||
configuration. Django's built-in server, namely the :djadmin:`runserver`
|
||||
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's
|
||||
set to ``<project_name>.wsgi.application``, which points to the ``application``
|
||||
callable in :file:`<project_name>/wsgi.py`.
|
||||
command, reads it from the :setting:`WSGI_APPLICATION` setting. By default,
|
||||
it's set to ``<project_name>.wsgi.application``, which points to the
|
||||
``application`` callable in :file:`<project_name>/wsgi.py`.
|
||||
|
||||
Configuring the settings module
|
||||
===============================
|
||||
|
||||
@@ -124,8 +124,8 @@ use ``WSGIPythonPath``; instead you should use the ``python-path`` option to
|
||||
WSGIProcessGroup example.com
|
||||
|
||||
If you want to serve your project in a subdirectory
|
||||
(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias``
|
||||
to the configuration above:
|
||||
(``https://example.com/mysite`` in this example), you can add
|
||||
``WSGIScriptAlias`` to the configuration above:
|
||||
|
||||
.. code-block:: apache
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ How to manage error reporting
|
||||
|
||||
When you're running a public site you should always turn off the
|
||||
:setting:`DEBUG` setting. That will make your server run much faster, and will
|
||||
also prevent malicious users from seeing details of your application that can be
|
||||
revealed by the error pages.
|
||||
also prevent malicious users from seeing details of your application that can
|
||||
be revealed by the error pages.
|
||||
|
||||
However, running with :setting:`DEBUG` set to ``False`` means you'll never see
|
||||
errors generated by your site -- everyone will instead see your public error
|
||||
@@ -87,11 +87,11 @@ regular expression objects. For example::
|
||||
re.compile(r"^/phpmyadmin/"),
|
||||
]
|
||||
|
||||
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
|
||||
reported. Neither will any URL starting with ``/phpmyadmin/``.
|
||||
In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not*
|
||||
be reported. Neither will any URL starting with ``/phpmyadmin/``.
|
||||
|
||||
The following example shows how to exclude some conventional URLs that browsers and
|
||||
crawlers often request::
|
||||
The following example shows how to exclude some conventional URLs that browsers
|
||||
and crawlers often request::
|
||||
|
||||
import re
|
||||
|
||||
@@ -220,7 +220,8 @@ filtered out of error reports in a production environment (that is, where
|
||||
disclosed.
|
||||
|
||||
To systematically hide all POST parameters of a request in error reports,
|
||||
do not provide any argument to the ``sensitive_post_parameters`` decorator::
|
||||
do not provide any argument to the ``sensitive_post_parameters``
|
||||
decorator::
|
||||
|
||||
@sensitive_post_parameters()
|
||||
def my_view(request): ...
|
||||
@@ -379,5 +380,5 @@ within any given view by setting the ``HttpRequest``’s
|
||||
|
||||
You can also set up custom error reporting by writing a custom piece of
|
||||
:ref:`exception middleware <exception-middleware>`. If you do write custom
|
||||
error handling, it's a good idea to emulate Django's built-in error handling
|
||||
and only report/log errors if :setting:`DEBUG` is ``False``.
|
||||
error handling, it's a good idea to emulate Django's built-in error
|
||||
handling and only report/log errors if :setting:`DEBUG` is ``False``.
|
||||
|
||||
@@ -26,8 +26,8 @@ however, this data isn't loaded automatically, except if you use
|
||||
A fixture is a collection of data that Django knows how to import into a
|
||||
database. The most straightforward way of creating a fixture if you've already
|
||||
got some data is to use the :djadmin:`manage.py dumpdata <dumpdata>` command.
|
||||
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML
|
||||
(with PyYAML_ installed) documents. The :doc:`serialization documentation
|
||||
Or, you can write fixtures by hand; fixtures can be written as JSON, XML or
|
||||
YAML (with PyYAML_ installed) documents. The :doc:`serialization documentation
|
||||
</topics/serialization>` has more details about each of these supported
|
||||
:ref:`serialization formats <serialization-formats>`.
|
||||
|
||||
|
||||
@@ -44,8 +44,8 @@ Save this as a file by using standard Unix output redirection:
|
||||
|
||||
$ python manage.py inspectdb > models.py
|
||||
|
||||
This feature is meant as a shortcut, not as definitive model generation. See the
|
||||
:djadmin:`documentation of inspectdb <inspectdb>` for more information.
|
||||
This feature is meant as a shortcut, not as definitive model generation. See
|
||||
the :djadmin:`documentation of inspectdb <inspectdb>` for more information.
|
||||
|
||||
Once you've cleaned up your models, name the file ``models.py`` and put it in
|
||||
the Python package that holds your app. Then add the app to your
|
||||
|
||||
@@ -3,8 +3,8 @@ How to create CSV output
|
||||
========================
|
||||
|
||||
This document explains how to output CSV (Comma Separated Values) dynamically
|
||||
using Django views. To do this, you can either use the Python CSV library or the
|
||||
Django template system.
|
||||
using Django views. To do this, you can either use the Python CSV library or
|
||||
the Django template system.
|
||||
|
||||
Using the Python CSV library
|
||||
============================
|
||||
@@ -101,9 +101,10 @@ the assembly and transmission of a large CSV file::
|
||||
Using the template system
|
||||
=========================
|
||||
|
||||
Alternatively, you can use the :doc:`Django template system </topics/templates>`
|
||||
to generate CSV. This is lower-level than using the convenient Python :mod:`csv`
|
||||
module, but the solution is presented here for completeness.
|
||||
Alternatively, you can use the :doc:`Django template system
|
||||
</topics/templates>` to generate CSV. This is lower-level than using the
|
||||
convenient Python :mod:`csv` module, but the solution is presented here for
|
||||
completeness.
|
||||
|
||||
The idea here is to pass a list of items to your template, and have the
|
||||
template output the commas in a :ttag:`for` loop.
|
||||
|
||||
@@ -87,8 +87,8 @@ mention:
|
||||
browsers will handle the PDF using whatever program/plugin they've been
|
||||
configured to use for PDFs.
|
||||
|
||||
* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers
|
||||
in the "Save as..." dialog.
|
||||
* You can provide an arbitrary ``filename`` parameter. It'll be used by
|
||||
browsers in the "Save as..." dialog.
|
||||
|
||||
* You can hook into the ReportLab API: The same buffer passed as the first
|
||||
argument to ``canvas.Canvas`` can be fed to the
|
||||
@@ -112,8 +112,8 @@ Other formats
|
||||
Notice that there isn't a lot in these examples that's PDF-specific -- just the
|
||||
bits using ``reportlab``. You can use a similar technique to generate any
|
||||
arbitrary format that you can find a Python library for. Also see
|
||||
:doc:`/howto/outputting-csv` for another example and some techniques you can use
|
||||
when generated text-based formats.
|
||||
:doc:`/howto/outputting-csv` for another example and some techniques you can
|
||||
use when generated text-based formats.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -63,7 +63,8 @@ in the ``templates`` directory, and add the template files to that folder:
|
||||
|
||||
The template loader first looks for templates in the ``DIRS`` directory. When
|
||||
the views in the ``blog`` app ask for the ``blog/post.html`` and
|
||||
``blog/list.html`` templates, the loader will return the files you just created.
|
||||
``blog/list.html`` templates, the loader will return the files you just
|
||||
created.
|
||||
|
||||
Overriding from an app's template directory
|
||||
===========================================
|
||||
|
||||
@@ -155,10 +155,10 @@ file-serving functionality: It doesn't know about the finders feature of the
|
||||
collected under :setting:`STATIC_ROOT`.
|
||||
|
||||
Because of this, ``staticfiles`` ships its own
|
||||
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass
|
||||
of the built-in one that has the ability to transparently serve all the assets
|
||||
during execution of these tests in a way very similar to what we get at
|
||||
development time with ``DEBUG = True``, i.e. without having to collect them
|
||||
:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a
|
||||
subclass of the built-in one that has the ability to transparently serve all
|
||||
the assets during execution of these tests in a way very similar to what we get
|
||||
at development time with ``DEBUG = True``, i.e. without having to collect them
|
||||
using :djadmin:`collectstatic` first.
|
||||
|
||||
Deployment
|
||||
|
||||
@@ -91,7 +91,8 @@ Once you're ready, it is time to :doc:`install the new Django version
|
||||
is a major upgrade, you might want to set up a new environment with all the
|
||||
dependencies first.
|
||||
|
||||
If you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` flag:
|
||||
If you installed Django with pip_, you can use the ``--upgrade`` or ``-U``
|
||||
flag:
|
||||
|
||||
.. console::
|
||||
|
||||
@@ -127,6 +128,6 @@ If you are using caching provided by Django, you should consider clearing your
|
||||
cache after upgrading. Otherwise you may run into problems, for example, if you
|
||||
are caching pickled objects as these objects are not guaranteed to be
|
||||
pickle-compatible across Django versions. A past instance of incompatibility
|
||||
was caching pickled :class:`~django.http.HttpResponse` objects, either
|
||||
directly or indirectly via the :func:`~django.views.decorators.cache.cache_page`
|
||||
was caching pickled :class:`~django.http.HttpResponse` objects, either directly
|
||||
or indirectly via the :func:`~django.views.decorators.cache.cache_page`
|
||||
decorator.
|
||||
|
||||
@@ -173,7 +173,8 @@ the respective field according to your needs.
|
||||
migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
|
||||
]
|
||||
|
||||
* Now you can apply the migrations as usual with the :djadmin:`migrate` command.
|
||||
* Now you can apply the migrations as usual with the :djadmin:`migrate`
|
||||
command.
|
||||
|
||||
Note there is a race condition if you allow objects to be created while this
|
||||
migration is running. Objects created after the ``AddField`` and before
|
||||
@@ -277,12 +278,13 @@ Migrating data between third-party apps
|
||||
You can use a data migration to move data from one third-party application to
|
||||
another.
|
||||
|
||||
If you plan to remove the old app later, you'll need to set the ``dependencies``
|
||||
property based on whether or not the old app is installed. Otherwise, you'll
|
||||
have missing dependencies once you uninstall the old app. Similarly, you'll
|
||||
need to catch :exc:`LookupError` in the ``apps.get_model()`` call that
|
||||
retrieves models from the old app. This approach allows you to deploy your
|
||||
project anywhere without first installing and then uninstalling the old app.
|
||||
If you plan to remove the old app later, you'll need to set the
|
||||
``dependencies`` property based on whether or not the old app is installed.
|
||||
Otherwise, you'll have missing dependencies once you uninstall the old app.
|
||||
Similarly, you'll need to catch :exc:`LookupError` in the ``apps.get_model()``
|
||||
call that retrieves models from the old app. This approach allows you to deploy
|
||||
your project anywhere without first installing and then uninstalling the old
|
||||
app.
|
||||
|
||||
Here's a sample migration:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user