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

Fixed #30573 -- Rephrased documentation to avoid words that minimise the involved difficulty.

This patch does not remove all occurrences of the words in question.
Rather, I went through all of the occurrences of the words listed
below, and judged if they a) suggested the reader had some kind of
knowledge/experience, and b) if they added anything of value (including
tone of voice, etc). I left most of the words alone. I looked at the
following words:

- simply/simple
- easy/easier/easiest
- obvious
- just
- merely
- straightforward
- ridiculous

Thanks to Carlton Gibson for guidance on how to approach this issue, and
to Tim Bell for providing the idea. But the enormous lion's share of
thanks go to Adam Johnson for his patient and helpful review.
This commit is contained in:
Tobias Kunze
2019-06-17 16:54:55 +02:00
committed by Mariusz Felisiak
parent addabc492b
commit 4a954cfd11
149 changed files with 1101 additions and 1157 deletions

View File

@@ -8,7 +8,7 @@ Django contains a registry of installed applications that stores configuration
and provides introspection. It also maintains a list of available :doc:`models
</topics/db/models>`.
This registry is simply called :attr:`~django.apps.apps` and it's available in
This registry is called :attr:`~django.apps.apps` and it's available in
:mod:`django.apps`::
>>> from django.apps import apps
@@ -40,7 +40,7 @@ projects with the :setting:`INSTALLED_APPS` setting and optionally with other
mechanisms such as URLconfs, the :setting:`MIDDLEWARE` setting, or template
inheritance.
It is important to understand that a Django application is just a set of code
It is important to understand that a Django application is a set of code
that interacts with various parts of the framework. There's no such thing as
an ``Application`` object. However, there's a few places where Django needs to
interact with installed applications, mainly for configuration and also for
@@ -59,9 +59,8 @@ Configuring applications
To configure an application, subclass :class:`~django.apps.AppConfig` and put
the dotted path to that subclass in :setting:`INSTALLED_APPS`.
When :setting:`INSTALLED_APPS` simply contains the dotted path to an
application module, Django checks for a ``default_app_config`` variable in
that module.
When :setting:`INSTALLED_APPS` contains the dotted path to an application
module, Django checks for a ``default_app_config`` variable in that module.
If it's defined, it's the dotted path to the :class:`~django.apps.AppConfig`
subclass for that application.
@@ -99,11 +98,11 @@ subclass by default as follows::
default_app_config = 'rock_n_roll.apps.RockNRollConfig'
That will cause ``RockNRollConfig`` to be used when :setting:`INSTALLED_APPS`
just contains ``'rock_n_roll'``. This allows you to make use of
:class:`~django.apps.AppConfig` features without requiring your users to
update their :setting:`INSTALLED_APPS` setting. Besides this use case, it's
best to avoid using ``default_app_config`` and instead specify the app config
class in :setting:`INSTALLED_APPS` as described next.
contains ``'rock_n_roll'``. This allows you to make use of
:class:`~django.apps.AppConfig` features without requiring your users to update
their :setting:`INSTALLED_APPS` setting. Besides this use case, it's best to
avoid using ``default_app_config`` and instead specify the app config class in
:setting:`INSTALLED_APPS` as described next.
Of course, you can also tell your users to put
``'rock_n_roll.apps.RockNRollConfig'`` in their :setting:`INSTALLED_APPS`

View File

@@ -325,8 +325,8 @@ Security
The security checks do not make your site secure. They do not audit code, do
intrusion detection, or do anything particularly complex. Rather, they help
perform an automated, low-hanging-fruit checklist. They help you remember the
simple things that improve your site's security.
perform an automated, low-hanging-fruit checklist, that can help you to improve
your site's security.
Some of these checks may not be appropriate for your particular deployment
configuration. For instance, if you do your HTTP to HTTPS redirection in a load

View File

@@ -332,5 +332,5 @@ Date-based mixins
return the list of years for which ``qs`` has entries. If
``date_type`` isn't provided, the result of
:meth:`~BaseDateListView.get_date_list_period` is used. ``date_type``
and ``ordering`` are simply passed to
and ``ordering`` are passed to
:meth:`QuerySet.dates()<django.db.models.query.QuerySet.dates>`.

View File

@@ -209,8 +209,8 @@ The following mixins are used to construct Django's editing views:
.. method:: put(*args, **kwargs)
The ``PUT`` action is also handled and just passes all parameters
through to :meth:`post`.
The ``PUT`` action is also handled and passes all parameters through to
:meth:`post`.
``DeletionMixin``

View File

@@ -136,8 +136,7 @@ Multiple object mixins
.. method:: get_paginate_by(queryset)
Returns the number of items to paginate by, or ``None`` for no
pagination. By default this simply returns the value of
:attr:`paginate_by`.
pagination. By default this returns the value of :attr:`paginate_by`.
.. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
@@ -147,7 +146,7 @@ Multiple object mixins
.. method:: get_paginate_orphans()
An integer specifying the number of "overflow" objects the last page
can contain. By default this simply returns the value of
can contain. By default this returns the value of
:attr:`paginate_orphans`.
.. method:: get_allow_empty()

View File

@@ -12,7 +12,7 @@ Simple mixins
.. attribute:: extra_context
A dictionary to include in the context. This is a convenient way of
specifying some simple context in
specifying some context in
:meth:`~django.views.generic.base.View.as_view`. Example usage::
from django.views.generic import TemplateView

View File

@@ -63,7 +63,7 @@ Single object mixins
with access to individual objects should be prevented from obtaining
this list, setting ``query_pk_and_slug`` to ``True`` will help prevent
the guessing of URLs as each URL will require two correct,
non-sequential arguments. Simply using a unique slug may serve the same
non-sequential arguments. Using a unique slug may serve the same
purpose, but this scheme allows you to have non-unique slugs.
.. _insecure direct object reference: https://www.owasp.org/index.php/Top_10_2013-A4-Insecure_Direct_Object_References
@@ -128,7 +128,7 @@ Single object mixins
.. method:: get_slug_field()
Returns the name of a slug field to be used to look up by slug. By
default this simply returns the value of :attr:`slug_field`.
default this returns the value of :attr:`slug_field`.
``SingleObjectTemplateResponseMixin``

View File

@@ -37,10 +37,9 @@ loading in a frame no matter which site made the request.
.. _X-Frame-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
Django provides a few simple ways to include this header in responses from your
site:
Django provides a few ways to include this header in responses from your site:
#. A simple middleware that sets the header in all responses.
#. A middleware that sets the header in all responses.
#. A set of view decorators that can be used to override the middleware or to
only set the header for certain views.

View File

@@ -9,7 +9,7 @@ then change it." This works well for a majority of use cases. However, if you
need to make the same change to many objects at once, this workflow can be
quite tedious.
In these cases, Django's admin lets you write and register "actions" -- simple
In these cases, Django's admin lets you write and register "actions" --
functions that get called with a list of objects selected on the change list
page.
@@ -43,7 +43,7 @@ Writing actions
The easiest way to explain actions is by example, so let's dive in.
A common use case for admin actions is the bulk updating of a model. Imagine a
simple news application with an ``Article`` model::
news application with an ``Article`` model::
from django.db import models
@@ -71,7 +71,7 @@ Writing action functions
------------------------
First, we'll need to write a function that gets called when the action is
triggered from the admin. Action functions are just regular functions that take
triggered from the admin. Action functions are regular functions that take
three arguments:
* The current :class:`ModelAdmin`
@@ -89,7 +89,7 @@ request object, but we will use the queryset::
For the best performance, we're using the queryset's :ref:`update method
<topics-db-queries-update>`. Other types of actions might need to deal
with each object individually; in these cases we'd just iterate over the
with each object individually; in these cases we'd iterate over the
queryset::
for obj in queryset:
@@ -138,7 +138,7 @@ That code will give us an admin change list that looks something like this:
.. image:: _images/adding-actions-to-the-modeladmin.png
That's really all there is to it! If you're itching to write your own actions,
you now know enough to get started. The rest of this document just covers more
you now know enough to get started. The rest of this document covers more
advanced techniques.
Handling errors in actions
@@ -159,12 +159,12 @@ advanced options.
Actions as :class:`ModelAdmin` methods
--------------------------------------
The example above shows the ``make_published`` action defined as a simple
function. That's perfectly fine, but it's not perfect from a code design point
of view: since the action is tightly coupled to the ``Article`` object, it
makes sense to hook the action to the ``ArticleAdmin`` object itself.
The example above shows the ``make_published`` action defined as a function.
That's perfectly fine, but it's not perfect from a code design point of view:
since the action is tightly coupled to the ``Article`` object, it makes sense
to hook the action to the ``ArticleAdmin`` object itself.
That's easy enough to do::
You can do it like this::
class ArticleAdmin(admin.ModelAdmin):
...
@@ -180,9 +180,9 @@ Notice first that we've moved ``make_published`` into a method and renamed the
``'make_published'`` in ``actions`` instead of a direct function reference. This
tells the :class:`ModelAdmin` to look up the action as a method.
Defining actions as methods gives the action more straightforward, idiomatic
access to the :class:`ModelAdmin` itself, allowing the action to call any of the
methods provided by the admin.
Defining actions as methods gives the action more idiomatic access to the
:class:`ModelAdmin` itself, allowing the action to call any of the methods
provided by the admin.
.. _custom-admin-action:
@@ -208,17 +208,15 @@ performing an action:
Actions that provide intermediate pages
---------------------------------------
By default, after an action is performed the user is simply redirected back
to the original change list page. However, some actions, especially more
complex ones, will need to return intermediate pages. For example, the
built-in delete action asks for confirmation before deleting the selected
objects.
By default, after an action is performed the user is redirected back to the
original change list page. However, some actions, especially more complex ones,
will need to return intermediate pages. For example, the built-in delete action
asks for confirmation before deleting the selected objects.
To provide an intermediary page, simply return an
:class:`~django.http.HttpResponse` (or subclass) from your action. For
example, you might write a simple export function that uses Django's
:doc:`serialization functions </topics/serialization>` to dump some selected
objects as JSON::
To provide an intermediary page, return an :class:`~django.http.HttpResponse`
(or subclass) from your action. For example, you might write a export function
that uses Django's :doc:`serialization functions </topics/serialization>` to
dump some selected objects as JSON::
from django.core import serializers
from django.http import HttpResponse
@@ -236,7 +234,7 @@ This allows you to provide complex interaction logic on the intermediary
pages. For example, if you wanted to provide a more complete export function,
you'd want to let the user choose a format, and possibly a list of fields to
include in the export. The best thing to do would be to write a small action
that simply redirects to your custom export view::
that redirects to your custom export view::
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
@@ -247,9 +245,9 @@ that simply redirects to your custom export view::
ct = ContentType.objects.get_for_model(queryset.model)
return HttpResponseRedirect("/export/?ct=%s&ids=%s" % (ct.pk, ",".join(selected)))
As you can see, the action is the simple part; all the complex logic would
belong in your export view. This would need to deal with objects of any type,
hence the business with the ``ContentType``.
As you can see, the action is rather short; all the complex logic would belong
in your export view. This would need to deal with objects of any type, hence
the business with the ``ContentType``.
Writing this view is left as an exercise to the reader.
@@ -303,8 +301,7 @@ Disabling a site-wide action
site-wide.
If, however, you need to re-enable a globally-disabled action for one
particular model, simply list it explicitly in your ``ModelAdmin.actions``
list::
particular model, list it explicitly in your ``ModelAdmin.actions`` list::
# Globally disable delete selected
admin.site.disable_action('delete_selected')
@@ -323,8 +320,8 @@ Disabling a site-wide action
Disabling all actions for a particular :class:`ModelAdmin`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want *no* bulk actions available for a given :class:`ModelAdmin`, simply
set :attr:`ModelAdmin.actions` to ``None``::
If you want *no* bulk actions available for a given :class:`ModelAdmin`, set
:attr:`ModelAdmin.actions` to ``None``::
class MyModelAdmin(admin.ModelAdmin):
actions = None

View File

@@ -83,8 +83,7 @@ Other topics
The ``ModelAdmin`` class is the representation of a model in the admin
interface. Usually, these are stored in a file named ``admin.py`` in your
application. Let's take a look at a very simple example of
the ``ModelAdmin``::
application. Let's take a look at an example of the ``ModelAdmin``::
from django.contrib import admin
from myproject.myapp.models import Author
@@ -1195,8 +1194,8 @@ subclass::
A read-only field can not only display data from a model's field, it can
also display the output of a model's method or a method of the
``ModelAdmin`` class itself. This is very similar to the way
:attr:`ModelAdmin.list_display` behaves. This provides an easy way to use
the admin interface to provide feedback on the status of the objects being
:attr:`ModelAdmin.list_display` behaves. This provides a way to use the
admin interface to provide feedback on the status of the objects being
edited, for example::
from django.contrib import admin
@@ -1742,7 +1741,7 @@ templates used by the :class:`ModelAdmin` views:
kwargs['form'] = MySuperuserForm
return super().get_form(request, obj, **kwargs)
You may also simply return a custom :class:`~django.forms.ModelForm` class
You may also return a custom :class:`~django.forms.ModelForm` class
directly.
.. method:: ModelAdmin.get_formsets_with_inlines(request, obj=None)
@@ -2159,9 +2158,9 @@ return the uncompressed versions of the various JavaScript files, including
Adding custom validation to the admin
-------------------------------------
Adding custom validation of data in the admin is quite easy. The automatic
admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
you the ability define your own form::
You can also add custom validation of data in the admin. The automatic admin
interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
the ability define your own form::
class ArticleAdmin(admin.ModelAdmin):
form = MyArticleAdminForm
@@ -2535,8 +2534,7 @@ layout required for multiple widgets will vary depending on the intermediate
model.
However, we still want to be able to edit that information inline. Fortunately,
this is easy to do with inline admin models. Suppose we have the following
models::
we can do this with inline admin models. Suppose we have the following models::
from django.db import models
@@ -2560,7 +2558,7 @@ define an inline class for the ``Membership`` model::
model = Membership
extra = 1
This simple example uses the default ``InlineModelAdmin`` values for the
This example uses the default ``InlineModelAdmin`` values for the
``Membership`` model, and limits the extra add forms to one. This could be
customized using any of the options available to ``InlineModelAdmin`` classes.
@@ -2633,9 +2631,9 @@ specific information.
Overriding admin templates
==========================
It is relatively easy to override many of the templates which the admin module
uses to generate the various pages of an admin site. You can even override a
few of these templates for a specific app, or a specific model.
You can override many of the templates which the admin module uses to generate
the various pages of an admin site. You can even override a few of these
templates for a specific app, or a specific model.
Set up your projects admin template directories
-----------------------------------------------
@@ -2732,7 +2730,7 @@ app or per model. The following can:
* ``submit_line.html``
For those templates that cannot be overridden in this way, you may still
override them for your entire project. Just place the new version in your
override them for your entire project by placing the new version in your
``templates/admin`` directory. This is particularly useful to create custom 404
and 500 pages.
@@ -2923,11 +2921,11 @@ Customizing the :class:`AdminSite` class
----------------------------------------
If you'd like to set up your own admin site with custom behavior, you're free
to subclass ``AdminSite`` and override or add anything you like. Then, simply
create an instance of your ``AdminSite`` subclass (the same way you'd
instantiate any other Python class) and register your models and
``ModelAdmin`` subclasses with it instead of with the default site. Finally,
update :file:`myproject/urls.py` to reference your :class:`AdminSite` subclass.
to subclass ``AdminSite`` and override or add anything you like. Then, create
an instance of your ``AdminSite`` subclass (the same way you'd instantiate any
other Python class) and register your models and ``ModelAdmin`` subclasses with
it instead of with the default site. Finally, update :file:`myproject/urls.py`
to reference your :class:`AdminSite` subclass.
.. code-block:: python
:caption: myapp/admin.py
@@ -3000,9 +2998,9 @@ returns a site instance.
Multiple admin sites in the same URLconf
----------------------------------------
It's easy to create multiple instances of the admin site on the same
Django-powered website. Just create multiple instances of ``AdminSite`` and
root each one at a different URL.
You can create multiple instances of the admin site on the same Django-powered
website. Create multiple instances of ``AdminSite`` and place each one at a
different URL.
In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
separate versions of the admin site -- using the ``AdminSite`` instances

View File

@@ -55,9 +55,9 @@ Two points to keep in mind:
various operations in the change form and we need that to be rendered too.
Sometimes you'll need to work with ``jQuery`` plugins that are not registered
in the ``django.jQuery`` namespace. To do that, simply change how the code
listens for events. Instead of wrapping the listener in the ``django.jQuery``
namespace, just listen to the event triggered from there. For example:
in the ``django.jQuery`` namespace. To do that, change how the code listens for
events. Instead of wrapping the listener in the ``django.jQuery`` namespace,
listen to the event triggered from there. For example:
.. code-block:: html+django

View File

@@ -648,8 +648,8 @@ The following backends are available in :mod:`django.contrib.auth.backends`:
.. method:: authenticate(request, remote_user)
The username passed as ``remote_user`` is considered trusted. This
method simply returns the user object with the given username, creating
a new user object if :attr:`~RemoteUserBackend.create_unknown_user` is
method returns the user object with the given username, creating a new
user object if :attr:`~RemoteUserBackend.create_unknown_user` is
``True``.
Returns ``None`` if :attr:`~RemoteUserBackend.create_unknown_user` is

View File

@@ -240,7 +240,7 @@ to go one step further and use
:class:`~django.contrib.contenttypes.models.ContentType` to enable truly
generic (sometimes called "polymorphic") relationships between models.
A simple example is a tagging system, which might look like this::
For example, it could be used for a tagging system like so::
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
@@ -438,7 +438,7 @@ it would be deleted at the same time.
Unlike :class:`~django.db.models.ForeignKey`,
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` does not accept
an :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this
behavior; if desired, you can avoid the cascade-deletion simply by not using
behavior; if desired, you can avoid the cascade-deletion by not using
:class:`~django.contrib.contenttypes.fields.GenericRelation`, and alternate
behavior can be provided via the :data:`~django.db.models.signals.pre_delete`
signal.

View File

@@ -5,14 +5,14 @@ The flatpages app
.. module:: django.contrib.flatpages
:synopsis: A framework for managing simple ?flat? HTML content in a database.
Django comes with an optional "flatpages" application. It lets you store simple
"flat" HTML content in a database and handles the management for you via
Django's admin interface and a Python API.
Django comes with an optional "flatpages" application. It lets you store "flat"
HTML content in a database and handles the management for you via Django's
admin interface and a Python API.
A flatpage is a simple object with a URL, title and content. Use it for
one-off, special-case pages, such as "About" or "Privacy Policy" pages, that
you want to store in a database but for which you don't want to develop a
custom Django application.
A flatpage is a object with a URL, title and content. Use it for one-off,
special-case pages, such as "About" or "Privacy Policy" pages, that you want to
store in a database but for which you don't want to develop a custom Django
application.
A flatpage can use a custom template or a default, systemwide flatpage
template. It can be associated with one, or multiple, sites.
@@ -58,9 +58,9 @@ How it works
============
``manage.py migrate`` creates two tables in your database: ``django_flatpage``
and ``django_flatpage_sites``. ``django_flatpage`` is a simple lookup table
that simply maps a URL to a title and bunch of text content.
``django_flatpage_sites`` associates a flatpage with a site.
and ``django_flatpage_sites``. ``django_flatpage`` is a lookup table that maps
a URL to a title and bunch of text content. ``django_flatpage_sites``
associates a flatpage with a site.
Using the URLconf
-----------------
@@ -229,12 +229,12 @@ By default, flatpages are rendered via the template
particular flatpage: in the admin, a collapsed fieldset titled
"Advanced options" (clicking will expand it) contains a field for
specifying a template name. If you're creating a flat page via the
Python API you can simply set the template name as the field
``template_name`` on the ``FlatPage`` object.
Python API you can set the template name as the field ``template_name`` on the
``FlatPage`` object.
Creating the :file:`flatpages/default.html` template is your responsibility;
in your template directory, just create a :file:`flatpages` directory
containing a file :file:`default.html`.
in your template directory, create a :file:`flatpages` directory containing a
file :file:`default.html`.
Flatpage templates are passed a single context variable, ``flatpage``,
which is the flatpage object.

View File

@@ -284,10 +284,10 @@ Then distance queries may be performed as follows::
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))
Raster queries work the same way by simply replacing the geometry field
``point`` with a raster field, or the ``pnt`` object with a raster object, or
both. To specify the band index of a raster input on the right hand side, a
3-tuple can be passed to the lookup as follows::
Raster queries work the same way by replacing the geometry field ``point`` with
a raster field, or the ``pnt`` object with a raster object, or both. To specify
the band index of a raster input on the right hand side, a 3-tuple can be
passed to the lookup as follows::
>>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))

View File

@@ -88,7 +88,7 @@ Form widgets
GeoDjango form widgets allow you to display and edit geographic data on a
visual map.
Note that none of the currently available widgets supports 3D geometries, hence
geometry fields will fallback using a simple ``Textarea`` widget for such data.
geometry fields will fallback using a ``Textarea`` widget for such data.
Widget attributes
-----------------

View File

@@ -36,7 +36,7 @@ The GDAL/OGR tools described here are designed to help you read in
your geospatial data, in order for most of them to be useful you have
to have some data to work with. If you're starting out and don't yet
have any data of your own to use, GeoDjango tests contain a number of
simple data sets that you can use for testing. You can download them here::
data sets that you can use for testing. You can download them here::
$ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}
$ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/rasters/raster.tif
@@ -49,7 +49,7 @@ Vector Data Source Objects
:class:`DataSource` is a wrapper for the OGR data source object that
supports reading data from a variety of OGR-supported geospatial file
formats and data sources using a simple, consistent interface. Each
formats and data sources using a consistent interface. Each
data source is represented by a :class:`DataSource` object which contains
one or more layers of data. Each layer, represented by a :class:`Layer`
object, contains some number of geographic features (:class:`Feature`),
@@ -1085,7 +1085,7 @@ Raster Data Objects
:class:`GDALRaster` is a wrapper for the GDAL raster source object that
supports reading data from a variety of GDAL-supported geospatial file
formats and data sources using a simple, consistent interface. Each
formats and data sources using a consistent interface. Each
data source is represented by a :class:`GDALRaster` object which contains
one or more layers of data named bands. Each band, represented by a
:class:`GDALBand` object, contains georeferenced image data. For example, an RGB

View File

@@ -887,8 +887,8 @@ SpatiaLite
Returns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry
column. This is analogous to a simplified version of the :class:`Union`
aggregate, except it can be several orders of magnitude faster than performing
a union because it simply rolls up geometries into a collection or multi object,
not caring about dissolving boundaries.
a union because it rolls up geometries into a collection or multi object, not
caring about dissolving boundaries.
``Extent``
~~~~~~~~~~

View File

@@ -833,7 +833,7 @@ Geometry Collections
Prepared Geometries
===================
In order to obtain a prepared geometry, just access the
In order to obtain a prepared geometry, access the
:attr:`GEOSGeometry.prepared` property. Once you have a
``PreparedGeometry`` instance its spatial predicate methods, listed below,
may be used with other ``GEOSGeometry`` objects. An operation with a prepared
@@ -911,8 +911,8 @@ I/O Objects
Reader Objects
--------------
The reader I/O classes simply return a :class:`GEOSGeometry` instance from the
WKB and/or WKT input given to their ``read(geom)`` method.
The reader I/O classes return a :class:`GEOSGeometry` instance from the WKB
and/or WKT input given to their ``read(geom)`` method.
.. class:: WKBReader

View File

@@ -39,7 +39,7 @@ totally fine with GeoDjango. Your mileage may vary.
The GeoDjango interfaces to GEOS, GDAL, and GeoIP may be used
independently of Django. In other words, no database or settings file
required -- just import them as normal from :mod:`django.contrib.gis`.
required -- import them as normal from :mod:`django.contrib.gis`.
.. _PROJ.4: https://github.com/OSGeo/proj.4/wiki/
__ https://postgis.net/

View File

@@ -272,9 +272,9 @@ KyngChaos packages
~~~~~~~~~~~~~~~~~~
William Kyngesburye provides a number of `geospatial library binary packages`__
that make it simple to get GeoDjango installed on macOS without compiling
them from source. However, `Xcode`_ is still necessary for compiling the
Python database adapters :ref:`psycopg2_kyngchaos` (for PostGIS).
that help to get GeoDjango installed on macOS without compiling them from
source. However, `Xcode`_ is still necessary for compiling the Python database
adapters :ref:`psycopg2_kyngchaos` (for PostGIS).
.. note::
@@ -385,9 +385,9 @@ PostgreSQL
~~~~~~~~~~
First, download the latest `PostgreSQL 9.x installer`__ from the
`EnterpriseDB`__ website. After downloading, simply run the installer,
follow the on-screen directions, and keep the default options unless
you know the consequences of changing them.
`EnterpriseDB`__ website. After downloading, run the installer, follow the
on-screen directions, and keep the default options unless you know the
consequences of changing them.
.. note::
@@ -446,14 +446,13 @@ __ http://www.stickpeople.com/projects/python/win-psycopg/
OSGeo4W
~~~~~~~
The `OSGeo4W installer`_ makes it simple to install the PROJ.4, GDAL, and GEOS
libraries required by GeoDjango. First, download the `OSGeo4W installer`_,
and run it. Select :menuselection:`Express Web-GIS Install` and click next.
In the 'Select Packages' list, ensure that GDAL is selected; MapServer and
Apache are also enabled by default, but are not required by GeoDjango and
may be unchecked safely. After clicking next, the packages will be
automatically downloaded and installed, after which you may exit the
installer.
The `OSGeo4W installer`_ helps to install the PROJ.4, GDAL, and GEOS libraries
required by GeoDjango. First, download the `OSGeo4W installer`_, and run it.
Select :menuselection:`Express Web-GIS Install` and click next. In the 'Select
Packages' list, ensure that GDAL is selected; MapServer and Apache are also
enabled by default, but are not required by GeoDjango and may be unchecked
safely. After clicking next, the packages will be automatically downloaded and
installed, after which you may exit the installer.
.. _OSGeo4W installer: https://trac.osgeo.org/osgeo4w/

View File

@@ -38,7 +38,7 @@ command line interface and enter the following query::
sqlite> CREATE VIRTUAL TABLE testrtree USING rtree(id,minX,maxX,minY,maxY);
If you obtain an error, you will have to recompile SQLite from source. Otherwise,
just skip this section.
skip this section.
To install from sources, download the latest amalgamation source archive from
the `SQLite download page`__, and extract::

View File

@@ -25,8 +25,8 @@ then inserting into a GeoDjango model.
that :class:`LayerMapping` is using too much memory, set
:setting:`DEBUG` to ``False`` in your settings. When :setting:`DEBUG`
is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>`
*every* SQL query -- thus, when SQL statements contain geometries, it is
easy to consume more memory than is typical.
*every* SQL query -- and when SQL statements contain geometries, this may
consume more memory than is typical.
Example
=======
@@ -75,10 +75,10 @@ Example
Saved: Name: 2
Saved: Name: 3
Here, :class:`LayerMapping` just transformed the three geometries from the
shapefile in their original spatial reference system (WGS84) to the spatial
reference system of the GeoDjango model (NAD83). If no spatial reference
system is defined for the layer, use the ``source_srs`` keyword with a
Here, :class:`LayerMapping` transformed the three geometries from the shapefile
in their original spatial reference system (WGS84) to the spatial reference
system of the GeoDjango model (NAD83). If no spatial reference system is
defined for the layer, use the ``source_srs`` keyword with a
:class:`~django.contrib.gis.gdal.SpatialReference` object to specify one.
``LayerMapping`` API

View File

@@ -26,8 +26,8 @@ instantiated in units of kilometers (``km``) and miles (``mi``)::
>>> print(d2)
5.0 mi
Conversions are easy, just access the preferred unit attribute to get a
converted distance quantity::
For conversions, access the preferred unit attribute to get a converted
distance quantity::
>>> print(d1.mi) # Converting 5 kilometers to miles
3.10685596119

View File

@@ -73,8 +73,8 @@ is done from an existing superuser account)::
Windows
-------
On Windows platforms the pgAdmin III utility may also be used as
a simple way to add superuser privileges to your database user.
On Windows platforms you can use the pgAdmin III utility to add superuser
privileges to your database user.
By default, the PostGIS installer on Windows includes a template
spatial database entitled ``template_postgis``.

View File

@@ -758,8 +758,8 @@ available with the :class:`~django.contrib.gis.admin.GeoModelAdmin`
The PROJ.4 datum shifting files must be installed (see the :ref:`PROJ.4
installation instructions <proj4>` for more details).
If you meet this requirement, then just substitute the ``OSMGeoAdmin``
option class in your ``admin.py`` file::
If you meet this requirement, then substitute the ``OSMGeoAdmin`` option class
in your ``admin.py`` file::
admin.site.register(WorldBorder, admin.OSMGeoAdmin)

View File

@@ -61,7 +61,7 @@ See the :doc:`contenttypes documentation </ref/contrib/contenttypes>`.
``flatpages``
=============
A framework for managing simple "flat" HTML content in a database.
A framework for managing "flat" HTML content in a database.
See the :doc:`flatpages documentation </ref/contrib/flatpages>`.

View File

@@ -194,9 +194,9 @@ If you're using the context processor, your template should be rendered with a
``RequestContext``. Otherwise, ensure ``messages`` is available to
the template context.
Even if you know there is only just one message, you should still iterate over
the ``messages`` sequence, because otherwise the message storage will not be cleared
for the next request.
Even if you know there is only one message, you should still iterate over the
``messages`` sequence, because otherwise the message storage will not be
cleared for the next request.
The context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which
is a mapping of the message level names to their numeric value::
@@ -235,8 +235,7 @@ The ``Message`` class
.. class:: storage.base.Message
When you loop over the list of messages in a template, what you get are
instances of the ``Message`` class. It's quite a simple object, with only a
few attributes:
instances of the ``Message`` class. They have only a few attributes:
* ``message``: The actual text of the message.

View File

@@ -24,7 +24,7 @@ may be a good choice for the :ref:`range fields <range-fields>` and
.. class:: ArrayField(base_field, size=None, **options)
A field for storing lists of data. Most field types can be used, you simply
A field for storing lists of data. Most field types can be used, and you
pass another field instance as the :attr:`base_field
<ArrayField.base_field>`. You may also specify a :attr:`size
<ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional
@@ -333,7 +333,7 @@ We will use the following example model::
Key lookups
~~~~~~~~~~~
To query based on a given key, you simply use that key as the lookup name::
To query based on a given key, you can use that key as the lookup name::
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
@@ -537,8 +537,7 @@ We will use the following example model::
Key, index, and path lookups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To query based on a given dictionary key, simply use that key as the lookup
name::
To query based on a given dictionary key, use that key as the lookup name::
>>> Dog.objects.create(name='Rufus', data={
... 'breed': 'labrador',

View File

@@ -15,8 +15,7 @@ Fields
.. class:: SimpleArrayField(base_field, delimiter=',', max_length=None, min_length=None)
A simple field which maps to an array. It is represented by an HTML
``<input>``.
A field which maps to an array. It is represented by an HTML ``<input>``.
.. attribute:: base_field

View File

@@ -21,7 +21,7 @@ The ``search`` lookup
.. fieldlookup:: search
The simplest way to use full text search is to search a single term against a
A common way to use full text search is to search a single term against a
single column in the database. For example::
>>> Entry.objects.filter(body_text__search='Cheese')
@@ -111,9 +111,9 @@ See :ref:`postgresql-fts-search-configuration` for an explanation of the
.. class:: SearchRank(vector, query, weights=None)
So far, we've just returned the results for which any match between the vector
and the query are possible. It's likely you may wish to order the results by
some sort of relevancy. PostgreSQL provides a ranking function which takes into
So far, we've returned the results for which any match between the vector and
the query are possible. It's likely you may wish to order the results by some
sort of relevancy. PostgreSQL provides a ranking function which takes into
account how often the query terms appear in the document, how close together
the terms are in the document, and how important the part of the document is
where they occur. The better the match, the higher the value of the rank. To

View File

@@ -5,7 +5,7 @@ The redirects app
.. module:: django.contrib.redirects
:synopsis: A framework for managing redirects.
Django comes with an optional redirects application. It lets you store simple
Django comes with an optional redirects application. It lets you store
redirects in a database and handles the redirecting for you. It uses the HTTP
response status code ``301 Moved Permanently`` by default.
@@ -25,7 +25,7 @@ How it works
============
``manage.py migrate`` creates a ``django_redirect`` table in your database. This
is a simple lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
is a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.
The :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`
does all of the work. Each time any Django application raises a 404

View File

@@ -5,8 +5,8 @@ The sitemap framework
.. module:: django.contrib.sitemaps
:synopsis: A framework for generating Google sitemap XML files.
Django comes with a high-level sitemap-generating framework that makes
creating sitemap_ XML files easy.
Django comes with a high-level sitemap-generating framework to create sitemap_
XML files.
.. _sitemap: https://www.sitemaps.org/
@@ -22,7 +22,7 @@ The Django sitemap framework automates the creation of this XML file by letting
you express this information in Python code.
It works much like Django's :doc:`syndication framework
</ref/contrib/syndication>`. To create a sitemap, just write a
</ref/contrib/syndication>`. To create a sitemap, write a
:class:`~django.contrib.sitemaps.Sitemap` class and point to it in your
:doc:`URLconf </topics/http/urls>`.
@@ -76,11 +76,11 @@ a :class:`~django.contrib.sitemaps.Sitemap` class (e.g.,
``Sitemap`` classes
===================
A :class:`~django.contrib.sitemaps.Sitemap` class is a simple Python
class that represents a "section" of entries in your sitemap. For example,
one :class:`~django.contrib.sitemaps.Sitemap` class could represent
all the entries of your Weblog, while another could represent all of the
events in your events calendar.
A :class:`~django.contrib.sitemaps.Sitemap` class is a Python class that
represents a "section" of entries in your sitemap. For example, one
:class:`~django.contrib.sitemaps.Sitemap` class could represent all the entries
of your Weblog, while another could represent all of the events in your events
calendar.
In the simplest case, all these sections get lumped together into one
:file:`sitemap.xml`, but it's also possible to use the framework to generate a
@@ -90,8 +90,8 @@ sitemap index that references individual sitemap files, one per section. (See
:class:`~django.contrib.sitemaps.Sitemap` classes must subclass
``django.contrib.sitemaps.Sitemap``. They can live anywhere in your codebase.
A simple example
================
An example
==========
Let's assume you have a blog system, with an ``Entry`` model, and you want your
sitemap to include all the links to your individual blog entries. Here's how
@@ -116,11 +116,10 @@ Note:
attributes corresponding to ``<changefreq>`` and ``<priority>`` elements,
respectively. They can be made callable as functions, as
:attr:`~Sitemap.lastmod` was in the example.
* :attr:`~Sitemap.items()` is simply a method that returns a list of
objects. The objects returned will get passed to any callable methods
corresponding to a sitemap property (:attr:`~Sitemap.location`,
:attr:`~Sitemap.lastmod`, :attr:`~Sitemap.changefreq`, and
:attr:`~Sitemap.priority`).
* :attr:`~Sitemap.items()` is a method that returns a list of objects. The
objects returned will get passed to any callable methods corresponding to a
sitemap property (:attr:`~Sitemap.location`, :attr:`~Sitemap.lastmod`,
:attr:`~Sitemap.changefreq`, and :attr:`~Sitemap.priority`).
* :attr:`~Sitemap.lastmod` should return a :class:`~datetime.datetime`.
* There is no :attr:`~Sitemap.location` method in this example, but you
can provide it in order to specify the URL for your object. By default,

View File

@@ -13,7 +13,7 @@ the domain names and "verbose" names of your Django-powered sites.
Use it if your single Django installation powers more than one site and you
need to differentiate between those sites in some way.
The sites framework is mainly based on a simple model:
The sites framework is mainly based on this model:
.. class:: models.Site
@@ -37,7 +37,7 @@ try to get the current site by comparing the
the :meth:`request.get_host() <django.http.HttpRequest.get_host>` method.
How you use this is up to you, but Django uses it in a couple of ways
automatically via simple conventions.
automatically via a couple of conventions.
Example usage
=============
@@ -58,10 +58,10 @@ publish the same story twice: once for LJWorld.com and again for Lawrence.com.
But that's inefficient for site producers, and it's redundant to store
multiple copies of the same story in the database.
The better solution is simple: Both sites use the same article database, and an
article is associated with one or more sites. In Django model terminology,
that's represented by a :class:`~django.db.models.ManyToManyField` in the
``Article`` model::
A better solution removes the content duplication: Both sites use the same
article database, and an article is associated with one or more sites. In
Django model terminology, that's represented by a
:class:`~django.db.models.ManyToManyField` in the ``Article`` model::
from django.contrib.sites.models import Site
from django.db import models
@@ -80,8 +80,8 @@ This accomplishes several things quite nicely:
database; it only has a single record in the database.
* It lets the site developers use the same Django view code for both sites.
The view code that displays a given story just checks to make sure the
requested story is on the current site. It looks something like this::
The view code that displays a given story checks to make sure the requested
story is on the current site. It looks something like this::
from django.contrib.sites.shortcuts import get_current_site
@@ -215,7 +215,7 @@ subscribing to LJWorld.com alerts." Same goes for the email's message body.
Note that an even more flexible (but more heavyweight) way of doing this would
be to use Django's template system. Assuming Lawrence.com and LJWorld.com have
different template directories (:setting:`DIRS <TEMPLATES-DIRS>`), you could
simply farm out to the template system like so::
farm out to the template system like so::
from django.core.mail import send_mail
from django.template import Context, loader
@@ -243,7 +243,7 @@ Getting the current domain for full URLs
Django's ``get_absolute_url()`` convention is nice for getting your objects'
URL without the domain name, but in some cases you might want to display the
full URL -- with ``http://`` and the domain and everything -- for an object.
To do this, you can use the sites framework. A simple example::
To do this, you can use the sites framework. An example::
>>> from django.contrib.sites.models import Site
>>> obj = MyModel.objects.get(id=3)
@@ -401,7 +401,7 @@ If you often use this pattern::
site = Site.objects.get_current()
...
there is simple way to avoid repetitions. Add
To avoid repetitions, add
:class:`django.contrib.sites.middleware.CurrentSiteMiddleware` to
:setting:`MIDDLEWARE`. The middleware sets the ``site`` attribute on every
request object, so you can use ``request.site`` to get the current site.

View File

@@ -387,7 +387,7 @@ hashed names of processed files instead of a static manifest file called
have access to the file system.
If you want to override certain options of the cache backend the storage uses,
simply specify a custom entry in the :setting:`CACHES` setting named
specify a custom entry in the :setting:`CACHES` setting named
``'staticfiles'``. It falls back to using the ``'default'`` cache backend.
.. warning::

View File

@@ -6,8 +6,8 @@ The syndication feed framework
:synopsis: A framework for generating syndication feeds, in RSS and Atom,
quite easily.
Django comes with a high-level syndication-feed-generating framework
that makes creating RSS_ and Atom_ feeds easy.
Django comes with a high-level syndication-feed-generating framework for
creating RSS_ and Atom_ feeds.
To create any syndication feed, all you have to do is write a short
Python class. You can create as many feeds as you want.
@@ -94,13 +94,12 @@ Note:
standard RSS ``<title>``, ``<link>`` and ``<description>`` elements,
respectively.
* ``items()`` is, simply, a method that returns a list of objects that
should be included in the feed as ``<item>`` elements. Although this
example returns ``NewsItem`` objects using Django's
:doc:`object-relational mapper </ref/models/querysets>`, ``items()``
doesn't have to return model instances. Although you get a few bits of
functionality "for free" by using Django models, ``items()`` can
return any type of object you want.
* ``items()`` is, a method that returns a list of objects that should be
included in the feed as ``<item>`` elements. Although this example returns
``NewsItem`` objects using Django's :doc:`object-relational mapper
</ref/models/querysets>`, ``items()`` doesn't have to return model instances.
Although you get a few bits of functionality "for free" by using Django
models, ``items()`` can return any type of object you want.
* If you're creating an Atom feed, rather than an RSS feed, set the
``subtitle`` attribute instead of the ``description`` attribute.
@@ -246,7 +245,7 @@ Here's the code for these beat-specific feeds::
To generate the feed's ``<title>``, ``<link>`` and ``<description>``, Django
uses the ``title()``, ``link()`` and ``description()`` methods. In
the previous example, they were simple string class attributes, but this example
the previous example, they were string class attributes, but this example
illustrates that they can be either strings *or* methods. For each of
``title``, ``link`` and ``description``, Django follows this
algorithm:
@@ -262,7 +261,8 @@ Also note that ``items()`` also follows the same algorithm -- first, it
tries ``items(obj)``, then ``items()``, then finally an ``items``
class attribute (which should be a list).
We are using a template for the item descriptions. It can be very simple:
We are using a template for the item descriptions. It can be as minimal as
this:
.. code-block:: html+django
@@ -333,10 +333,9 @@ Publishing Atom and RSS feeds in tandem
---------------------------------------
Some developers like to make available both Atom *and* RSS versions of their
feeds. That's easy to do with Django: Just create a subclass of your
:class:`~django.contrib.syndication.views.Feed`
class and set the ``feed_type`` to something different. Then update your
URLconf to add the extra versions.
feeds. To do that, you can create a subclass of your
:class:`~django.contrib.syndication.views.Feed` class and set the ``feed_type``
to something different. Then update your URLconf to add the extra versions.
Here's a full example::
@@ -367,8 +366,8 @@ Here's a full example::
subtitle and description are not necessarily the same thing. Instead, you
should define a ``subtitle`` attribute.
In the above example, we simply set the Atom feed's ``subtitle`` to the
RSS feed's ``description``, because it's quite short already.
In the above example, we set the Atom feed's ``subtitle`` to the RSS feed's
``description``, because it's quite short already.
And the accompanying URLconf::
@@ -1073,5 +1072,5 @@ For example, you might start implementing an iTunes RSS feed generator like so::
super().add_root_elements(handler)
handler.addQuickElement('itunes:explicit', 'clean')
Obviously there's a lot more work to be done for a complete custom feed class,
but the above example should demonstrate the basic idea.
There's a lot more work to be done for a complete custom feed class, but the
above example should demonstrate the basic idea.

View File

@@ -80,7 +80,7 @@ set if you've enabled CSRF protection for your views as outlined above.
The CSRF token cookie is named ``csrftoken`` by default, but you can control
the cookie name via the :setting:`CSRF_COOKIE_NAME` setting.
Acquiring the token is straightforward:
You can acquire the token like this:
.. code-block:: javascript
@@ -227,7 +227,7 @@ when, due to a programming error, the CSRF token has not been included with a
POST form.
The error page, however, is not very friendly, so you may want to provide your
own view for handling this condition. To do this, simply set the
own view for handling this condition. To do this, set the
:setting:`CSRF_FAILURE_VIEW` setting.
CSRF failures are logged as warnings to the :ref:`django.security.csrf

View File

@@ -710,8 +710,8 @@ If you're getting this error, you can solve it by:
# ...
}
This will simply make SQLite wait a bit longer before throwing "database
is locked" errors; it won't really do anything to solve them.
This will make SQLite wait a bit longer before throwing "database is locked"
errors; it won't really do anything to solve them.
``QuerySet.select_for_update()`` not supported
----------------------------------------------

View File

@@ -213,7 +213,7 @@ specified in your :setting:`USER`, :setting:`PASSWORD`, etc., settings.
* For SQLite, this runs the ``sqlite3`` command-line client.
* For Oracle, this runs the ``sqlplus`` command-line client.
This command assumes the programs are on your ``PATH`` so that a simple call to
This command assumes the programs are on your ``PATH`` so that a call to
the program name (``psql``, ``mysql``, ``sqlite3``, ``sqlplus``) will find the
program in the right place. There's no way to specify the location of the
program manually.
@@ -400,7 +400,7 @@ By default, ``inspectdb`` creates unmanaged models. That is, ``managed = False``
in the model's ``Meta`` class tells Django not to manage each table's creation,
modification, and deletion. If you do want to allow Django to manage the
table's lifecycle, you'll need to change the
:attr:`~django.db.models.Options.managed` option to ``True`` (or simply remove
:attr:`~django.db.models.Options.managed` option to ``True`` (or remove
it because ``True`` is its default value).
Database-specific notes
@@ -537,7 +537,7 @@ raise an exception::
post_save.connect(my_handler, sender=MyModel)
You could also write a simple decorator to encapsulate this logic::
You could also write a decorator to encapsulate this logic::
from functools import wraps
@@ -917,7 +917,7 @@ project for some common errors (see the :djadmin:`check` command). If any
errors are found, they will be printed to standard output.
You can run as many concurrent servers as you want, as long as they're on
separate ports. Just execute ``django-admin runserver`` more than once.
separate ports by executing ``django-admin runserver`` more than once.
Note that the default IP address, ``127.0.0.1``, is not accessible from other
machines on your network. To make your development server viewable to other
@@ -1729,7 +1729,7 @@ Example usage::
.. django-admin-option:: --traceback
Displays a full stack trace when a :exc:`~django.core.management.CommandError`
is raised. By default, ``django-admin`` will show a simple error message when a
is raised. By default, ``django-admin`` will show an error message when a
``CommandError`` occurs and a full stack trace for any other exception.
Example usage::

View File

@@ -12,8 +12,8 @@ Uploaded files
During file uploads, the actual file data is stored in :attr:`request.FILES
<django.http.HttpRequest.FILES>`. Each entry in this dictionary is an
``UploadedFile`` object (or a subclass) -- a simple wrapper around an uploaded
file. You'll usually use one of these methods to access the uploaded content:
``UploadedFile`` object (or a subclass) -- a wrapper around an uploaded file.
You'll usually use one of these methods to access the uploaded content:
.. method:: UploadedFile.read()
@@ -33,9 +33,9 @@ file. You'll usually use one of these methods to access the uploaded content:
A generator returning chunks of the file. If ``multiple_chunks()`` is
``True``, you should use this method in a loop instead of ``read()``.
In practice, it's often easiest simply to use ``chunks()`` all the time.
Looping over ``chunks()`` instead of using ``read()`` ensures that large
files don't overwhelm your system's memory.
In practice, it's often easiest to use ``chunks()`` all the time. Looping
over ``chunks()`` instead of using ``read()`` ensures that large files
don't overwhelm your system's memory.
Here are some useful attributes of ``UploadedFile``:
@@ -72,8 +72,8 @@ Here are some useful attributes of ``UploadedFile``:
.. note::
Like regular Python files, you can read the file line-by-line simply by
iterating over the uploaded file:
Like regular Python files, you can read the file line-by-line by iterating
over the uploaded file:
.. code-block:: python

View File

@@ -25,7 +25,7 @@ A :class:`Form` instance is either **bound** to a set of data, or **unbound**.
.. class:: Form
To create an unbound :class:`Form` instance, simply instantiate the class::
To create an unbound :class:`Form` instance, instantiate the class::
>>> f = ContactForm()
@@ -158,8 +158,9 @@ By default, ``as_json()`` does not escape its output. If you are using it for
something like AJAX requests to a form view where the client interprets the
response and inserts errors into the page, you'll want to be sure to escape the
results on the client-side to avoid the possibility of a cross-site scripting
attack. It's trivial to do so using a JavaScript library like jQuery - simply
use ``$(el).text(errorText)`` rather than ``.html()``.
attack. You can do this in JavaScript with ``element.textContent = errorText``
or with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()``
function).
If for some reason you don't want to use client-side escaping, you can also
set ``escape_html=True`` and error messages will be escaped so you can use them
@@ -185,7 +186,7 @@ should be added. If its value is ``None`` the error will be treated as
a non-field error as returned by :meth:`Form.non_field_errors()
<django.forms.Form.non_field_errors>`.
The ``error`` argument can be a simple string, or preferably an instance of
The ``error`` argument can be a string, or preferably an instance of
``ValidationError``. See :ref:`raising-validation-error` for best practices
when defining form errors.
@@ -434,7 +435,7 @@ Outputting forms as HTML
========================
The second task of a ``Form`` object is to render itself as HTML. To do so,
simply ``print`` it::
``print`` it::
>>> f = ContactForm()
>>> print(f)
@@ -563,7 +564,7 @@ errors. For example, you might want to present required form rows in bold and
highlight errors in red.
The :class:`Form` class has a couple of hooks you can use to add ``class``
attributes to required rows or to rows with errors: simply set the
attributes to required rows or to rows with errors: set the
:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`
attributes::
@@ -634,7 +635,7 @@ tags nor ``id`` attributes::
<p>Cc myself: <input type="checkbox" name="cc_myself"></p>
If ``auto_id`` is set to ``True``, then the form output *will* include
``<label>`` tags and will simply use the field name as its ``id`` for each form
``<label>`` tags and will use the field name as its ``id`` for each form
field::
>>> f = ContactForm(auto_id=True)
@@ -750,7 +751,7 @@ In the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are
displayed in the order in which you define them in your form class. For
example, in the ``ContactForm`` example, the fields are defined in the order
``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML
output, just change the order in which those fields are listed in the class.
output, change the order in which those fields are listed in the class.
There are several other ways to customize the order:
@@ -833,7 +834,7 @@ pass that in at construction time::
More granular output
====================
The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are simply shortcuts --
The ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts --
they're not the only way a form object can be displayed.
.. class:: BoundField
@@ -1121,8 +1122,8 @@ form data)::
# Bound form with an image field, data from the request
>>> f = ContactFormWithMugshot(request.POST, request.FILES)
Constructing an unbound form is the same as always -- just omit both
form data *and* file data::
Constructing an unbound form is the same as always -- omit both form data *and*
file data::
# Unbound form with an image field
>>> f = ContactFormWithMugshot()

View File

@@ -1239,12 +1239,11 @@ method::
Creating custom fields
======================
If the built-in ``Field`` classes don't meet your needs, you can easily create
custom ``Field`` classes. To do this, just create a subclass of
``django.forms.Field``. Its only requirements are that it implement a
``clean()`` method and that its ``__init__()`` method accept the core arguments
mentioned above (``required``, ``label``, ``initial``, ``widget``,
``help_text``).
If the built-in ``Field`` classes don't meet your needs, you can create custom
``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its
only requirements are that it implement a ``clean()`` method and that its
``__init__()`` method accept the core arguments mentioned above (``required``,
``label``, ``initial``, ``widget``, ``help_text``).
You can also customize how a field will be accessed by overriding
:meth:`~django.forms.Field.get_bound_field()`.

View File

@@ -19,10 +19,10 @@ for the best practice in raising ``ValidationError``. If no ``ValidationError``
is raised, the method should return the cleaned (normalized) data as a Python
object.
Most validation can be done using `validators`_ - simple helpers that can be
reused easily. Validators are simple functions (or callables) that take a single
argument and raise ``ValidationError`` on invalid input. Validators are run
after the field's ``to_python`` and ``validate`` methods have been called.
Most validation can be done using `validators`_ - helpers that can be reused.
Validators are functions (or callables) that take a single argument and raise
``ValidationError`` on invalid input. Validators are run after the field's
``to_python`` and ``validate`` methods have been called.
Validation of a form is split into several steps, which can be customized or
overridden:
@@ -65,9 +65,9 @@ overridden:
For example, if you wanted to validate that the contents of a
``CharField`` called ``serialnumber`` was unique,
``clean_serialnumber()`` would be the right place to do this. You don't
need a specific field (it's just a ``CharField``), but you want a
formfield-specific piece of validation and, possibly,
cleaning/normalizing the data.
need a specific field (it's a ``CharField``), but you want a
formfield-specific piece of validation and, possibly, cleaning/normalizing
the data.
The return value of this method replaces the existing value in
``cleaned_data``, so it must be the field's value from ``cleaned_data`` (even
@@ -218,16 +218,16 @@ previous features.
Using validators
----------------
Django's form (and model) fields support use of simple utility functions and
classes known as validators. A validator is merely a callable object or
function that takes a value and simply returns nothing if the value is valid or
raises a :exc:`~django.core.exceptions.ValidationError` if not. These can be
passed to a field's constructor, via the field's ``validators`` argument, or
defined on the :class:`~django.forms.Field` class itself with the
``default_validators`` attribute.
Django's form (and model) fields support use of utility functions and classes
known as validators. A validator is a callable object or function that takes a
value and returns nothing if the value is valid or raises a
:exc:`~django.core.exceptions.ValidationError` if not. These can be passed to a
field's constructor, via the field's ``validators`` argument, or defined on the
:class:`~django.forms.Field` class itself with the ``default_validators``
attribute.
Simple validators can be used to validate values inside the field, let's have
a look at Django's ``SlugField``::
Validators can be used to validate values inside the field, let's have a look
at Django's ``SlugField``::
from django.core import validators
from django.forms import CharField
@@ -235,9 +235,9 @@ a look at Django's ``SlugField``::
class SlugField(CharField):
default_validators = [validators.validate_slug]
As you can see, ``SlugField`` is just a ``CharField`` with a customized
validator that validates that submitted text obeys to some character rules.
This can also be done on field definition so::
As you can see, ``SlugField`` is a ``CharField`` with a customized validator
that validates that submitted text obeys to some character rules. This can also
be done on field definition so::
slug = forms.SlugField()
@@ -281,8 +281,7 @@ Every form that uses this field will have these methods run before anything
else can be done with the field's data. This is cleaning that is specific to
this type of field, regardless of how it is subsequently used.
Let's create a simple ``ContactForm`` to demonstrate how you'd use this
field::
Let's create a ``ContactForm`` to demonstrate how you'd use this field::
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
@@ -291,10 +290,10 @@ field::
recipients = MultiEmailField()
cc_myself = forms.BooleanField(required=False)
Simply use ``MultiEmailField`` like any other form field. When the
``is_valid()`` method is called on the form, the ``MultiEmailField.clean()``
method will be run as part of the cleaning process and it will, in turn, call
the custom ``to_python()`` and ``validate()`` methods.
Use ``MultiEmailField`` like any other form field. When the ``is_valid()``
method is called on the form, the ``MultiEmailField.clean()`` method will be
run as part of the cleaning process and it will, in turn, call the custom
``to_python()`` and ``validate()`` methods.
Cleaning a specific field attribute
-----------------------------------
@@ -403,7 +402,7 @@ work out what works effectively in your particular situation. Our new code
self.add_error('cc_myself', msg)
self.add_error('subject', msg)
The second argument of ``add_error()`` can be a simple string, or preferably
an instance of ``ValidationError``. See :ref:`raising-validation-error` for
more details. Note that ``add_error()`` automatically removes the field
from ``cleaned_data``.
The second argument of ``add_error()`` can be a string, or preferably an
instance of ``ValidationError``. See :ref:`raising-validation-error` for more
details. Note that ``add_error()`` automatically removes the field from
``cleaned_data``.

View File

@@ -34,8 +34,7 @@ which widget is used on which field, see the documentation about
:ref:`built-in-fields`.
However, if you want to use a different widget for a field, you can
just use the :attr:`~Field.widget` argument on the field definition. For
example::
use the :attr:`~Field.widget` argument on the field definition. For example::
from django import forms
@@ -127,7 +126,7 @@ need to specify additional attributes at the time when the widget object is
instantiated and assigned to a form field (and perhaps add some rules to your
CSS files).
For example, take the following simple form::
For example, take the following form::
from django import forms
@@ -770,8 +769,8 @@ that specifies the template used to render each choice. For example, for the
</label>
If you decide not to loop over the radio buttons -- e.g., if your template
simply includes ``{{ myform.beatles }}`` -- they'll be output in a ``<ul>``
with ``<li>`` tags, as above.
includes ``{{ myform.beatles }}`` -- they'll be output in a ``<ul>`` with
``<li>`` tags, as above.
The outer ``<ul>`` container receives the ``id`` attribute of the widget,
if defined, or :attr:`BoundField.auto_id` otherwise.

View File

@@ -20,10 +20,10 @@ manipulation. You can also write your own ``Operation`` classes if you want
to encapsulate a custom change you commonly make.
If you need an empty migration file to write your own ``Operation`` objects
into, just use ``python manage.py makemigrations --empty yourappname``,
but be aware that manually adding schema-altering operations can confuse the
migration autodetector and make resulting runs of :djadmin:`makemigrations`
output incorrect code.
into, use ``python manage.py makemigrations --empty yourappname``, but be aware
that manually adding schema-altering operations can confuse the migration
autodetector and make resulting runs of :djadmin:`makemigrations` output
incorrect code.
All of the core Django operations are available from the
``django.db.migrations.operations`` module.
@@ -53,8 +53,8 @@ The field instance should be an unbound field (so just
``bases`` is an optional list of other classes to have this model inherit from;
it can contain both class objects as well as strings in the format
``"appname.ModelName"`` if you want to depend on another model (so you inherit
from the historical version). If it's not supplied, it defaults to just
inheriting from the standard ``models.Model``.
from the historical version). If it's not supplied, it defaults to inheriting
from the standard ``models.Model``.
``managers`` takes a list of 2-tuples of ``(manager_name, manager_instance)``.
The first manager in the list will be the default manager for this model during
@@ -318,9 +318,8 @@ The optional ``elidable`` argument determines whether or not the operation will
be removed (elided) when :ref:`squashing migrations <migration-squashing>`.
You are advised to write the code as a separate function above the ``Migration``
class in the migration file, and just pass it to ``RunPython``. Here's an
example of using ``RunPython`` to create some initial objects on a ``Country``
model::
class in the migration file, and pass it to ``RunPython``. Here's an example of
using ``RunPython`` to create some initial objects on a ``Country`` model::
from django.db import migrations
@@ -423,8 +422,8 @@ Writing your own
================
Operations have a relatively simple API, and they're designed so that you can
easily write your own to supplement the built-in Django ones. The basic structure
of an ``Operation`` looks like this::
easily write your own to supplement the built-in Django ones. The basic
structure of an ``Operation`` looks like this::
from django.db.migrations.operations.base import Operation
@@ -462,21 +461,21 @@ of an ``Operation`` looks like this::
return "Custom Operation"
You can take this template and work from it, though we suggest looking at the
built-in Django operations in ``django.db.migrations.operations`` - they're
easy to read and cover a lot of the example usage of semi-internal aspects
of the migration framework like ``ProjectState`` and the patterns used to get
historical models, as well as ``ModelState`` and the patterns used to mutate
historical models in ``state_forwards()``.
built-in Django operations in ``django.db.migrations.operations`` - they cover
a lot of the example usage of semi-internal aspects of the migration framework
like ``ProjectState`` and the patterns used to get historical models, as well
as ``ModelState`` and the patterns used to mutate historical models in
``state_forwards()``.
Some things to note:
* You don't need to learn too much about ``ProjectState`` to just write simple
migrations; just know that it has an ``apps`` property that gives access to
an app registry (which you can then call ``get_model`` on).
* You don't need to learn too much about ``ProjectState`` to write migrations;
just know that it has an ``apps`` property that gives access to an app
registry (which you can then call ``get_model`` on).
* ``database_forwards`` and ``database_backwards`` both get two states passed
to them; these just represent the difference the ``state_forwards`` method
would have applied, but are given to you for convenience and speed reasons.
to them; these represent the difference the ``state_forwards`` method would
have applied, but are given to you for convenience and speed reasons.
* If you want to work with model classes or model instances from the
``from_state`` argument in ``database_forwards()`` or
@@ -506,9 +505,9 @@ Some things to note:
for the :class:`~django.db.models.Manager` instances in
``ModelState.managers``.
As a simple example, let's make an operation that loads PostgreSQL extensions
(which contain some of PostgreSQL's more exciting features). It's simple enough;
there's no model state changes, and all it does is run one command::
As an example, let's make an operation that loads PostgreSQL extensions (which
contain some of PostgreSQL's more exciting features). Since there's no model
state changes, all it does is run one command::
from django.db.migrations.operations.base import Operation

View File

@@ -96,7 +96,7 @@ A ``Case()`` expression is like the :keyword:`if` ... :keyword:`elif` ...
truthful value. The ``result`` expression from the matching ``When()`` object
is returned.
A simple example::
An example::
>>>
>>> from datetime import date, timedelta

View File

@@ -98,8 +98,7 @@ into Python memory.
Instead, Django uses the ``F()`` object to generate an SQL expression that
describes the required operation at the database level.
This is easiest to understand through an example. Normally, one might do
something like this::
Let's try this with an example. Normally, one might do something like this::
# Tintin filed a news story!
reporter = Reporters.objects.get(name='Tintin')
@@ -167,7 +166,7 @@ Python - update a field's value avoids a *race condition*.
If two Python threads execute the code in the first example above, one thread
could retrieve, increment, and save a field's value after the other has
retrieved it from the database. The value that the second thread saves will be
based on the original value; the work of the first thread will simply be lost.
based on the original value; the work of the first thread will be lost.
If the database is responsible for updating the field, the process is more
robust: it will only ever update the field based on the value of the field in
@@ -443,9 +442,9 @@ into the ``template`` attribute.
Creating your own Aggregate Functions
-------------------------------------
Creating your own aggregate is extremely easy. At a minimum, you need
to define ``function``, but you can also completely customize the
SQL that is generated. Here's a brief example::
You can create your own aggregate functions, too. At a minimum, you need to
define ``function``, but you can also completely customize the SQL that is
generated. Here's a brief example::
from django.db.models import Aggregate
@@ -496,8 +495,8 @@ output value.
.. class:: ExpressionWrapper(expression, output_field)
``ExpressionWrapper`` simply surrounds another expression and provides access
to properties, such as ``output_field``, that may not be available on other
``ExpressionWrapper`` surrounds another expression and provides access to
properties, such as ``output_field``, that may not be available on other
expressions. ``ExpressionWrapper`` is necessary when using arithmetic on
``F()`` expressions with different types as described in
:ref:`using-f-with-annotations`.
@@ -754,8 +753,8 @@ The ``order_by`` argument accepts a sequence of expressions on which you can
call :meth:`~django.db.models.Expression.asc` and
:meth:`~django.db.models.Expression.desc`. The ordering controls the order in
which the expression is applied. For example, if you sum over the rows in a
partition, the first result is just the value of the first row, the second is
the sum of first and second row.
partition, the first result is the value of the first row, the second is the
sum of first and second row.
The ``frame`` parameter specifies which other rows that should be used in the
computation. See :ref:`window-frames` for details.
@@ -773,7 +772,7 @@ the same studio in the same genre and release year::
>>> ),
>>> )
This makes it easy to check if a movie is rated better or worse than its peers.
This allows you to check if a movie is rated better or worse than its peers.
You may want to apply multiple expressions over the same window, i.e., the
same partition and frame. For example, you could modify the previous example
@@ -1061,7 +1060,7 @@ We do some basic validation on the parameters, including requiring at least
the eventual result to.
Now we implement the pre-processing and validation. Since we do not have
any of our own validation at this point, we just delegate to the nested
any of our own validation at this point, we delegate to the nested
expressions::
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):

View File

@@ -127,7 +127,7 @@ define a suitably-named constant for each value::
Though you can define a choices list outside of a model class and then
refer to it, defining the choices and names for each choice inside the
model class keeps all of that information with the class that uses it,
and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
and helps reference the choices (e.g, ``Student.SOPHOMORE``
will work anywhere that the ``Student`` model has been imported).
In addition, Django provides enumeration types that you can subclass to define
@@ -634,10 +634,10 @@ Any combination of these options will result in an error.
The ``auto_now`` and ``auto_now_add`` options will always use the date in
the :ref:`default timezone <default-current-time-zone>` at the moment of
creation or update. If you need something different, you may want to
consider simply using your own callable default or overriding ``save()``
instead of using ``auto_now`` or ``auto_now_add``; or using a
``DateTimeField`` instead of a ``DateField`` and deciding how to handle the
conversion from datetime to date at display time.
consider using your own callable default or overriding ``save()`` instead
of using ``auto_now`` or ``auto_now_add``; or using a ``DateTimeField``
instead of a ``DateField`` and deciding how to handle the conversion from
datetime to date at display time.
``DateTimeField``
-----------------
@@ -1582,7 +1582,7 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
if it is a profile model designed specifically for your custom user model.
Setting it to ``False`` does not mean you can reference a swappable model
even if it is swapped out - ``False`` just means that the migrations made
even if it is swapped out - ``False`` means that the migrations made
with this ForeignKey will always reference the exact model you specify
(so it will fail hard if the user tries to run with a User model you don't
support, for example).

View File

@@ -16,14 +16,14 @@ Throughout this reference we'll use the :ref:`example Weblog models
Creating objects
================
To create a new instance of a model, just instantiate it like any other Python
To create a new instance of a model, instantiate it like any other Python
class:
.. class:: Model(**kwargs)
The keyword arguments are simply the names of the fields you've defined on your
model. Note that instantiating a model in no way touches your database; for
that, you need to :meth:`~Model.save()`.
The keyword arguments are the names of the fields you've defined on your model.
Note that instantiating a model in no way touches your database; for that, you
need to :meth:`~Model.save()`.
.. note::
@@ -116,8 +116,8 @@ are loaded from the database::
super().save(*args, **kwargs)
The example above shows a full ``from_db()`` implementation to clarify how that
is done. In this case it would of course be possible to just use ``super()`` call
in the ``from_db()`` method.
is done. In this case it would of course be possible to use ``super()`` call in
the ``from_db()`` method.
Refreshing objects from database
================================
@@ -396,8 +396,8 @@ Explicitly specifying auto-primary-key values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a model has an :class:`~django.db.models.AutoField` but you want to define a
new object's ID explicitly when saving, just define it explicitly before
saving, rather than relying on the auto-assignment of the ID::
new object's ID explicitly when saving, define it explicitly before saving,
rather than relying on the auto-assignment of the ID::
>>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b3.id # Returns 3.
@@ -500,8 +500,8 @@ In some rare circumstances, it's necessary to be able to force the
doing an ``UPDATE``. Or vice-versa: update, if possible, but not insert a new
row. In these cases you can pass the ``force_insert=True`` or
``force_update=True`` parameters to the :meth:`~Model.save()` method.
Obviously, passing both parameters is an error: you cannot both insert *and*
update at the same time!
Passing both parameters is an error: you cannot both insert *and* update at the
same time!
It should be very rare that you'll need to use these parameters. Django will
almost always do the right thing and trying to override that will lead to
@@ -749,9 +749,9 @@ This template code is much better:
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>
The logic here is that if you change the URL structure of your objects, even
for something simple such as correcting a spelling error, you don't want to
have to track down every place that the URL might be created. Specify it once,
in ``get_absolute_url()`` and have all your other code call that one place.
for something small like correcting a spelling error, you don't want to have to
track down every place that the URL might be created. Specify it once, in
``get_absolute_url()`` and have all your other code call that one place.
.. note::
The string you return from ``get_absolute_url()`` **must** contain only

View File

@@ -151,8 +151,8 @@ Here's the formal declaration of a ``QuerySet``:
The ``query`` parameter to :class:`QuerySet` exists so that specialized
query subclasses can reconstruct internal query state. The value of the
parameter is an opaque representation of that query state and is not
part of a public API. To put it simply: if you need to ask, you don't
need to use it.
part of a public API. To put it another way: if you need to ask, you
don't need to use it.
.. currentmodule:: django.db.models.query.QuerySet
@@ -1943,7 +1943,7 @@ details. The internal implementation has some more error-checking than this and
handles some extra edge-conditions; if you're interested, read the code.
If you have a field named ``defaults`` and want to use it as an exact lookup in
``get_or_create()``, just use ``'defaults__exact'``, like so::
``get_or_create()``, use ``'defaults__exact'``, like so::
Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})
@@ -2418,8 +2418,8 @@ gains).
Additionally, if a ``some_queryset`` has not yet been evaluated, but you know
that it will be at some point, then using ``some_queryset.exists()`` will do
more overall work (one query for the existence check plus an extra one to later
retrieve the results) than simply using ``bool(some_queryset)``, which
retrieves the results and then checks if any were returned.
retrieve the results) than using ``bool(some_queryset)``, which retrieves the
results and then checks if any were returned.
``update()``
~~~~~~~~~~~~

View File

@@ -91,7 +91,7 @@ Related objects reference
# No need to call e.save() at this point -- it's already been saved.
This is equivalent to (but much simpler than)::
This is equivalent to (but simpler than)::
>>> b = Blog.objects.get(id=1)
>>> e = Entry(

View File

@@ -34,10 +34,10 @@ If you are writing or maintaining a third-party database backend for Django,
you will need to provide a ``SchemaEditor`` implementation in order to work with
1.7's migration functionality - however, as long as your database is relatively
standard in its use of SQL and relational design, you should be able to
subclass one of the built-in Django ``SchemaEditor`` classes and just tweak the
subclass one of the built-in Django ``SchemaEditor`` classes and tweak the
syntax a little. Also note that there are a few new database features that
migrations will look for: ``can_rollback_ddl`` and
``supports_combined_alters`` are the most important.
migrations will look for: ``can_rollback_ddl``
and ``supports_combined_alters`` are the most important.
Methods
=======
@@ -48,8 +48,8 @@ Methods
.. method:: BaseDatabaseSchemaEditor.execute(sql, params=[])
Executes the SQL statement passed in, with parameters if supplied. This
is a simple wrapper around the normal database cursors that allows
capture of the SQL to a ``.sql`` file if the user wishes.
is a wrapper around the normal database cursors that allows capture of the SQL
to a ``.sql`` file if the user wishes.
``create_model()``
------------------

View File

@@ -196,8 +196,8 @@ See the :ref:`cache documentation <cache_key_prefixing>` for more information.
Default: ``''`` (Empty string)
The location of the cache to use. This might be the directory for a
file system cache, a host and port for a memcache server, or simply an
identifying name for a local memory cache. e.g.::
file system cache, a host and port for a memcache server, or an identifying
name for a local memory cache. e.g.::
CACHES = {
'default': {
@@ -2443,8 +2443,8 @@ A list containing the settings for all template engines to be used with
Django. Each item of the list is a dictionary containing the options for an
individual engine.
Here's a simple setup that tells the Django template engine to load templates
from the ``templates`` subdirectory inside each installed application::
Here's a setup that tells the Django template engine to load templates from the
``templates`` subdirectory inside each installed application::
TEMPLATES = [
{
@@ -2657,7 +2657,7 @@ the correct environment.
Default: ``True``
A boolean that specifies whether Django's translation system should be enabled.
This provides an easy way to turn it off, for performance. If this is set to
This provides a way to turn it off, for performance. If this is set to
``False``, Django will make some optimizations so as not to load the
translation machinery.
@@ -2759,7 +2759,7 @@ Default: ``None``
The full Python path of the WSGI application object that Django's built-in
servers (e.g. :djadmin:`runserver`) will use. The :djadmin:`django-admin
startproject <startproject>` management command will create a simple
startproject <startproject>` management command will create a standard
``wsgi.py`` file with an ``application`` callable in it, and point this setting
to that ``application``.
@@ -3374,7 +3374,7 @@ setting.
.. note::
When using the ``AppDirectoriesFinder`` finder, make sure your apps
can be found by staticfiles. Simply add the app to the
can be found by staticfiles by adding the app to the
:setting:`INSTALLED_APPS` setting of your site.
Static file finders are currently considered a private interface, and this

View File

@@ -239,7 +239,7 @@ Some operations -- such as caching -- cannot be performed on an
unrendered template. They must be performed on a fully complete and
rendered response.
If you're using middleware, the solution is easy. Middleware provides
If you're using middleware, you can do that. Middleware provides
multiple opportunities to process a response on exit from a view. If
you put behavior in the response middleware, it's guaranteed to execute
after template rendering has taken place.
@@ -253,7 +253,7 @@ be invoked when rendering has completed. Using this callback, you can
defer critical processing until a point where you can guarantee that
rendered content will be available.
To define a post-render callback, just define a function that takes
To define a post-render callback, define a function that takes
a single argument -- response -- and register that function with
the template response::
@@ -285,8 +285,8 @@ A :class:`TemplateResponse` object can be used anywhere that a normal
:class:`django.http.HttpResponse` can be used. It can also be used as an
alternative to calling :func:`~django.shortcuts.render()`.
For example, the following simple view returns a :class:`TemplateResponse`
with a simple template and a context containing a queryset::
For example, the following view returns a :class:`TemplateResponse` with a
template and a context containing a queryset::
from django.template.response import TemplateResponse

View File

@@ -5,7 +5,7 @@ The Django template language: for Python programmers
.. currentmodule:: django.template
This document explains the Django template system from a technical
perspective -- how it works and how to extend it. If you're just looking for
perspective -- how it works and how to extend it. If you're looking for
reference on the language syntax, see :doc:`/ref/templates/language`.
It assumes an understanding of templates, contexts, variables, tags, and
@@ -41,12 +41,12 @@ lower level APIs:
Configuring an engine
=====================
If you are simply using the
:class:`~django.template.backends.django.DjangoTemplates` backend, this
probably isn't the documentation you're looking for. An instance of the
``Engine`` class described below is accessible using the ``engine`` attribute
of that backend and any attribute defaults mentioned below are overridden by
what's passed by :class:`~django.template.backends.django.DjangoTemplates`.
If you are using the :class:`~django.template.backends.django.DjangoTemplates`
backend, this probably isn't the documentation you're looking for. An instance
of the ``Engine`` class described below is accessible using the ``engine``
attribute of that backend and any attribute defaults mentioned below are
overridden by what's passed by
:class:`~django.template.backends.django.DjangoTemplates`.
.. class:: Engine(dirs=None, app_dirs=False, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8', libraries=None, builtins=None, autoescape=True)
@@ -315,9 +315,8 @@ straight lookups. Here are some things to keep in mind:
.. _alters-data-description:
* Obviously, there can be side effects when calling some variables, and
it'd be either foolish or a security hole to allow the template system
to access them.
* There can be side effects when calling some variables, and it'd be either
foolish or a security hole to allow the template system to access them.
A good example is the :meth:`~django.db.models.Model.delete` method on
each Django model object. The template system shouldn't be allowed to do
@@ -754,10 +753,10 @@ variables:
Writing your own context processors
-----------------------------------
A context processor has a very simple interface: It's a Python function
that takes one argument, an :class:`~django.http.HttpRequest` object, and
returns a dictionary that gets added to the template context. Each context
processor *must* return a dictionary.
A context processor has a simple interface: It's a Python function that takes
one argument, an :class:`~django.http.HttpRequest` object, and returns a
dictionary that gets added to the template context. Each context processor
*must* return a dictionary.
Custom context processors can live anywhere in your code base. All Django
cares about is that your custom context processors are pointed to by the
@@ -859,7 +858,7 @@ loaders that come with Django:
subdirectory. If the directory exists, Django looks for templates in there.
This means you can store templates with your individual apps. This also
makes it easy to distribute Django apps with default templates.
helps to distribute Django apps with default templates.
For example, for this setting::
@@ -885,8 +884,8 @@ loaders that come with Django:
it caches a list of which :setting:`INSTALLED_APPS` packages have a
``templates`` subdirectory.
You can enable this loader simply by setting
:setting:`APP_DIRS <TEMPLATES-APP_DIRS>` to ``True``::
You can enable this loader by setting :setting:`APP_DIRS
<TEMPLATES-APP_DIRS>` to ``True``::
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',

View File

@@ -123,7 +123,7 @@ You can mix variables and strings::
In some cases you might want to refer to the current value of a cycle
without advancing to the next value. To do this,
just give the ``{% cycle %}`` tag a name, using "as", like this::
give the ``{% cycle %}`` tag a name, using "as", like this::
{% cycle 'row1' 'row2' as rowcolors %}
@@ -2182,9 +2182,9 @@ the output will be the string ``"01:23"`` (The ``"TIME_FORMAT"`` format
specifier for the ``de`` locale as shipped with Django is ``"H:i"``).
The ``time`` filter will only accept parameters in the format string that
relate to the time of day, not the date (for obvious reasons). If you need to
format a ``date`` value, use the :tfilter:`date` filter instead (or along
``time`` if you need to render a full :py:class:`~datetime.datetime` value).
relate to the time of day, not the date. If you need to format a ``date``
value, use the :tfilter:`date` filter instead (or along with :tfilter:`time` if
you need to render a full :py:class:`~datetime.datetime` value).
There is one exception the above rule: When passed a ``datetime`` value with
attached timezone information (a :ref:`time-zone-aware

View File

@@ -36,8 +36,8 @@ Templates
.. highlightlang:: html+django
A template is simply a text file. It can generate any text-based format (HTML,
XML, CSV, etc.).
A template is a text file. It can generate any text-based format (HTML, XML,
CSV, etc.).
A template contains **variables**, which get replaced with values when the
template is evaluated, and **tags**, which control the logic of the template.
@@ -289,7 +289,7 @@ engine is template inheritance. Template inheritance allows you to build a base
"skeleton" template that contains all the common elements of your site and
defines **blocks** that child templates can override.
It's easiest to understand template inheritance by starting with an example::
Let's look at template inheritance by starting with an example::
<!DOCTYPE html>
<html lang="en">
@@ -314,9 +314,9 @@ It's easiest to understand template inheritance by starting with an example::
</body>
</html>
This template, which we'll call ``base.html``, defines a simple HTML skeleton
document that you might use for a simple two-column page. It's the job of
"child" templates to fill the empty blocks with content.
This template, which we'll call ``base.html``, defines an HTML skeleton
document that you might use for a two-column page. It's the job of "child"
templates to fill the empty blocks with content.
In this example, the :ttag:`block` tag defines three blocks that child
templates can fill in. All the :ttag:`block` tag does is to tell the template
@@ -386,8 +386,8 @@ inheritance is the following three-level approach:
article or blog entry. These templates extend the appropriate section
template.
This approach maximizes code reuse and makes it easy to add items to shared
content areas, such as section-wide navigation.
This approach maximizes code reuse and helps to add items to shared content
areas, such as section-wide navigation.
Here are some tips for working with inheritance:
@@ -533,8 +533,8 @@ the output will be::
For template blocks
~~~~~~~~~~~~~~~~~~~
To control auto-escaping for a template, wrap the template (or just a
particular section of the template) in the :ttag:`autoescape` tag, like so::
To control auto-escaping for a template, wrap the template (or a particular
section of the template) in the :ttag:`autoescape` tag, like so::
{% autoescape off %}
Hello {{ name }}

View File

@@ -103,8 +103,8 @@ need to distinguish caches by the ``Accept-language`` header.
The list of headers to use for cache key generation is stored in the same
cache as the pages themselves. If the cache ages some data out of the
cache, this just means that we have to build the response once to get at
the Vary header and so at the list of headers to use for the cache key.
cache, this means that we have to build the response once to get at the
Vary header and so at the list of headers to use for the cache key.
``django.utils.dateparse``
==========================
@@ -491,9 +491,9 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004
As well as offering potential performance advantages, ``@cached_property``
can ensure that an attribute's value does not change unexpectedly over the
life of an instance. This could occur with a method whose computation is
based on ``datetime.now()``, or simply if a change were saved to the
database by some other process in the brief interval between subsequent
invocations of a method on the same instance.
based on ``datetime.now()``, or if a change were saved to the database by
some other process in the brief interval between subsequent invocations of
a method on the same instance.
You can make cached properties of methods. For example, if you had an
expensive ``get_friends()`` method and wanted to allow calling it without
@@ -551,9 +551,9 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004
The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
specifying the type(s) that the original function can return. A common
use case is to have functions that return text. For these, you can just
pass the ``str`` type to ``keep_lazy`` (or even simpler, use the
:func:`keep_lazy_text` decorator described in the next section).
use case is to have functions that return text. For these, you can pass the
``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator
described in the next section).
Using this decorator means you can write your function and assume that the
input is a proper string, then add support for lazy translation objects at
@@ -564,7 +564,8 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004
A shortcut for ``keep_lazy(str)(func)``.
If you have a function that returns text and you want to be able to take
lazy arguments while delaying their evaluation, simply use this decorator::
lazy arguments while delaying their evaluation, you can use this
decorator::
from django.utils.functional import keep_lazy, keep_lazy_text
@@ -1060,7 +1061,7 @@ functions without the ``u``.
:func:`django.utils.translation.activate` to fetch the translation object
for a given language, activates it as the translation object for the
current thread and reactivates the previous active language on exit.
Optionally, it can simply deactivate the temporary translation on exit with
Optionally, it can deactivate the temporary translation on exit with
:func:`django.utils.translation.deactivate` if the ``deactivate`` argument
is ``True``. If you pass ``None`` as the language argument, a
``NullTranslations()`` instance is activated within the context.

View File

@@ -66,9 +66,9 @@ The 404 (page not found) view
When you raise :exc:`~django.http.Http404` from within a view, Django loads a
special view devoted to handling 404 errors. By default, it's the view
:func:`django.views.defaults.page_not_found`, which either produces a very
simple "Not Found" message or loads and renders the template ``404.html`` if
you created it in your root template directory.
:func:`django.views.defaults.page_not_found`, which either produces a "Not
Found" message or loads and renders the template ``404.html`` if you created it
in your root template directory.
The default 404 view will pass two variables to the template: ``request_path``,
which is the URL that resulted in the error, and ``exception``, which is a
@@ -97,9 +97,9 @@ The 500 (server error) view
Similarly, Django executes special-case behavior in the case of runtime errors
in view code. If a view results in an exception, Django will, by default, call
the view ``django.views.defaults.server_error``, which either produces a very
simple "Server Error" message or loads and renders the template ``500.html`` if
you created it in your root template directory.
the view ``django.views.defaults.server_error``, which either produces a
"Server Error" message or loads and renders the template ``500.html`` if you
created it in your root template directory.
The default 500 view passes no variables to the ``500.html`` template and is
rendered with an empty ``Context`` to lessen the chance of additional errors.