summaryrefslogtreecommitdiff
path: root/docs/topics
diff options
context:
space:
mode:
authorLuke Plant <L.Plant.98@cantab.net>2011-10-14 00:12:01 +0000
committerLuke Plant <L.Plant.98@cantab.net>2011-10-14 00:12:01 +0000
commitd1e5c55258d624058a93c8cacdb1f25ae7857554 (patch)
treedca859edc2229f68b7511687aa8b333378786633 /docs/topics
parent5109ac370928a5924887424b6d6c803038fcb691 (diff)
Fixed many more ReST indentation errors, somehow accidentally missed from [16955]
git-svn-id: http://code.djangoproject.com/svn/django/trunk@16983 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'docs/topics')
-rw-r--r--docs/topics/cache.txt170
-rw-r--r--docs/topics/class-based-views.txt26
-rw-r--r--docs/topics/conditional-view-processing.txt32
-rw-r--r--docs/topics/db/managers.txt36
-rw-r--r--docs/topics/db/models.txt270
-rw-r--r--docs/topics/db/optimization.txt22
-rw-r--r--docs/topics/db/queries.txt74
-rw-r--r--docs/topics/db/transactions.txt34
-rw-r--r--docs/topics/email.txt166
-rw-r--r--docs/topics/forms/index.txt68
-rw-r--r--docs/topics/forms/modelforms.txt124
-rw-r--r--docs/topics/generic-views-migration.txt36
-rw-r--r--docs/topics/generic-views.txt26
-rw-r--r--docs/topics/http/file-uploads.txt176
-rw-r--r--docs/topics/http/middleware.txt26
-rw-r--r--docs/topics/http/sessions.txt80
-rw-r--r--docs/topics/http/shortcuts.txt50
-rw-r--r--docs/topics/http/urls.txt176
-rw-r--r--docs/topics/http/views.txt60
-rw-r--r--docs/topics/i18n/deployment.txt146
-rw-r--r--docs/topics/i18n/index.txt36
-rw-r--r--docs/topics/i18n/internationalization.txt110
-rw-r--r--docs/topics/i18n/localization.txt46
-rw-r--r--docs/topics/install.txt20
-rw-r--r--docs/topics/logging.txt141
-rw-r--r--docs/topics/serialization.txt18
-rw-r--r--docs/topics/settings.txt20
-rw-r--r--docs/topics/signals.txt28
-rw-r--r--docs/topics/signing.txt12
-rw-r--r--docs/topics/testing.txt312
30 files changed, 1270 insertions, 1271 deletions
diff --git a/docs/topics/cache.txt b/docs/topics/cache.txt
index ae6bb5c604..768bd245b8 100644
--- a/docs/topics/cache.txt
+++ b/docs/topics/cache.txt
@@ -94,15 +94,15 @@ two most common are `python-memcached`_ and `pylibmc`_.
To use Memcached with Django:
- * Set :setting:`BACKEND <CACHES-BACKEND>` to
- ``django.core.cache.backends.memcached.MemcachedCache`` or
- ``django.core.cache.backends.memcached.PyLibMCCache`` (depending
- on your chosen memcached binding)
+* Set :setting:`BACKEND <CACHES-BACKEND>` to
+ ``django.core.cache.backends.memcached.MemcachedCache`` or
+ ``django.core.cache.backends.memcached.PyLibMCCache`` (depending
+ on your chosen memcached binding)
- * Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,
- where ``ip`` is the IP address of the Memcached daemon and ``port`` is the
- port on which Memcached is running, or to a ``unix:path`` value, where
- ``path`` is the path to a Memcached Unix socket file.
+* Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,
+ where ``ip`` is the IP address of the Memcached daemon and ``port`` is the
+ port on which Memcached is running, or to a ``unix:path`` value, where
+ ``path`` is the path to a Memcached Unix socket file.
In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
the ``python-memcached`` binding::
@@ -358,55 +358,55 @@ backend, each cache backend can be given additional arguments to
control caching behavior. These arguments are provided as additional
keys in the :setting:`CACHES` setting. Valid arguments are as follows:
- * :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in
- seconds, to use for the cache. This argument defaults to 300
- seconds (5 minutes).
+* :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in
+ seconds, to use for the cache. This argument defaults to 300
+ seconds (5 minutes).
- * :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be
- passed to cache backend. The list options understood by each
- backend vary with each backend.
+* :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be
+ passed to cache backend. The list options understood by each
+ backend vary with each backend.
- Cache backends that implement their own culling strategy (i.e.,
- the ``locmem``, ``filesystem`` and ``database`` backends) will
- honor the following options:
+ Cache backends that implement their own culling strategy (i.e.,
+ the ``locmem``, ``filesystem`` and ``database`` backends) will
+ honor the following options:
- * ``MAX_ENTRIES``: the maximum number of entries allowed in
- the cache before old values are deleted. This argument
- defaults to ``300``.
+ * ``MAX_ENTRIES``: the maximum number of entries allowed in
+ the cache before old values are deleted. This argument
+ defaults to ``300``.
- * ``CULL_FREQUENCY``: The fraction of entries that are culled
- when ``MAX_ENTRIES`` is reached. The actual ratio is
- ``1/CULL_FREQUENCY``, so set ``CULL_FREQUENCY``: to ``2`` to
- cull half of the entries when ``MAX_ENTRIES`` is reached.
+ * ``CULL_FREQUENCY``: The fraction of entries that are culled
+ when ``MAX_ENTRIES`` is reached. The actual ratio is
+ ``1/CULL_FREQUENCY``, so set ``CULL_FREQUENCY``: to ``2`` to
+ cull half of the entries when ``MAX_ENTRIES`` is reached.
- A value of ``0`` for ``CULL_FREQUENCY`` means that the
- entire cache will be dumped when ``MAX_ENTRIES`` is reached.
- This makes culling *much* faster at the expense of more
- cache misses.
+ A value of ``0`` for ``CULL_FREQUENCY`` means that the
+ entire cache will be dumped when ``MAX_ENTRIES`` is reached.
+ This makes culling *much* faster at the expense of more
+ cache misses.
- Cache backends backed by a third-party library will pass their
- options directly to the underlying cache library. As a result,
- the list of valid options depends on the library in use.
+ Cache backends backed by a third-party library will pass their
+ options directly to the underlying cache library. As a result,
+ the list of valid options depends on the library in use.
- * :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be
- automatically included (prepended by default) to all cache keys
- used by the Django server.
+* :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be
+ automatically included (prepended by default) to all cache keys
+ used by the Django server.
- See the :ref:`cache documentation <cache_key_prefixing>` for
- more information.
+ See the :ref:`cache documentation <cache_key_prefixing>` for
+ more information.
- * :setting:`VERSION <CACHES-VERSION>`: The default version number
- for cache keys generated by the Django server.
+* :setting:`VERSION <CACHES-VERSION>`: The default version number
+ for cache keys generated by the Django server.
- See the :ref:`cache documentation <cache_versioning>` for more
- information.
+ See the :ref:`cache documentation <cache_versioning>` for more
+ information.
- * :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`
- A string containing a dotted path to a function that defines how
- to compose a prefix, version and key into a final cache key.
+* :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`
+ A string containing a dotted path to a function that defines how
+ to compose a prefix, version and key into a final cache key.
- See the :ref:`cache documentation <cache_key_transformation>`
- for more information.
+ See the :ref:`cache documentation <cache_key_transformation>`
+ for more information.
In this example, a filesystem backend is being configured with a timeout
of 60 seconds, and a maximum capacity of 1000 items::
@@ -470,14 +470,14 @@ response for HEAD request.
Additionally, the cache middleware automatically sets a few headers in each
:class:`~django.http.HttpResponse`:
- * Sets the ``Last-Modified`` header to the current date/time when a fresh
- (uncached) version of the page is requested.
+* Sets the ``Last-Modified`` header to the current date/time when a fresh
+ (uncached) version of the page is requested.
- * Sets the ``Expires`` header to the current date/time plus the defined
- :setting:`CACHE_MIDDLEWARE_SECONDS`.
+* Sets the ``Expires`` header to the current date/time plus the defined
+ :setting:`CACHE_MIDDLEWARE_SECONDS`.
- * Sets the ``Cache-Control`` header to give a max age for the page --
- again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.
+* Sets the ``Cache-Control`` header to give a max age for the page --
+ again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.
See :doc:`/topics/http/middleware` for more on middleware.
@@ -932,21 +932,21 @@ reaches your Web site.
Here are a few examples of upstream caches:
- * Your ISP may cache certain pages, so if you requested a page from
- http://example.com/, your ISP would send you the page without having to
- access example.com directly. The maintainers of example.com have no
- knowledge of this caching; the ISP sits between example.com and your Web
- browser, handling all of the caching transparently.
+* Your ISP may cache certain pages, so if you requested a page from
+ http://example.com/, your ISP would send you the page without having to
+ access example.com directly. The maintainers of example.com have no
+ knowledge of this caching; the ISP sits between example.com and your Web
+ browser, handling all of the caching transparently.
- * Your Django Web site may sit behind a *proxy cache*, such as Squid Web
- Proxy Cache (http://www.squid-cache.org/), that caches pages for
- performance. In this case, each request first would be handled by the
- proxy, and it would be passed to your application only if needed.
+* Your Django Web site may sit behind a *proxy cache*, such as Squid Web
+ Proxy Cache (http://www.squid-cache.org/), that caches pages for
+ performance. In this case, each request first would be handled by the
+ proxy, and it would be passed to your application only if needed.
- * Your Web browser caches pages, too. If a Web page sends out the
- appropriate headers, your browser will use the local cached copy for
- subsequent requests to that page, without even contacting the Web page
- again to see whether it has changed.
+* Your Web browser caches pages, too. If a Web page sends out the
+ appropriate headers, your browser will use the local cached copy for
+ subsequent requests to that page, without even contacting the Web page
+ again to see whether it has changed.
Upstream caching is a nice efficiency boost, but there's a danger to it:
Many Web pages' contents differ based on authentication and a host of other
@@ -1099,12 +1099,12 @@ entries may be cached on any shared cache. The following code uses
There are a few other ways to control cache parameters. For example, HTTP
allows applications to do the following:
- * Define the maximum time a page should be cached.
+* Define the maximum time a page should be cached.
- * Specify whether a cache should always check for newer versions, only
- delivering the cached content when there are no changes. (Some caches
- might deliver cached content even if the server page changed, simply
- because the cache copy isn't yet expired.)
+* Specify whether a cache should always check for newer versions, only
+ delivering the cached content when there are no changes. (Some caches
+ might deliver cached content even if the server page changed, simply
+ because the cache copy isn't yet expired.)
In Django, use the ``cache_control`` view decorator to specify these cache
parameters. In this example, ``cache_control`` tells caches to revalidate the
@@ -1119,14 +1119,14 @@ cache on every access and to store cached versions for, at most, 3,600 seconds::
Any valid ``Cache-Control`` HTTP directive is valid in ``cache_control()``.
Here's a full list:
- * ``public=True``
- * ``private=True``
- * ``no_cache=True``
- * ``no_transform=True``
- * ``must_revalidate=True``
- * ``proxy_revalidate=True``
- * ``max_age=num_seconds``
- * ``s_maxage=num_seconds``
+* ``public=True``
+* ``private=True``
+* ``no_cache=True``
+* ``no_transform=True``
+* ``must_revalidate=True``
+* ``proxy_revalidate=True``
+* ``max_age=num_seconds``
+* ``s_maxage=num_seconds``
For explanation of Cache-Control HTTP directives, see the `Cache-Control spec`_.
@@ -1154,12 +1154,12 @@ Other optimizations
Django comes with a few other pieces of middleware that can help optimize your
site's performance:
- * ``django.middleware.http.ConditionalGetMiddleware`` adds support for
- modern browsers to conditionally GET responses based on the ``ETag``
- and ``Last-Modified`` headers.
+* ``django.middleware.http.ConditionalGetMiddleware`` adds support for
+ modern browsers to conditionally GET responses based on the ``ETag``
+ and ``Last-Modified`` headers.
- * :class:`django.middleware.gzip.GZipMiddleware` compresses responses for all
- modern browsers, saving bandwidth and transfer time.
+* :class:`django.middleware.gzip.GZipMiddleware` compresses responses for all
+ modern browsers, saving bandwidth and transfer time.
Order of MIDDLEWARE_CLASSES
===========================
@@ -1175,9 +1175,9 @@ response phase. Thus, you need to make sure that ``UpdateCacheMiddleware``
appears *before* any other middleware that might add something to the ``Vary``
header. The following middleware modules do so:
- * ``SessionMiddleware`` adds ``Cookie``
- * ``GZipMiddleware`` adds ``Accept-Encoding``
- * ``LocaleMiddleware`` adds ``Accept-Language``
+* ``SessionMiddleware`` adds ``Cookie``
+* ``GZipMiddleware`` adds ``Accept-Encoding``
+* ``LocaleMiddleware`` adds ``Accept-Language``
``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,
where middleware is applied first-to-last, so an item at the top of the list
diff --git a/docs/topics/class-based-views.txt b/docs/topics/class-based-views.txt
index 62368faee1..3812faefd2 100644
--- a/docs/topics/class-based-views.txt
+++ b/docs/topics/class-based-views.txt
@@ -29,22 +29,22 @@ be passed as an extra argument to the URLconf.
Django ships with generic views to do the following:
- * Perform common "simple" tasks: redirect to a different page and
- render a given template.
+* Perform common "simple" tasks: redirect to a different page and
+ render a given template.
- * Display list and detail pages for a single object. If we were creating an
- application to manage conferences then a ``TalkListView`` and a
- ``RegisteredUserListView`` would be examples of list views. A single
- talk page is an example of what we call a "detail" view.
+* Display list and detail pages for a single object. If we were creating an
+ application to manage conferences then a ``TalkListView`` and a
+ ``RegisteredUserListView`` would be examples of list views. A single
+ talk page is an example of what we call a "detail" view.
- * Present date-based objects in year/month/day archive pages,
- associated detail, and "latest" pages.
- `The Django Weblog <http://www.djangoproject.com/weblog/>`_'s
- year, month, and day archives are built with these, as would be a typical
- newspaper's archives.
+* Present date-based objects in year/month/day archive pages,
+ associated detail, and "latest" pages.
+ `The Django Weblog <http://www.djangoproject.com/weblog/>`_'s
+ year, month, and day archives are built with these, as would be a typical
+ newspaper's archives.
- * Allow users to create, update, and delete objects -- with or
- without authorization.
+* Allow users to create, update, and delete objects -- with or
+ without authorization.
Taken together, these views provide easy interfaces to perform the most common
tasks developers encounter.
diff --git a/docs/topics/conditional-view-processing.txt b/docs/topics/conditional-view-processing.txt
index d9b607fca2..1979e89c31 100644
--- a/docs/topics/conditional-view-processing.txt
+++ b/docs/topics/conditional-view-processing.txt
@@ -154,18 +154,18 @@ trying to change has been altered in the meantime.
For example, consider the following exchange between the client and server:
- 1. Client requests ``/foo/``.
- 2. Server responds with some content with an ETag of ``"abcd1234"``.
- 3. Client sends an HTTP ``PUT`` request to ``/foo/`` to update the
- resource. It also sends an ``If-Match: "abcd1234"`` header to specify
- the version it is trying to update.
- 4. Server checks to see if the resource has changed, by computing the ETag
- the same way it does for a ``GET`` request (using the same function).
- If the resource *has* changed, it will return a 412 status code code,
- meaning "precondition failed".
- 5. Client sends a ``GET`` request to ``/foo/``, after receiving a 412
- response, to retrieve an updated version of the content before updating
- it.
+1. Client requests ``/foo/``.
+2. Server responds with some content with an ETag of ``"abcd1234"``.
+3. Client sends an HTTP ``PUT`` request to ``/foo/`` to update the
+ resource. It also sends an ``If-Match: "abcd1234"`` header to specify
+ the version it is trying to update.
+4. Server checks to see if the resource has changed, by computing the ETag
+ the same way it does for a ``GET`` request (using the same function).
+ If the resource *has* changed, it will return a 412 status code code,
+ meaning "precondition failed".
+5. Client sends a ``GET`` request to ``/foo/``, after receiving a 412
+ response, to retrieve an updated version of the content before updating
+ it.
The important thing this example shows is that the same functions can be used
to compute the ETag and last modification values in all situations. In fact,
@@ -182,10 +182,10 @@ conditional ``GET`` handling via the
easy to use and suitable for many situations, those pieces of middleware
functionality have limitations for advanced usage:
- * They are applied globally to all views in your project
- * They don't save you from generating the response itself, which may be
- expensive
- * They are only appropriate for HTTP ``GET`` requests.
+* They are applied globally to all views in your project
+* They don't save you from generating the response itself, which may be
+ expensive
+* They are only appropriate for HTTP ``GET`` requests.
You should choose the most appropriate tool for your particular problem here.
If you have a way to compute ETags and modification times quickly and if some
diff --git a/docs/topics/db/managers.txt b/docs/topics/db/managers.txt
index cbe381d46e..eda6f9dac0 100644
--- a/docs/topics/db/managers.txt
+++ b/docs/topics/db/managers.txt
@@ -205,26 +205,26 @@ first manager declared is the *default manager*, it is important to allow that
to be controlled. So here's how Django handles custom managers and
:ref:`model inheritance <model-inheritance>`:
- 1. Managers defined on non-abstract base classes are *not* inherited by
- child classes. If you want to reuse a manager from a non-abstract base,
- redeclare it explicitly on the child class. These sorts of managers are
- likely to be fairly specific to the class they are defined on, so
- inheriting them can often lead to unexpected results (particularly as
- far as the default manager goes). Therefore, they aren't passed onto
- child classes.
+1. Managers defined on non-abstract base classes are *not* inherited by
+ child classes. If you want to reuse a manager from a non-abstract base,
+ redeclare it explicitly on the child class. These sorts of managers are
+ likely to be fairly specific to the class they are defined on, so
+ inheriting them can often lead to unexpected results (particularly as
+ far as the default manager goes). Therefore, they aren't passed onto
+ child classes.
- 2. Managers from abstract base classes are always inherited by the child
- class, using Python's normal name resolution order (names on the child
- class override all others; then come names on the first parent class,
- and so on). Abstract base classes are designed to capture information
- and behavior that is common to their child classes. Defining common
- managers is an appropriate part of this common information.
+2. Managers from abstract base classes are always inherited by the child
+ class, using Python's normal name resolution order (names on the child
+ class override all others; then come names on the first parent class,
+ and so on). Abstract base classes are designed to capture information
+ and behavior that is common to their child classes. Defining common
+ managers is an appropriate part of this common information.
- 3. The default manager on a class is either the first manager declared on
- the class, if that exists, or the default manager of the first abstract
- base class in the parent hierarchy, if that exists. If no default
- manager is explicitly declared, Django's normal default manager is
- used.
+3. The default manager on a class is either the first manager declared on
+ the class, if that exists, or the default manager of the first abstract
+ base class in the parent hierarchy, if that exists. If no default
+ manager is explicitly declared, Django's normal default manager is
+ used.
These rules provide the necessary flexibility if you want to install a
collection of custom managers on a group of models, via an abstract base
diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt
index 465d9193a4..e16622ef06 100644
--- a/docs/topics/db/models.txt
+++ b/docs/topics/db/models.txt
@@ -10,13 +10,13 @@ model maps to a single database table.
The basics:
- * Each model is a Python class that subclasses
- :class:`django.db.models.Model`.
+* Each model is a Python class that subclasses
+ :class:`django.db.models.Model`.
- * Each attribute of the model represents a database field.
+* Each attribute of the model represents a database field.
- * With all of this, Django gives you an automatically-generated
- database-access API; see :doc:`/topics/db/queries`.
+* With all of this, Django gives you an automatically-generated
+ database-access API; see :doc:`/topics/db/queries`.
.. seealso::
@@ -53,16 +53,16 @@ The above ``Person`` model would create a database table like this:
Some technical notes:
- * The name of the table, ``myapp_person``, is automatically derived from
- some model metadata but can be overridden. See :ref:`table-names` for more
- details..
+* The name of the table, ``myapp_person``, is automatically derived from
+ some model metadata but can be overridden. See :ref:`table-names` for more
+ details..
- * An ``id`` field is added automatically, but this behavior can be
- overridden. See :ref:`automatic-primary-key-fields`.
+* An ``id`` field is added automatically, but this behavior can be
+ overridden. See :ref:`automatic-primary-key-fields`.
- * The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
- syntax, but it's worth noting Django uses SQL tailored to the database
- backend specified in your :doc:`settings file </topics/settings>`.
+* The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
+ syntax, but it's worth noting Django uses SQL tailored to the database
+ backend specified in your :doc:`settings file </topics/settings>`.
Using models
============
@@ -113,13 +113,13 @@ Each field in your model should be an instance of the appropriate
:class:`~django.db.models.Field` class. Django uses the field class types to
determine a few things:
- * The database column type (e.g. ``INTEGER``, ``VARCHAR``).
+* The database column type (e.g. ``INTEGER``, ``VARCHAR``).
- * The :doc:`widget </ref/forms/widgets>` to use in Django's admin interface,
- if you care to use it (e.g. ``<input type="text">``, ``<select>``).
+* The :doc:`widget </ref/forms/widgets>` to use in Django's admin interface,
+ if you care to use it (e.g. ``<input type="text">``, ``<select>``).
- * The minimal validation requirements, used in Django's admin and in
- automatically-generated forms.
+* The minimal validation requirements, used in Django's admin and in
+ automatically-generated forms.
Django ships with dozens of built-in field types; you can find the complete list
in the :ref:`model field reference <model-field-types>`. You can easily write
@@ -140,83 +140,83 @@ optional. They're fully explained in the :ref:`reference
<common-model-field-options>`, but here's a quick summary of the most often-used
ones:
- :attr:`~Field.null`
- If ``True``, Django will store empty values as ``NULL`` in the database.
- Default is ``False``.
+:attr:`~Field.null`
+ If ``True``, Django will store empty values as ``NULL`` in the database.
+ Default is ``False``.
- :attr:`~Field.blank`
- If ``True``, the field is allowed to be blank. Default is ``False``.
+:attr:`~Field.blank`
+ If ``True``, the field is allowed to be blank. Default is ``False``.
- Note that this is different than :attr:`~Field.null`.
- :attr:`~Field.null` is purely database-related, whereas
- :attr:`~Field.blank` is validation-related. If a field has
- :attr:`blank=True <Field.blank>`, validation on Django's admin site will
- allow entry of an empty value. If a field has :attr:`blank=False
- <Field.blank>`, the field will be required.
+ Note that this is different than :attr:`~Field.null`.
+ :attr:`~Field.null` is purely database-related, whereas
+ :attr:`~Field.blank` is validation-related. If a field has
+ :attr:`blank=True <Field.blank>`, validation on Django's admin site will
+ allow entry of an empty value. If a field has :attr:`blank=False
+ <Field.blank>`, the field will be required.
- :attr:`~Field.choices`
- An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
- this field. If this is given, Django's admin will use a select box
- instead of the standard text field and will limit choices to the choices
- given.
+:attr:`~Field.choices`
+ An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
+ this field. If this is given, Django's admin will use a select box
+ instead of the standard text field and will limit choices to the choices
+ given.
- A choices list looks like this::
+ A choices list looks like this::
- YEAR_IN_SCHOOL_CHOICES = (
- (u'FR', u'Freshman'),
- (u'SO', u'Sophomore'),
- (u'JR', u'Junior'),
- (u'SR', u'Senior'),
- (u'GR', u'Graduate'),
- )
+ YEAR_IN_SCHOOL_CHOICES = (
+ (u'FR', u'Freshman'),
+ (u'SO', u'Sophomore'),
+ (u'JR', u'Junior'),
+ (u'SR', u'Senior'),
+ (u'GR', u'Graduate'),
+ )
- The first element in each tuple is the value that will be stored in the
- database, the second element will be displayed by the admin interface,
- or in a ModelChoiceField. Given an instance of a model object, the
- display value for a choices field can be accessed using the
- ``get_FOO_display`` method. For example::
+ The first element in each tuple is the value that will be stored in the
+ database, the second element will be displayed by the admin interface,
+ or in a ModelChoiceField. Given an instance of a model object, the
+ display value for a choices field can be accessed using the
+ ``get_FOO_display`` method. For example::
- from django.db import models
+ from django.db import models
- class Person(models.Model):
- GENDER_CHOICES = (
- (u'M', u'Male'),
- (u'F', u'Female'),
- )
- name = models.CharField(max_length=60)
- gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
+ class Person(models.Model):
+ GENDER_CHOICES = (
+ (u'M', u'Male'),
+ (u'F', u'Female'),
+ )
+ name = models.CharField(max_length=60)
+ gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
- ::
+ ::
- >>> p = Person(name="Fred Flintstone", gender="M")
- >>> p.save()
- >>> p.gender
- u'M'
- >>> p.get_gender_display()
- u'Male'
+ >>> p = Person(name="Fred Flintstone", gender="M")
+ >>> p.save()
+ >>> p.gender
+ u'M'
+ >>> p.get_gender_display()
+ u'Male'
- :attr:`~Field.default`
- The default value for the field. This can be a value or a callable
- object. If callable it will be called every time a new object is
- created.
+:attr:`~Field.default`
+ The default value for the field. This can be a value or a callable
+ object. If callable it will be called every time a new object is
+ created.
- :attr:`~Field.help_text`
- Extra "help" text to be displayed under the field on the object's admin
- form. It's useful for documentation even if your object doesn't have an
- admin form.
+:attr:`~Field.help_text`
+ Extra "help" text to be displayed under the field on the object's admin
+ form. It's useful for documentation even if your object doesn't have an
+ admin form.
- :attr:`~Field.primary_key`
- If ``True``, this field is the primary key for the model.
+:attr:`~Field.primary_key`
+ If ``True``, this field is the primary key for the model.
- If you don't specify :attr:`primary_key=True <Field.primary_key>` for
- any fields in your model, Django will automatically add an
- :class:`IntegerField` to hold the primary key, so you don't need to set
- :attr:`primary_key=True <Field.primary_key>` on any of your fields
- unless you want to override the default primary-key behavior. For more,
- see :ref:`automatic-primary-key-fields`.
+ If you don't specify :attr:`primary_key=True <Field.primary_key>` for
+ any fields in your model, Django will automatically add an
+ :class:`IntegerField` to hold the primary key, so you don't need to set
+ :attr:`primary_key=True <Field.primary_key>` on any of your fields
+ unless you want to override the default primary-key behavior. For more,
+ see :ref:`automatic-primary-key-fields`.
- :attr:`~Field.unique`
- If ``True``, this field must be unique throughout the table.
+:attr:`~Field.unique`
+ If ``True``, this field must be unique throughout the table.
Again, these are just short descriptions of the most common field options. Full
details can be found in the :ref:`common model field option reference
@@ -435,24 +435,24 @@ explicit declaration defines how the two models are related.
There are a few restrictions on the intermediate model:
- * Your intermediate model must contain one - and *only* one - foreign key
- to the target model (this would be ``Person`` in our example). If you
- have more than one foreign key, a validation error will be raised.
+* Your intermediate model must contain one - and *only* one - foreign key
+ to the target model (this would be ``Person`` in our example). If you
+ have more than one foreign key, a validation error will be raised.
- * Your intermediate model must contain one - and *only* one - foreign key
- to the source model (this would be ``Group`` in our example). If you
- have more than one foreign key, a validation error will be raised.
+* Your intermediate model must contain one - and *only* one - foreign key
+ to the source model (this would be ``Group`` in our example). If you
+ have more than one foreign key, a validation error will be raised.
- * The only exception to this is a model which has a many-to-many
- relationship to itself, through an intermediary model. In this
- case, two foreign keys to the same model are permitted, but they
- will be treated as the two (different) sides of the many-to-many
- relation.
+* The only exception to this is a model which has a many-to-many
+ relationship to itself, through an intermediary model. In this
+ case, two foreign keys to the same model are permitted, but they
+ will be treated as the two (different) sides of the many-to-many
+ relation.
- * When defining a many-to-many relationship from a model to
- itself, using an intermediary model, you *must* use
- :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
- :ref:`the model field reference <manytomany-arguments>`).
+* When defining a many-to-many relationship from a model to
+ itself, using an intermediary model, you *must* use
+ :attr:`symmetrical=False <ManyToManyField.symmetrical>` (see
+ :ref:`the model field reference <manytomany-arguments>`).
Now that you have set up your :class:`~django.db.models.ManyToManyField` to use
your intermediary model (``Membership``, in this case), you're ready to start
@@ -601,17 +601,17 @@ Field name restrictions
Django places only two restrictions on model field names:
- 1. A field name cannot be a Python reserved word, because that would result
- in a Python syntax error. For example::
+1. A field name cannot be a Python reserved word, because that would result
+ in a Python syntax error. For example::
- class Example(models.Model):
- pass = models.IntegerField() # 'pass' is a reserved word!
+ class Example(models.Model):
+ pass = models.IntegerField() # 'pass' is a reserved word!
- 2. A field name cannot contain more than one underscore in a row, due to
- the way Django's query lookup syntax works. For example::
+2. A field name cannot contain more than one underscore in a row, due to
+ the way Django's query lookup syntax works. For example::
- class Example(models.Model):
- foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
+ class Example(models.Model):
+ foo__bar = models.IntegerField() # 'foo__bar' has two underscores!
These limitations can be worked around, though, because your field name doesn't
necessarily have to match your database column name. See the
@@ -702,23 +702,23 @@ of :ref:`methods automatically given to each model <model-instance-methods>`.
You can override most of these -- see `overriding predefined model methods`_,
below -- but there are a couple that you'll almost always want to define:
- :meth:`~Model.__unicode__`
- A Python "magic method" that returns a unicode "representation" of any
- object. This is what Python and Django will use whenever a model
- instance needs to be coerced and displayed as a plain string. Most
- notably, this happens when you display an object in an interactive
- console or in the admin.
+:meth:`~Model.__unicode__`
+ A Python "magic method" that returns a unicode "representation" of any
+ object. This is what Python and Django will use whenever a model
+ instance needs to be coerced and displayed as a plain string. Most
+ notably, this happens when you display an object in an interactive
+ console or in the admin.
- You'll always want to define this method; the default isn't very helpful
- at all.
+ You'll always want to define this method; the default isn't very helpful
+ at all.
- :meth:`~Model.get_absolute_url`
- This tells Django how to calculate the URL for an object. Django uses
- this in its admin interface, and any time it needs to figure out a URL
- for an object.
+:meth:`~Model.get_absolute_url`
+ This tells Django how to calculate the URL for an object. Django uses
+ this in its admin interface, and any time it needs to figure out a URL
+ for an object.
- Any object that has a URL that uniquely identifies it should define this
- method.
+ Any object that has a URL that uniquely identifies it should define this
+ method.
.. _overriding-model-methods:
@@ -800,16 +800,16 @@ models.
There are three styles of inheritance that are possible in Django.
- 1. Often, you will just want to use the parent class to hold information that
- you don't want to have to type out for each child model. This class isn't
- going to ever be used in isolation, so :ref:`abstract-base-classes` are
- what you're after.
- 2. If you're subclassing an existing model (perhaps something from another
- application entirely) and want each model to have its own database table,
- :ref:`multi-table-inheritance` is the way to go.
- 3. Finally, if you only want to modify the Python-level behavior of a model,
- without changing the models fields in any way, you can use
- :ref:`proxy-models`.
+1. Often, you will just want to use the parent class to hold information that
+ you don't want to have to type out for each child model. This class isn't
+ going to ever be used in isolation, so :ref:`abstract-base-classes` are
+ what you're after.
+2. If you're subclassing an existing model (perhaps something from another
+ application entirely) and want each model to have its own database table,
+ :ref:`multi-table-inheritance` is the way to go.
+3. Finally, if you only want to modify the Python-level behavior of a model,
+ without changing the models fields in any way, you can use
+ :ref:`proxy-models`.
.. _abstract-base-classes:
@@ -1197,14 +1197,14 @@ were needed in any case, so the current separation arose.
So, the general rules are:
- 1. If you are mirroring an existing model or database table and don't want
- all the original database table columns, use ``Meta.managed=False``.
- That option is normally useful for modeling database views and tables
- not under the control of Django.
- 2. If you are wanting to change the Python-only behavior of a model, but
- keep all the same fields as in the original, use ``Meta.proxy=True``.
- This sets things up so that the proxy model is an exact copy of the
- storage structure of the original model when data is saved.
+1. If you are mirroring an existing model or database table and don't want
+ all the original database table columns, use ``Meta.managed=False``.
+ That option is normally useful for modeling database views and tables
+ not under the control of Django.
+2. If you are wanting to change the Python-only behavior of a model, but
+ keep all the same fields as in the original, use ``Meta.proxy=True``.
+ This sets things up so that the proxy model is an exact copy of the
+ storage structure of the original model when data is saved.
Multiple inheritance
--------------------
diff --git a/docs/topics/db/optimization.txt b/docs/topics/db/optimization.txt
index dda7e9504a..baea968fdb 100644
--- a/docs/topics/db/optimization.txt
+++ b/docs/topics/db/optimization.txt
@@ -224,21 +224,21 @@ many-to-many relation to User, the following template code is optimal:
It is optimal because:
- 1. Since QuerySets are lazy, this does no database queries if 'display_inbox'
- is False.
+1. Since QuerySets are lazy, this does no database queries if 'display_inbox'
+ is False.
- #. Use of :ttag:`with` means that we store ``user.emails.all`` in a variable
- for later use, allowing its cache to be re-used.
+#. Use of :ttag:`with` means that we store ``user.emails.all`` in a variable
+ for later use, allowing its cache to be re-used.
- #. The line ``{% if emails %}`` causes ``QuerySet.__nonzero__()`` to be called,
- which causes the ``user.emails.all()`` query to be run on the database, and
- at the least the first line to be turned into an ORM object. If there aren't
- any results, it will return False, otherwise True.
+#. The line ``{% if emails %}`` causes ``QuerySet.__nonzero__()`` to be called,
+ which causes the ``user.emails.all()`` query to be run on the database, and
+ at the least the first line to be turned into an ORM object. If there aren't
+ any results, it will return False, otherwise True.
- #. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling
- out the rest of the cache without doing another query.
+#. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling
+ out the rest of the cache without doing another query.
- #. The :ttag:`for` loop iterates over the already filled cache.
+#. The :ttag:`for` loop iterates over the already filled cache.
In total, this code does either one or zero database queries. The only
deliberate optimization performed is the use of the :ttag:`with` tag. Using
diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
index e499b71502..ee50821ac5 100644
--- a/docs/topics/db/queries.txt
+++ b/docs/topics/db/queries.txt
@@ -184,13 +184,13 @@ complete set of objects.
To create such a subset, you refine the initial ``QuerySet``, adding filter
conditions. The two most common ways to refine a ``QuerySet`` are:
- ``filter(**kwargs)``
- Returns a new ``QuerySet`` containing objects that match the given
- lookup parameters.
+``filter(**kwargs)``
+ Returns a new ``QuerySet`` containing objects that match the given
+ lookup parameters.
- ``exclude(**kwargs)``
- Returns a new ``QuerySet`` containing objects that do *not* match the
- given lookup parameters.
+``exclude(**kwargs)``
+ Returns a new ``QuerySet`` containing objects that do *not* match the
+ given lookup parameters.
The lookup parameters (``**kwargs`` in the above function definitions) should
be in the format described in `Field lookups`_ below.
@@ -391,56 +391,56 @@ The database API supports about two dozen lookup types; a complete reference
can be found in the :ref:`field lookup reference <field-lookups>`. To give you a taste of what's available, here's some of the more common lookups
you'll probably use:
- :lookup:`exact`
- An "exact" match. For example::
+:lookup:`exact`
+ An "exact" match. For example::
- >>> Entry.objects.get(headline__exact="Man bites dog")
+ >>> Entry.objects.get(headline__exact="Man bites dog")
- Would generate SQL along these lines:
+ Would generate SQL along these lines:
- .. code-block:: sql
+ .. code-block:: sql
- SELECT ... WHERE headline = 'Man bites dog';
+ SELECT ... WHERE headline = 'Man bites dog';
- If you don't provide a lookup type -- that is, if your keyword argument
- doesn't contain a double underscore -- the lookup type is assumed to be
- ``exact``.
+ If you don't provide a lookup type -- that is, if your keyword argument
+ doesn't contain a double underscore -- the lookup type is assumed to be
+ ``exact``.
- For example, the following two statements are equivalent::
+ For example, the following two statements are equivalent::
- >>> Blog.objects.get(id__exact=14) # Explicit form
- >>> Blog.objects.get(id=14) # __exact is implied
+ >>> Blog.objects.get(id__exact=14) # Explicit form
+ >>> Blog.objects.get(id=14) # __exact is implied
- This is for convenience, because ``exact`` lookups are the common case.
+ This is for convenience, because ``exact`` lookups are the common case.
- :lookup:`iexact`
- A case-insensitive match. So, the query::
+:lookup:`iexact`
+ A case-insensitive match. So, the query::
- >>> Blog.objects.get(name__iexact="beatles blog")
+ >>> Blog.objects.get(name__iexact="beatles blog")
- Would match a ``Blog`` titled "Beatles Blog", "beatles blog", or even
- "BeAtlES blOG".
+ Would match a ``Blog`` titled "Beatles Blog", "beatles blog", or even
+ "BeAtlES blOG".
- :lookup:`contains`
- Case-sensitive containment test. For example::
+:lookup:`contains`
+ Case-sensitive containment test. For example::
- Entry.objects.get(headline__contains='Lennon')
+ Entry.objects.get(headline__contains='Lennon')
- Roughly translates to this SQL:
+ Roughly translates to this SQL:
- .. code-block:: sql
+ .. code-block:: sql
- SELECT ... WHERE headline LIKE '%Lennon%';
+ SELECT ... WHERE headline LIKE '%Lennon%';
- Note this will match the headline ``'Today Lennon honored'`` but not
- ``'today lennon honored'``.
+ Note this will match the headline ``'Today Lennon honored'`` but not
+ ``'today lennon honored'``.
- There's also a case-insensitive version, :lookup:`icontains`.
+ There's also a case-insensitive version, :lookup:`icontains`.
- :lookup:`startswith`, :lookup:`endswith`
- Starts-with and ends-with search, respectively. There are also
- case-insensitive versions called :lookup:`istartswith` and
- :lookup:`iendswith`.
+:lookup:`startswith`, :lookup:`endswith`
+ Starts-with and ends-with search, respectively. There are also
+ case-insensitive versions called :lookup:`istartswith` and
+ :lookup:`iendswith`.
Again, this only scratches the surface. A complete reference can be found in the
:ref:`field lookup reference <field-lookups>`.
diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt
index c316bbf143..b2ee26d6b0 100644
--- a/docs/topics/db/transactions.txt
+++ b/docs/topics/db/transactions.txt
@@ -69,29 +69,29 @@ per-function or per-code-block basis.
These functions, described in detail below, can be used in two different ways:
- * As a decorator_ on a particular function. For example::
+* As a decorator_ on a particular function. For example::
- from django.db import transaction
+ from django.db import transaction
- @transaction.commit_on_success
- def viewfunc(request):
- # ...
- # this code executes inside a transaction
- # ...
+ @transaction.commit_on_success
+ def viewfunc(request):
+ # ...
+ # this code executes inside a transaction
+ # ...
- * As a `context manager`_ around a particular block of code::
+* As a `context manager`_ around a particular block of code::
- from django.db import transaction
+ from django.db import transaction
- def viewfunc(request):
- # ...
- # this code executes using default transaction management
- # ...
+ def viewfunc(request):
+ # ...
+ # this code executes using default transaction management
+ # ...
- with transaction.commit_on_success():
- # ...
- # this code executes inside a transaction
- # ...
+ with transaction.commit_on_success():
+ # ...
+ # this code executes inside a transaction
+ # ...
Both techniques work with all supported version of Python. However, in Python
2.5, you must add ``from __future__ import with_statement`` at the beginning
diff --git a/docs/topics/email.txt b/docs/topics/email.txt
index 6771b83d01..6bc30874ae 100644
--- a/docs/topics/email.txt
+++ b/docs/topics/email.txt
@@ -45,26 +45,26 @@ The simplest way to send email is using
The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters
are required.
- * ``subject``: A string.
- * ``message``: A string.
- * ``from_email``: A string.
- * ``recipient_list``: A list of strings, each an email address. Each
- member of ``recipient_list`` will see the other recipients in the "To:"
- field of the email message.
- * ``fail_silently``: A boolean. If it's ``False``, ``send_mail`` will raise
- an :exc:`smtplib.SMTPException`. See the :mod:`smtplib` docs for a list of
- possible exceptions, all of which are subclasses of
- :exc:`~smtplib.SMTPException`.
- * ``auth_user``: The optional username to use to authenticate to the SMTP
- server. If this isn't provided, Django will use the value of the
- :setting:`EMAIL_HOST_USER` setting.
- * ``auth_password``: The optional password to use to authenticate to the
- SMTP server. If this isn't provided, Django will use the value of the
- :setting:`EMAIL_HOST_PASSWORD` setting.
- * ``connection``: The optional email backend to use to send the mail.
- If unspecified, an instance of the default backend will be used.
- See the documentation on :ref:`Email backends <topic-email-backends>`
- for more details.
+* ``subject``: A string.
+* ``message``: A string.
+* ``from_email``: A string.
+* ``recipient_list``: A list of strings, each an email address. Each
+ member of ``recipient_list`` will see the other recipients in the "To:"
+ field of the email message.
+* ``fail_silently``: A boolean. If it's ``False``, ``send_mail`` will raise
+ an :exc:`smtplib.SMTPException`. See the :mod:`smtplib` docs for a list of
+ possible exceptions, all of which are subclasses of
+ :exc:`~smtplib.SMTPException`.
+* ``auth_user``: The optional username to use to authenticate to the SMTP
+ server. If this isn't provided, Django will use the value of the
+ :setting:`EMAIL_HOST_USER` setting.
+* ``auth_password``: The optional password to use to authenticate to the
+ SMTP server. If this isn't provided, Django will use the value of the
+ :setting:`EMAIL_HOST_PASSWORD` setting.
+* ``connection``: The optional email backend to use to send the mail.
+ If unspecified, an instance of the default backend will be used.
+ See the documentation on :ref:`Email backends <topic-email-backends>`
+ for more details.
send_mass_mail()
================
@@ -239,34 +239,34 @@ All parameters are optional and can be set at any time prior to calling the
.. versionchanged:: 1.3
The ``cc`` argument was added.
- * ``subject``: The subject line of the email.
+* ``subject``: The subject line of the email.
- * ``body``: The body text. This should be a plain text message.
+* ``body``: The body text. This should be a plain text message.
- * ``from_email``: The sender's address. Both ``fred@example.com`` and
- ``Fred <fred@example.com>`` forms are legal. If omitted, the
- :setting:`DEFAULT_FROM_EMAIL` setting is used.
+* ``from_email``: The sender's address. Both ``fred@example.com`` and
+ ``Fred <fred@example.com>`` forms are legal. If omitted, the
+ :setting:`DEFAULT_FROM_EMAIL` setting is used.
- * ``to``: A list or tuple of recipient addresses.
+* ``to``: A list or tuple of recipient addresses.
- * ``bcc``: A list or tuple of addresses used in the "Bcc" header when
- sending the email.
+* ``bcc``: A list or tuple of addresses used in the "Bcc" header when
+ sending the email.
- * ``connection``: An email backend instance. Use this parameter if
- you want to use the same connection for multiple messages. If omitted, a
- new connection is created when ``send()`` is called.
+* ``connection``: An email backend instance. Use this parameter if
+ you want to use the same connection for multiple messages. If omitted, a
+ new connection is created when ``send()`` is called.
- * ``attachments``: A list of attachments to put on the message. These can
- be either ``email.MIMEBase.MIMEBase`` instances, or ``(filename,
- content, mimetype)`` triples.
+* ``attachments``: A list of attachments to put on the message. These can
+ be either ``email.MIMEBase.MIMEBase`` instances, or ``(filename,
+ content, mimetype)`` triples.
- * ``headers``: A dictionary of extra headers to put on the message. The
- keys are the header name, values are the header values. It's up to the
- caller to ensure header names and values are in the correct format for
- an email message.
+* ``headers``: A dictionary of extra headers to put on the message. The
+ keys are the header name, values are the header values. It's up to the
+ caller to ensure header names and values are in the correct format for
+ an email message.
- * ``cc``: A list or tuple of recipient addresses used in the "Cc" header
- when sending the email.
+* ``cc``: A list or tuple of recipient addresses used in the "Cc" header
+ when sending the email.
For example::
@@ -276,51 +276,51 @@ For example::
The class has the following methods:
- * ``send(fail_silently=False)`` sends the message. If a connection was
- specified when the email was constructed, that connection will be used.
- Otherwise, an instance of the default backend will be instantiated and
- used. If the keyword argument ``fail_silently`` is ``True``, exceptions
- raised while sending the message will be quashed.
+* ``send(fail_silently=False)`` sends the message. If a connection was
+ specified when the email was constructed, that connection will be used.
+ Otherwise, an instance of the default backend will be instantiated and
+ used. If the keyword argument ``fail_silently`` is ``True``, exceptions
+ raised while sending the message will be quashed.
- * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
- subclass of Python's ``email.MIMEText.MIMEText`` class) or a
- ``django.core.mail.SafeMIMEMultipart`` object holding the message to be
- sent. If you ever need to extend the
- :class:`~django.core.mail.EmailMessage` class, you'll probably want to
- override this method to put the content you want into the MIME object.
+* ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a
+ subclass of Python's ``email.MIMEText.MIMEText`` class) or a
+ ``django.core.mail.SafeMIMEMultipart`` object holding the message to be
+ sent. If you ever need to extend the
+ :class:`~django.core.mail.EmailMessage` class, you'll probably want to
+ override this method to put the content you want into the MIME object.
- * ``recipients()`` returns a list of all the recipients of the message,
- whether they're recorded in the ``to`` or ``bcc`` attributes. This is
- another method you might need to override when subclassing, because the
- SMTP server needs to be told the full list of recipients when the message
- is sent. If you add another way to specify recipients in your class, they
- need to be returned from this method as well.
+* ``recipients()`` returns a list of all the recipients of the message,
+ whether they're recorded in the ``to`` or ``bcc`` attributes. This is
+ another method you might need to override when subclassing, because the
+ SMTP server needs to be told the full list of recipients when the message
+ is sent. If you add another way to specify recipients in your class, they
+ need to be returned from this method as well.
- * ``attach()`` creates a new file attachment and adds it to the message.
- There are two ways to call ``attach()``:
+* ``attach()`` creates a new file attachment and adds it to the message.
+ There are two ways to call ``attach()``:
- * You can pass it a single argument that is an
- ``email.MIMEBase.MIMEBase`` instance. This will be inserted directly
- into the resulting message.
+ * You can pass it a single argument that is an
+ ``email.MIMEBase.MIMEBase`` instance. This will be inserted directly
+ into the resulting message.
- * Alternatively, you can pass ``attach()`` three arguments:
- ``filename``, ``content`` and ``mimetype``. ``filename`` is the name
- of the file attachment as it will appear in the email, ``content`` is
- the data that will be contained inside the attachment and
- ``mimetype`` is the optional MIME type for the attachment. If you
- omit ``mimetype``, the MIME content type will be guessed from the
- filename of the attachment.
+ * Alternatively, you can pass ``attach()`` three arguments:
+ ``filename``, ``content`` and ``mimetype``. ``filename`` is the name
+ of the file attachment as it will appear in the email, ``content`` is
+ the data that will be contained inside the attachment and
+ ``mimetype`` is the optional MIME type for the attachment. If you
+ omit ``mimetype``, the MIME content type will be guessed from the
+ filename of the attachment.
- For example::
+ For example::
- message.attach('design.png', img_data, 'image/png')
+ message.attach('design.png', img_data, 'image/png')
- * ``attach_file()`` creates a new attachment using a file from your
- filesystem. Call it with the path of the file to attach and, optionally,
- the MIME type to use for the attachment. If the MIME type is omitted, it
- will be guessed from the filename. The simplest use would be::
+* ``attach_file()`` creates a new attachment using a file from your
+ filesystem. Call it with the path of the file to attach and, optionally,
+ the MIME type to use for the attachment. If the MIME type is omitted, it
+ will be guessed from the filename. The simplest use would be::
- message.attach_file('/images/weather_map.png')
+ message.attach_file('/images/weather_map.png')
.. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
@@ -371,15 +371,15 @@ The actual sending of an email is handled by the email backend.
The email backend class has the following methods:
- * ``open()`` instantiates an long-lived email-sending connection.
+* ``open()`` instantiates an long-lived email-sending connection.
- * ``close()`` closes the current email-sending connection.
+* ``close()`` closes the current email-sending connection.
- * ``send_messages(email_messages)`` sends a list of
- :class:`~django.core.mail.EmailMessage` objects. If the connection is
- not open, this call will implicitly open the connection, and close the
- connection afterwards. If the connection is already open, it will be
- left open after mail has been sent.
+* ``send_messages(email_messages)`` sends a list of
+ :class:`~django.core.mail.EmailMessage` objects. If the connection is
+ not open, this call will implicitly open the connection, and close the
+ connection afterwards. If the connection is already open, it will be
+ left open after mail has been sent.
Obtaining an instance of an email backend
-----------------------------------------
diff --git a/docs/topics/forms/index.txt b/docs/topics/forms/index.txt
index 5b6f87fbec..c5d33f0e54 100644
--- a/docs/topics/forms/index.txt
+++ b/docs/topics/forms/index.txt
@@ -17,10 +17,10 @@ While it is possible to process form submissions just using Django's
:class:`~django.http.HttpRequest` class, using the form library takes care of a
number of common form-related tasks. Using it, you can:
- 1. Display an HTML form with automatically generated form widgets.
- 2. Check submitted data against a set of validation rules.
- 3. Redisplay a form in the case of validation errors.
- 4. Convert submitted form data to the relevant Python data types.
+1. Display an HTML form with automatically generated form widgets.
+2. Check submitted data against a set of validation rules.
+3. Redisplay a form in the case of validation errors.
+4. Convert submitted form data to the relevant Python data types.
Overview
========
@@ -106,13 +106,13 @@ The standard pattern for processing a form in a view looks like this:
There are three code paths here:
- 1. If the form has not been submitted, an unbound instance of ContactForm is
- created and passed to the template.
- 2. If the form has been submitted, a bound instance of the form is created
- using ``request.POST``. If the submitted data is valid, it is processed
- and the user is re-directed to a "thanks" page.
- 3. If the form has been submitted but is invalid, the bound form instance is
- passed on to the template.
+1. If the form has not been submitted, an unbound instance of ContactForm is
+ created and passed to the template.
+2. If the form has been submitted, a bound instance of the form is created
+ using ``request.POST``. If the submitted data is valid, it is processed
+ and the user is re-directed to a "thanks" page.
+3. If the form has been submitted but is invalid, the bound form instance is
+ passed on to the template.
The distinction between **bound** and **unbound** forms is important. An unbound
form does not have any data associated with it; when rendered to the user, it
@@ -287,35 +287,35 @@ Within this loop, ``{{ field }}`` is an instance of :class:`BoundField`.
``BoundField`` also has the following attributes, which can be useful in your
templates:
- ``{{ field.label }}``
- The label of the field, e.g. ``Email address``.
+``{{ field.label }}``
+ The label of the field, e.g. ``Email address``.
- ``{{ field.label_tag }}``
- The field's label wrapped in the appropriate HTML ``<label>`` tag,
- e.g. ``<label for="id_email">Email address</label>``
+``{{ field.label_tag }}``
+ The field's label wrapped in the appropriate HTML ``<label>`` tag,
+ e.g. ``<label for="id_email">Email address</label>``
- ``{{ field.html_name }}``
- The name of the field that will be used in the input element's name
- field. This takes the form prefix into account, if it has been set.
+``{{ field.html_name }}``
+ The name of the field that will be used in the input element's name
+ field. This takes the form prefix into account, if it has been set.
- ``{{ field.help_text }}``
- Any help text that has been associated with the field.
+``{{ field.help_text }}``
+ Any help text that has been associated with the field.
- ``{{ field.errors }}``
- Outputs a ``<ul class="errorlist">`` containing any validation errors
- corresponding to this field. You can customize the presentation of
- the errors with a ``{% for error in field.errors %}`` loop. In this
- case, each object in the loop is a simple string containing the error
- message.
+``{{ field.errors }}``
+ Outputs a ``<ul class="errorlist">`` containing any validation errors
+ corresponding to this field. You can customize the presentation of
+ the errors with a ``{% for error in field.errors %}`` loop. In this
+ case, each object in the loop is a simple string containing the error
+ message.
- ``field.is_hidden``
- This attribute is ``True`` if the form field is a hidden field and
- ``False`` otherwise. It's not particularly useful as a template
- variable, but could be useful in conditional tests such as::
+``field.is_hidden``
+ This attribute is ``True`` if the form field is a hidden field and
+ ``False`` otherwise. It's not particularly useful as a template
+ variable, but could be useful in conditional tests such as::
- {% if field.is_hidden %}
- {# Do something special #}
- {% endif %}
+ {% if field.is_hidden %}
+ {# Do something special #}
+ {% endif %}
Looping over hidden and visible fields
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
index 07a2819fa3..832a3acff0 100644
--- a/docs/topics/forms/modelforms.txt
+++ b/docs/topics/forms/modelforms.txt
@@ -45,70 +45,70 @@ model field has a corresponding default form field. For example, a
model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is
the full list of conversions:
- =============================== ========================================
- Model field Form field
- =============================== ========================================
- ``AutoField`` Not represented in the form
+=============================== ========================================
+Model field Form field
+=============================== ========================================
+``AutoField`` Not represented in the form
- ``BigIntegerField`` ``IntegerField`` with ``min_value`` set
- to -9223372036854775808 and ``max_value``
- set to 9223372036854775807.
+``BigIntegerField`` ``IntegerField`` with ``min_value`` set
+ to -9223372036854775808 and ``max_value``
+ set to 9223372036854775807.
- ``BooleanField`` ``BooleanField``
+``BooleanField`` ``BooleanField``
- ``CharField`` ``CharField`` with ``max_length`` set to
- the model field's ``max_length``
+``CharField`` ``CharField`` with ``max_length`` set to
+ the model field's ``max_length``
- ``CommaSeparatedIntegerField`` ``CharField``
+``CommaSeparatedIntegerField`` ``CharField``
- ``DateField`` ``DateField``
+``DateField`` ``DateField``
- ``DateTimeField`` ``DateTimeField``
+``DateTimeField`` ``DateTimeField``
- ``DecimalField`` ``DecimalField``
+``DecimalField`` ``DecimalField``
- ``EmailField`` ``EmailField``
+``EmailField`` ``EmailField``
- ``FileField`` ``FileField``
+``FileField`` ``FileField``
- ``FilePathField`` ``CharField``
+``FilePathField`` ``CharField``
- ``FloatField`` ``FloatField``
+``FloatField`` ``FloatField``
- ``ForeignKey`` ``ModelChoiceField`` (see below)
+``ForeignKey`` ``ModelChoiceField`` (see below)
- ``ImageField`` ``ImageField``
+``ImageField`` ``ImageField``
- ``IntegerField`` ``IntegerField``
+``IntegerField`` ``IntegerField``
- ``IPAddressField`` ``IPAddressField``
+``IPAddressField`` ``IPAddressField``
- ``GenericIPAddressField`` ``GenericIPAddressField``
+``GenericIPAddressField`` ``GenericIPAddressField``
- ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
- below)
+``ManyToManyField`` ``ModelMultipleChoiceField`` (see
+ below)
- ``NullBooleanField`` ``CharField``
+``NullBooleanField`` ``CharField``
- ``PhoneNumberField`` ``USPhoneNumberField``
- (from ``django.contrib.localflavor.us``)
+``PhoneNumberField`` ``USPhoneNumberField``
+ (from ``django.contrib.localflavor.us``)
- ``PositiveIntegerField`` ``IntegerField``
+``PositiveIntegerField`` ``IntegerField``
- ``PositiveSmallIntegerField`` ``IntegerField``
+``PositiveSmallIntegerField`` ``IntegerField``
- ``SlugField`` ``SlugField``
+``SlugField`` ``SlugField``
- ``SmallIntegerField`` ``IntegerField``
+``SmallIntegerField`` ``IntegerField``
- ``TextField`` ``CharField`` with
- ``widget=forms.Textarea``
+``TextField`` ``CharField`` with
+ ``widget=forms.Textarea``
- ``TimeField`` ``TimeField``
+``TimeField`` ``TimeField``
- ``URLField`` ``URLField`` with ``verify_exists`` set
- to the model field's ``verify_exists``
- =============================== ========================================
+``URLField`` ``URLField`` with ``verify_exists`` set
+ to the model field's ``verify_exists``
+=============================== ========================================
.. versionadded:: 1.2
The ``BigIntegerField`` is new in Django 1.2.
@@ -117,31 +117,31 @@ the full list of conversions:
As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
types are special cases:
- * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
- which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
+* ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
+ which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
- * ``ManyToManyField`` is represented by
- ``django.forms.ModelMultipleChoiceField``, which is a
- ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
+* ``ManyToManyField`` is represented by
+ ``django.forms.ModelMultipleChoiceField``, which is a
+ ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
In addition, each generated form field has attributes set as follows:
- * If the model field has ``blank=True``, then ``required`` is set to
- ``False`` on the form field. Otherwise, ``required=True``.
+* If the model field has ``blank=True``, then ``required`` is set to
+ ``False`` on the form field. Otherwise, ``required=True``.
- * The form field's ``label`` is set to the ``verbose_name`` of the model
- field, with the first character capitalized.
+* The form field's ``label`` is set to the ``verbose_name`` of the model
+ field, with the first character capitalized.
- * The form field's ``help_text`` is set to the ``help_text`` of the model
- field.
+* The form field's ``help_text`` is set to the ``help_text`` of the model
+ field.
- * If the model field has ``choices`` set, then the form field's ``widget``
- will be set to ``Select``, with choices coming from the model field's
- ``choices``. The choices will normally include the blank choice which is
- selected by default. If the field is required, this forces the user to
- make a selection. The blank choice will not be included if the model
- field has ``blank=False`` and an explicit ``default`` value (the
- ``default`` value will be initially selected instead).
+* If the model field has ``choices`` set, then the form field's ``widget``
+ will be set to ``Select``, with choices coming from the model field's
+ ``choices``. The choices will normally include the blank choice which is
+ selected by default. If the field is required, this forces the user to
+ make a selection. The blank choice will not be included if the model
+ field has ``blank=False`` and an explicit ``default`` value (the
+ ``default`` value will be initially selected instead).
Finally, note that you can override the form field used for a given model
field. See `Overriding the default field types or widgets`_ below.
@@ -518,13 +518,13 @@ the original ``ArticleForm.Meta`` to remove one field.
There are a couple of things to note, however.
- * Normal Python name resolution rules apply. If you have multiple base
- classes that declare a ``Meta`` inner class, only the first one will be
- used. This means the child's ``Meta``, if it exists, otherwise the
- ``Meta`` of the first parent, etc.
+* Normal Python name resolution rules apply. If you have multiple base
+ classes that declare a ``Meta`` inner class, only the first one will be
+ used. This means the child's ``Meta``, if it exists, otherwise the
+ ``Meta`` of the first parent, etc.
- * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
- and a ``Form`` simultaneously.
+* For technical reasons, a subclass cannot inherit from both a ``ModelForm``
+ and a ``Form`` simultaneously.
Chances are these notes won't affect you unless you're trying to do something
tricky with subclassing.
diff --git a/docs/topics/generic-views-migration.txt b/docs/topics/generic-views-migration.txt
index fa62f5de1f..0647336b8c 100644
--- a/docs/topics/generic-views-migration.txt
+++ b/docs/topics/generic-views-migration.txt
@@ -17,24 +17,24 @@ Replace generic views with generic classes
Existing usage of function-based generic views should be replaced with
their class-based analogs:
- ==================================================== ====================================================
- Old function-based generic view New class-based generic view
- ==================================================== ====================================================
- ``django.views.generic.simple.direct_to_template`` :class:`django.views.generic.base.TemplateView`
- ``django.views.generic.simple.redirect_to`` :class:`django.views.generic.base.RedirectView`
- ``django.views.generic.list_detail.object_list`` :class:`django.views.generic.list.ListView`
- ``django.views.generic.list_detail.object_detail`` :class:`django.views.generic.detail.DetailView`
- ``django.views.generic.create_update.create_object`` :class:`django.views.generic.edit.CreateView`
- ``django.views.generic.create_update.update_object`` :class:`django.views.generic.edit.UpdateView`
- ``django.views.generic.create_update.delete_object`` :class:`django.views.generic.edit.DeleteView`
- ``django.views.generic.date_based.archive_index`` :class:`django.views.generic.dates.ArchiveIndexView`
- ``django.views.generic.date_based.archive_year`` :class:`django.views.generic.dates.YearArchiveView`
- ``django.views.generic.date_based.archive_month`` :class:`django.views.generic.dates.MonthArchiveView`
- ``django.views.generic.date_based.archive_week`` :class:`django.views.generic.dates.WeekArchiveView`
- ``django.views.generic.date_based.archive_day`` :class:`django.views.generic.dates.DayArchiveView`
- ``django.views.generic.date_based.archive_today`` :class:`django.views.generic.dates.TodayArchiveView`
- ``django.views.generic.date_based.object_detail`` :class:`django.views.generic.dates.DateDetailView`
- ==================================================== ====================================================
+==================================================== ====================================================
+Old function-based generic view New class-based generic view
+==================================================== ====================================================
+``django.views.generic.simple.direct_to_template`` :class:`django.views.generic.base.TemplateView`
+``django.views.generic.simple.redirect_to`` :class:`django.views.generic.base.RedirectView`
+``django.views.generic.list_detail.object_list`` :class:`django.views.generic.list.ListView`
+``django.views.generic.list_detail.object_detail`` :class:`django.views.generic.detail.DetailView`
+``django.views.generic.create_update.create_object`` :class:`django.views.generic.edit.CreateView`
+``django.views.generic.create_update.update_object`` :class:`django.views.generic.edit.UpdateView`
+``django.views.generic.create_update.delete_object`` :class:`django.views.generic.edit.DeleteView`
+``django.views.generic.date_based.archive_index`` :class:`django.views.generic.dates.ArchiveIndexView`
+``django.views.generic.date_based.archive_year`` :class:`django.views.generic.dates.YearArchiveView`
+``django.views.generic.date_based.archive_month`` :class:`django.views.generic.dates.MonthArchiveView`
+``django.views.generic.date_based.archive_week`` :class:`django.views.generic.dates.WeekArchiveView`
+``django.views.generic.date_based.archive_day`` :class:`django.views.generic.dates.DayArchiveView`
+``django.views.generic.date_based.archive_today`` :class:`django.views.generic.dates.TodayArchiveView`
+``django.views.generic.date_based.object_detail`` :class:`django.views.generic.dates.DateDetailView`
+==================================================== ====================================================
To do this, replace the reference to the generic view function with
a ``as_view()`` instantiation of the class-based view. For example,
diff --git a/docs/topics/generic-views.txt b/docs/topics/generic-views.txt
index 78c3c0199f..a79fc7c37c 100644
--- a/docs/topics/generic-views.txt
+++ b/docs/topics/generic-views.txt
@@ -28,22 +28,22 @@ be passed as an extra argument to the URLconf.
Django ships with generic views to do the following:
- * Perform common "simple" tasks: redirect to a different page and
- render a given template.
+* Perform common "simple" tasks: redirect to a different page and
+ render a given template.
- * Display list and detail pages for a single object. If we were creating an
- application to manage conferences then a ``talk_list`` view and a
- ``registered_user_list`` view would be examples of list views. A single
- talk page is an example of what we call a "detail" view.
+* Display list and detail pages for a single object. If we were creating an
+ application to manage conferences then a ``talk_list`` view and a
+ ``registered_user_list`` view would be examples of list views. A single
+ talk page is an example of what we call a "detail" view.
- * Present date-based objects in year/month/day archive pages,
- associated detail, and "latest" pages. The Django Weblog's
- (http://www.djangoproject.com/weblog/) year, month, and
- day archives are built with these, as would be a typical
- newspaper's archives.
+* Present date-based objects in year/month/day archive pages,
+ associated detail, and "latest" pages. The Django Weblog's
+ (http://www.djangoproject.com/weblog/) year, month, and
+ day archives are built with these, as would be a typical
+ newspaper's archives.
- * Allow users to create, update, and delete objects -- with or
- without authorization.
+* Allow users to create, update, and delete objects -- with or
+ without authorization.
Taken together, these views provide easy interfaces to perform the most common
tasks developers encounter.
diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt
index e5298ef2cb..1c1ef776bb 100644
--- a/docs/topics/http/file-uploads.txt
+++ b/docs/topics/http/file-uploads.txt
@@ -133,51 +133,51 @@ Changing upload handler behavior
Three settings control Django's file upload behavior:
- :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`
- The maximum size, in bytes, for files that will be uploaded into memory.
- Files larger than :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be
- streamed to disk.
+:setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`
+ The maximum size, in bytes, for files that will be uploaded into memory.
+ Files larger than :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be
+ streamed to disk.
- Defaults to 2.5 megabytes.
+ Defaults to 2.5 megabytes.
- :setting:`FILE_UPLOAD_TEMP_DIR`
- The directory where uploaded files larger than
- :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be stored.
+:setting:`FILE_UPLOAD_TEMP_DIR`
+ The directory where uploaded files larger than
+ :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE` will be stored.
- Defaults to your system's standard temporary directory (i.e. ``/tmp`` on
- most Unix-like systems).
+ Defaults to your system's standard temporary directory (i.e. ``/tmp`` on
+ most Unix-like systems).
- :setting:`FILE_UPLOAD_PERMISSIONS`
- The numeric mode (i.e. ``0644``) to set newly uploaded files to. For
- more information about what these modes mean, see the documentation for
- :func:`os.chmod`.
+:setting:`FILE_UPLOAD_PERMISSIONS`
+ The numeric mode (i.e. ``0644``) to set newly uploaded files to. For
+ more information about what these modes mean, see the documentation for
+ :func:`os.chmod`.
- If this isn't given or is ``None``, you'll get operating-system
- dependent behavior. On most platforms, temporary files will have a mode
- of ``0600``, and files saved from memory will be saved using the
- system's standard umask.
+ If this isn't given or is ``None``, you'll get operating-system
+ dependent behavior. On most platforms, temporary files will have a mode
+ of ``0600``, and files saved from memory will be saved using the
+ system's standard umask.
- .. warning::
+ .. warning::
- If you're not familiar with file modes, please note that the leading
- ``0`` is very important: it indicates an octal number, which is the
- way that modes must be specified. If you try to use ``644``, you'll
- get totally incorrect behavior.
+ If you're not familiar with file modes, please note that the leading
+ ``0`` is very important: it indicates an octal number, which is the
+ way that modes must be specified. If you try to use ``644``, you'll
+ get totally incorrect behavior.
- **Always prefix the mode with a 0.**
+ **Always prefix the mode with a 0.**
- :setting:`FILE_UPLOAD_HANDLERS`
- The actual handlers for uploaded files. Changing this setting allows
- complete customization -- even replacement -- of Django's upload
- process. See `upload handlers`_, below, for details.
+:setting:`FILE_UPLOAD_HANDLERS`
+ The actual handlers for uploaded files. Changing this setting allows
+ complete customization -- even replacement -- of Django's upload
+ process. See `upload handlers`_, below, for details.
- Defaults to::
+ Defaults to::
- ("django.core.files.uploadhandler.MemoryFileUploadHandler",
- "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
+ ("django.core.files.uploadhandler.MemoryFileUploadHandler",
+ "django.core.files.uploadhandler.TemporaryFileUploadHandler",)
- Which means "try to upload to memory first, then fall back to temporary
- files."
+ Which means "try to upload to memory first, then fall back to temporary
+ files."
``UploadedFile`` objects
========================
@@ -312,32 +312,32 @@ Required methods
Custom file upload handlers **must** define the following methods:
- ``FileUploadHandler.receive_data_chunk(self, raw_data, start)``
- Receives a "chunk" of data from the file upload.
+``FileUploadHandler.receive_data_chunk(self, raw_data, start)``
+ Receives a "chunk" of data from the file upload.
- ``raw_data`` is a byte string containing the uploaded data.
+ ``raw_data`` is a byte string containing the uploaded data.
- ``start`` is the position in the file where this ``raw_data`` chunk
- begins.
+ ``start`` is the position in the file where this ``raw_data`` chunk
+ begins.
- The data you return will get fed into the subsequent upload handlers'
- ``receive_data_chunk`` methods. In this way, one handler can be a
- "filter" for other handlers.
+ The data you return will get fed into the subsequent upload handlers'
+ ``receive_data_chunk`` methods. In this way, one handler can be a
+ "filter" for other handlers.
- Return ``None`` from ``receive_data_chunk`` to sort-circuit remaining
- upload handlers from getting this chunk.. This is useful if you're
- storing the uploaded data yourself and don't want future handlers to
- store a copy of the data.
+ Return ``None`` from ``receive_data_chunk`` to sort-circuit remaining
+ upload handlers from getting this chunk.. This is useful if you're
+ storing the uploaded data yourself and don't want future handlers to
+ store a copy of the data.
- If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
- will abort or the file will be completely skipped.
+ If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload
+ will abort or the file will be completely skipped.
- ``FileUploadHandler.file_complete(self, file_size)``
- Called when a file has finished uploading.
+``FileUploadHandler.file_complete(self, file_size)``
+ Called when a file has finished uploading.
- The handler should return an ``UploadedFile`` object that will be stored
- in ``request.FILES``. Handlers may also return ``None`` to indicate that
- the ``UploadedFile`` object should come from subsequent upload handlers.
+ The handler should return an ``UploadedFile`` object that will be stored
+ in ``request.FILES``. Handlers may also return ``None`` to indicate that
+ the ``UploadedFile`` object should come from subsequent upload handlers.
Optional methods
~~~~~~~~~~~~~~~~
@@ -345,56 +345,56 @@ Optional methods
Custom upload handlers may also define any of the following optional methods or
attributes:
- ``FileUploadHandler.chunk_size``
- Size, in bytes, of the "chunks" Django should store into memory and feed
- into the handler. That is, this attribute controls the size of chunks
- fed into ``FileUploadHandler.receive_data_chunk``.
+``FileUploadHandler.chunk_size``
+ Size, in bytes, of the "chunks" Django should store into memory and feed
+ into the handler. That is, this attribute controls the size of chunks
+ fed into ``FileUploadHandler.receive_data_chunk``.
- For maximum performance the chunk sizes should be divisible by ``4`` and
- should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
- multiple chunk sizes provided by multiple handlers, Django will use the
- smallest chunk size defined by any handler.
+ For maximum performance the chunk sizes should be divisible by ``4`` and
+ should not exceed 2 GB (2\ :sup:`31` bytes) in size. When there are
+ multiple chunk sizes provided by multiple handlers, Django will use the
+ smallest chunk size defined by any handler.
- The default is 64*2\ :sup:`10` bytes, or 64 KB.
+ The default is 64*2\ :sup:`10` bytes, or 64 KB.
- ``FileUploadHandler.new_file(self, field_name, file_name, content_type, content_length, charset)``
- Callback signaling that a new file upload is starting. This is called
- before any data has been fed to any upload handlers.
+``FileUploadHandler.new_file(self, field_name, file_name, content_type, content_length, charset)``
+ Callback signaling that a new file upload is starting. This is called
+ before any data has been fed to any upload handlers.
- ``field_name`` is a string name of the file ``<input>`` field.
+ ``field_name`` is a string name of the file ``<input>`` field.
- ``file_name`` is the unicode filename that was provided by the browser.
+ ``file_name`` is the unicode filename that was provided by the browser.
- ``content_type`` is the MIME type provided by the browser -- E.g.
- ``'image/jpeg'``.
+ ``content_type`` is the MIME type provided by the browser -- E.g.
+ ``'image/jpeg'``.
- ``content_length`` is the length of the image given by the browser.
- Sometimes this won't be provided and will be ``None``.
+ ``content_length`` is the length of the image given by the browser.
+ Sometimes this won't be provided and will be ``None``.
- ``charset`` is the character set (i.e. ``utf8``) given by the browser.
- Like ``content_length``, this sometimes won't be provided.
+ ``charset`` is the character set (i.e. ``utf8``) given by the browser.
+ Like ``content_length``, this sometimes won't be provided.
- This method may raise a ``StopFutureHandlers`` exception to prevent
- future handlers from handling this file.
+ This method may raise a ``StopFutureHandlers`` exception to prevent
+ future handlers from handling this file.
- ``FileUploadHandler.upload_complete(self)``
- Callback signaling that the entire upload (all files) has completed.
+``FileUploadHandler.upload_complete(self)``
+ Callback signaling that the entire upload (all files) has completed.
- ``FileUploadHandler.handle_raw_input(self, input_data, META, content_length, boundary, encoding)``
- Allows the handler to completely override the parsing of the raw
- HTTP input.
+``FileUploadHandler.handle_raw_input(self, input_data, META, content_length, boundary, encoding)``
+ Allows the handler to completely override the parsing of the raw
+ HTTP input.
- ``input_data`` is a file-like object that supports ``read()``-ing.
+ ``input_data`` is a file-like object that supports ``read()``-ing.
- ``META`` is the same object as ``request.META``.
+ ``META`` is the same object as ``request.META``.
- ``content_length`` is the length of the data in ``input_data``. Don't
- read more than ``content_length`` bytes from ``input_data``.
+ ``content_length`` is the length of the data in ``input_data``. Don't
+ read more than ``content_length`` bytes from ``input_data``.
- ``boundary`` is the MIME boundary for this request.
+ ``boundary`` is the MIME boundary for this request.
- ``encoding`` is the encoding of the request.
+ ``encoding`` is the encoding of the request.
- Return ``None`` if you want upload handling to continue, or a tuple of
- ``(POST, FILES)`` if you want to return the new data structures suitable
- for the request directly.
+ Return ``None`` if you want upload handling to continue, or a tuple of
+ ``(POST, FILES)`` if you want to return the new data structures suitable
+ for the request directly.
diff --git a/docs/topics/http/middleware.txt b/docs/topics/http/middleware.txt
index 01a5bd4cd3..a768a3bbd8 100644
--- a/docs/topics/http/middleware.txt
+++ b/docs/topics/http/middleware.txt
@@ -195,11 +195,11 @@ essentially placeholders for the ``process_*`` methods. If you do need some
global state you may use ``__init__`` to set up. However, keep in mind a couple
of caveats:
- * Django initializes your middleware without any arguments, so you can't
- define ``__init__`` as requiring any arguments.
+* Django initializes your middleware without any arguments, so you can't
+ define ``__init__`` as requiring any arguments.
- * Unlike the ``process_*`` methods which get called once per request,
- ``__init__`` gets called only *once*, when the Web server starts up.
+* Unlike the ``process_*`` methods which get called once per request,
+ ``__init__`` gets called only *once*, when the Web server starts up.
Marking middleware as unused
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -212,15 +212,15 @@ piece of middleware from the middleware process.
Guidelines
----------
- * Middleware classes don't have to subclass anything.
+* Middleware classes don't have to subclass anything.
- * The middleware class can live anywhere on your Python path. All Django
- cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
- the path to it.
+* The middleware class can live anywhere on your Python path. All Django
+ cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
+ the path to it.
- * Feel free to look at :doc:`Django's available middleware
- </ref/middleware>` for examples.
+* Feel free to look at :doc:`Django's available middleware
+ </ref/middleware>` for examples.
- * If you write a middleware component that you think would be useful to
- other people, contribute to the community! :doc:`Let us know
- </internals/contributing/index>`, and we'll consider adding it to Django.
+* If you write a middleware component that you think would be useful to
+ other people, contribute to the community! :doc:`Let us know
+ </internals/contributing/index>`, and we'll consider adding it to Django.
diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt
index 494b37cb94..a2849ae6eb 100644
--- a/docs/topics/http/sessions.txt
+++ b/docs/topics/http/sessions.txt
@@ -18,10 +18,10 @@ Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
To enable session functionality, do the following:
- * Edit the :setting:`MIDDLEWARE_CLASSES` setting and make sure
- it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
- The default ``settings.py`` created by ``django-admin.py startproject``
- has ``SessionMiddleware`` activated.
+* Edit the :setting:`MIDDLEWARE_CLASSES` setting and make sure
+ it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
+ The default ``settings.py`` created by ``django-admin.py startproject``
+ has ``SessionMiddleware`` activated.
If you don't want to use sessions, you might as well remove the
``SessionMiddleware`` line from :setting:`MIDDLEWARE_CLASSES` and
@@ -65,17 +65,17 @@ sure you've configured your cache; see the :doc:`cache documentation
Once your cache is configured, you've got two choices for how to store data in
the cache:
- * Set :setting:`SESSION_ENGINE` to
- ``"django.contrib.sessions.backends.cache"`` for a simple caching session
- store. Session data will be stored directly your cache. However, session
- data may not be persistent: cached data can be evicted if the cache fills
- up or if the cache server is restarted.
+* Set :setting:`SESSION_ENGINE` to
+ ``"django.contrib.sessions.backends.cache"`` for a simple caching session
+ store. Session data will be stored directly your cache. However, session
+ data may not be persistent: cached data can be evicted if the cache fills
+ up or if the cache server is restarted.
- * For persistent, cached data, set :setting:`SESSION_ENGINE` to
- ``"django.contrib.sessions.backends.cached_db"``. This uses a
- write-through cache -- every write to the cache will also be written to
- the database. Session reads only use the database if the data is not
- already in the cache.
+* For persistent, cached data, set :setting:`SESSION_ENGINE` to
+ ``"django.contrib.sessions.backends.cached_db"``. This uses a
+ write-through cache -- every write to the cache will also be written to
+ the database. Session reads only use the database if the data is not
+ already in the cache.
Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the ``cached_db`` backend will be fast
@@ -210,19 +210,19 @@ You can edit it multiple times.
Sets the expiration time for the session. You can pass a number of
different values:
- * If ``value`` is an integer, the session will expire after that
- many seconds of inactivity. For example, calling
- ``request.session.set_expiry(300)`` would make the session expire
- in 5 minutes.
+ * If ``value`` is an integer, the session will expire after that
+ many seconds of inactivity. For example, calling
+ ``request.session.set_expiry(300)`` would make the session expire
+ in 5 minutes.
- * If ``value`` is a ``datetime`` or ``timedelta`` object, the
- session will expire at that specific date/time.
+ * If ``value`` is a ``datetime`` or ``timedelta`` object, the
+ session will expire at that specific date/time.
- * If ``value`` is ``0``, the user's session cookie will expire
- when the user's Web browser is closed.
+ * If ``value`` is ``0``, the user's session cookie will expire
+ when the user's Web browser is closed.
- * If ``value`` is ``None``, the session reverts to using the global
- session expiry policy.
+ * If ``value`` is ``None``, the session reverts to using the global
+ session expiry policy.
Reading a session is not considered activity for expiration
purposes. Session expiration is computed from the last time the
@@ -248,14 +248,14 @@ You can edit it multiple times.
Session object guidelines
-------------------------
- * Use normal Python strings as dictionary keys on ``request.session``. This
- is more of a convention than a hard-and-fast rule.
+* Use normal Python strings as dictionary keys on ``request.session``. This
+ is more of a convention than a hard-and-fast rule.
- * Session dictionary keys that begin with an underscore are reserved for
- internal use by Django.
+* Session dictionary keys that begin with an underscore are reserved for
+ internal use by Django.
- * Don't override ``request.session`` with a new object, and don't access or
- set its attributes. Use it like a Python dictionary.
+* Don't override ``request.session`` with a new object, and don't access or
+ set its attributes. Use it like a Python dictionary.
Examples
--------
@@ -453,11 +453,11 @@ Default: ``django.contrib.sessions.backends.db``
Controls where Django stores session data. Valid values are:
- * ``'django.contrib.sessions.backends.db'``
- * ``'django.contrib.sessions.backends.file'``
- * ``'django.contrib.sessions.backends.cache'``
- * ``'django.contrib.sessions.backends.cached_db'``
- * ``'django.contrib.sessions.backends.signed_cookies'``
+* ``'django.contrib.sessions.backends.db'``
+* ``'django.contrib.sessions.backends.file'``
+* ``'django.contrib.sessions.backends.cache'``
+* ``'django.contrib.sessions.backends.cached_db'``
+* ``'django.contrib.sessions.backends.signed_cookies'``
See `configuring the session engine`_ for more details.
@@ -552,13 +552,13 @@ that is, if any of its dictionary values have been assigned or deleted.
Technical details
=================
- * The session dictionary should accept any pickleable Python object. See
- the :mod:`pickle` module for more information.
+* The session dictionary should accept any pickleable Python object. See
+ the :mod:`pickle` module for more information.
- * Session data is stored in a database table named ``django_session`` .
+* Session data is stored in a database table named ``django_session`` .
- * Django only sends a cookie if it needs to. If you don't set any session
- data, it won't send a session cookie.
+* Django only sends a cookie if it needs to. If you don't set any session
+ data, it won't send a session cookie.
Session IDs in URLs
===================
diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt
index 64b7c4a7e7..9c05c6e5e9 100644
--- a/docs/topics/http/shortcuts.txt
+++ b/docs/topics/http/shortcuts.txt
@@ -162,12 +162,12 @@ This example is equivalent to::
The arguments could be:
- * A model: the model's `get_absolute_url()` function will be called.
+ * A model: the model's `get_absolute_url()` function will be called.
- * A view name, possibly with arguments: `urlresolvers.reverse()` will
- be used to reverse-resolve the name.
+ * A view name, possibly with arguments: `urlresolvers.reverse()` will
+ be used to reverse-resolve the name.
- * A URL, which will be used as-is for the redirect location.
+ * A URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass ``permanent=True`` to issue a
permanent redirect
@@ -177,34 +177,34 @@ Examples
You can use the :func:`redirect` function in a number of ways.
- 1. By passing some object; that object's
- :meth:`~django.db.models.Model.get_absolute_url` method will be called
- to figure out the redirect URL::
+1. By passing some object; that object's
+ :meth:`~django.db.models.Model.get_absolute_url` method will be called
+ to figure out the redirect URL::
- def my_view(request):
- ...
- object = MyModel.objects.get(...)
- return redirect(object)
+ def my_view(request):
+ ...
+ object = MyModel.objects.get(...)
+ return redirect(object)
- 2. By passing the name of a view and optionally some positional or
- keyword arguments; the URL will be reverse resolved using the
- :func:`~django.core.urlresolvers.reverse` method::
+2. By passing the name of a view and optionally some positional or
+ keyword arguments; the URL will be reverse resolved using the
+ :func:`~django.core.urlresolvers.reverse` method::
- def my_view(request):
- ...
- return redirect('some-view-name', foo='bar')
+ def my_view(request):
+ ...
+ return redirect('some-view-name', foo='bar')
- 3. By passing a hardcoded URL to redirect to::
+3. By passing a hardcoded URL to redirect to::
- def my_view(request):
- ...
- return redirect('/some/url/')
+ def my_view(request):
+ ...
+ return redirect('/some/url/')
- This also works with full URLs::
+ This also works with full URLs::
- def my_view(request):
- ...
- return redirect('http://example.com/')
+ def my_view(request):
+ ...
+ return redirect('http://example.com/')
By default, :func:`redirect` returns a temporary redirect. All of the above
forms accept a ``permanent`` argument; if set to ``True`` a permanent redirect
diff --git a/docs/topics/http/urls.txt b/docs/topics/http/urls.txt
index 14d8a65e40..9349762312 100644
--- a/docs/topics/http/urls.txt
+++ b/docs/topics/http/urls.txt
@@ -42,27 +42,27 @@ How Django processes a request
When a user requests a page from your Django-powered site, this is the
algorithm the system follows to determine which Python code to execute:
- 1. Django determines the root URLconf module to use. Ordinarily,
- this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming
- ``HttpRequest`` object has an attribute called ``urlconf`` (set by
- middleware :ref:`request processing <request-middleware>`), its value
- will be used in place of the :setting:`ROOT_URLCONF` setting.
+1. Django determines the root URLconf module to use. Ordinarily,
+ this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming
+ ``HttpRequest`` object has an attribute called ``urlconf`` (set by
+ middleware :ref:`request processing <request-middleware>`), its value
+ will be used in place of the :setting:`ROOT_URLCONF` setting.
- 2. Django loads that Python module and looks for the variable
- ``urlpatterns``. This should be a Python list, in the format returned by
- the function :func:`django.conf.urls.patterns`.
+2. Django loads that Python module and looks for the variable
+ ``urlpatterns``. This should be a Python list, in the format returned by
+ the function :func:`django.conf.urls.patterns`.
- 3. Django runs through each URL pattern, in order, and stops at the first
- one that matches the requested URL.
+3. Django runs through each URL pattern, in order, and stops at the first
+ one that matches the requested URL.
- 4. Once one of the regexes matches, Django imports and calls the given
- view, which is a simple Python function. The view gets passed an
- :class:`~django.http.HttpRequest` as its first argument and any values
- captured in the regex as remaining arguments.
+4. Once one of the regexes matches, Django imports and calls the given
+ view, which is a simple Python function. The view gets passed an
+ :class:`~django.http.HttpRequest` as its first argument and any values
+ captured in the regex as remaining arguments.
- 5. If no regex matches, or if an exception is raised during any
- point in this process, Django invokes an appropriate
- error-handling view. See `Error handling`_ below.
+5. If no regex matches, or if an exception is raised during any
+ point in this process, Django invokes an appropriate
+ error-handling view. See `Error handling`_ below.
Example
=======
@@ -80,34 +80,34 @@ Here's a sample URLconf::
Notes:
- * To capture a value from the URL, just put parenthesis around it.
+* To capture a value from the URL, just put parenthesis around it.
- * There's no need to add a leading slash, because every URL has that. For
- example, it's ``^articles``, not ``^/articles``.
+* There's no need to add a leading slash, because every URL has that. For
+ example, it's ``^articles``, not ``^/articles``.
- * The ``'r'`` in front of each regular expression string is optional but
- recommended. It tells Python that a string is "raw" -- that nothing in
- the string should be escaped. See `Dive Into Python's explanation`_.
+* The ``'r'`` in front of each regular expression string is optional but
+ recommended. It tells Python that a string is "raw" -- that nothing in
+ the string should be escaped. See `Dive Into Python's explanation`_.
Example requests:
- * A request to ``/articles/2005/03/`` would match the third entry in the
- list. Django would call the function
- ``news.views.month_archive(request, '2005', '03')``.
+* A request to ``/articles/2005/03/`` would match the third entry in the
+ list. Django would call the function
+ ``news.views.month_archive(request, '2005', '03')``.
- * ``/articles/2005/3/`` would not match any URL patterns, because the
- third entry in the list requires two digits for the month.
+* ``/articles/2005/3/`` would not match any URL patterns, because the
+ third entry in the list requires two digits for the month.
- * ``/articles/2003/`` would match the first pattern in the list, not the
- second one, because the patterns are tested in order, and the first one
- is the first test to pass. Feel free to exploit the ordering to insert
- special cases like this.
+* ``/articles/2003/`` would match the first pattern in the list, not the
+ second one, because the patterns are tested in order, and the first one
+ is the first test to pass. Feel free to exploit the ordering to insert
+ special cases like this.
- * ``/articles/2003`` would not match any of these patterns, because each
- pattern requires that the URL end with a slash.
+* ``/articles/2003`` would not match any of these patterns, because each
+ pattern requires that the URL end with a slash.
- * ``/articles/2003/03/03/`` would match the final pattern. Django would call
- the function ``news.views.article_detail(request, '2003', '03', '03')``.
+* ``/articles/2003/03/03/`` would match the final pattern. Django would call
+ the function ``news.views.article_detail(request, '2003', '03', '03')``.
.. _Dive Into Python's explanation: http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
@@ -137,12 +137,12 @@ This accomplishes exactly the same thing as the previous example, with one
subtle difference: The captured values are passed to view functions as keyword
arguments rather than positional arguments. For example:
- * A request to ``/articles/2005/03/`` would call the function
- ``news.views.month_archive(request, year='2005', month='03')``, instead
- of ``news.views.month_archive(request, '2005', '03')``.
+* A request to ``/articles/2005/03/`` would call the function
+ ``news.views.month_archive(request, year='2005', month='03')``, instead
+ of ``news.views.month_archive(request, '2005', '03')``.
- * A request to ``/articles/2003/03/03/`` would call the function
- ``news.views.article_detail(request, year='2003', month='03', day='03')``.
+* A request to ``/articles/2003/03/03/`` would call the function
+ ``news.views.article_detail(request, year='2003', month='03', day='03')``.
In practice, this means your URLconfs are slightly more explicit and less prone
to argument-order bugs -- and you can reorder the arguments in your views'
@@ -518,17 +518,17 @@ provide a way to tell these named URLs apart.
A URL namespace comes in two parts, both of which are strings:
- * An **application namespace**. This describes the name of the application
- that is being deployed. Every instance of a single application will have
- the same application namespace. For example, Django's admin application
- has the somewhat predictable application namespace of ``admin``.
+* An **application namespace**. This describes the name of the application
+ that is being deployed. Every instance of a single application will have
+ the same application namespace. For example, Django's admin application
+ has the somewhat predictable application namespace of ``admin``.
- * An **instance namespace**. This identifies a specific instance of an
- application. Instance namespaces should be unique across your entire
- project. However, an instance namespace can be the same as the
- application namespace. This is used to specify a default instance of an
- application. For example, the default Django Admin instance has an
- instance namespace of ``admin``.
+* An **instance namespace**. This identifies a specific instance of an
+ application. Instance namespaces should be unique across your entire
+ project. However, an instance namespace can be the same as the
+ application namespace. This is used to specify a default instance of an
+ application. For example, the default Django Admin instance has an
+ instance namespace of ``admin``.
URL Namespaces can be specified in two ways.
@@ -745,31 +745,31 @@ the top-level namespace ``foo``.
When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits
the fully qualified name into parts, and then tries the following lookup:
- 1. First, Django looks for a matching application namespace (in this
- example, ``myapp``). This will yield a list of instances of that
- application.
+1. First, Django looks for a matching application namespace (in this
+ example, ``myapp``). This will yield a list of instances of that
+ application.
- 2. If there is a *current* application defined, Django finds and returns
- the URL resolver for that instance. The *current* application can be
- specified as an attribute on the template context - applications that
- expect to have multiple deployments should set the ``current_app``
- attribute on any ``Context`` or ``RequestContext`` that is used to
- render a template.
+2. If there is a *current* application defined, Django finds and returns
+ the URL resolver for that instance. The *current* application can be
+ specified as an attribute on the template context - applications that
+ expect to have multiple deployments should set the ``current_app``
+ attribute on any ``Context`` or ``RequestContext`` that is used to
+ render a template.
- The current application can also be specified manually as an argument
- to the :func:`reverse()` function.
+ The current application can also be specified manually as an argument
+ to the :func:`reverse()` function.
- 3. If there is no current application. Django looks for a default
- application instance. The default application instance is the instance
- that has an instance namespace matching the application namespace (in
- this example, an instance of the ``myapp`` called ``myapp``).
+3. If there is no current application. Django looks for a default
+ application instance. The default application instance is the instance
+ that has an instance namespace matching the application namespace (in
+ this example, an instance of the ``myapp`` called ``myapp``).
- 4. If there is no default application instance, Django will pick the last
- deployed instance of the application, whatever its instance name may be.
+4. If there is no default application instance, Django will pick the last
+ deployed instance of the application, whatever its instance name may be.
- 5. If the provided namespace doesn't match an application namespace in
- step 1, Django will attempt a direct lookup of the namespace as an
- instance namespace.
+5. If the provided namespace doesn't match an application namespace in
+ step 1, Django will attempt a direct lookup of the namespace as an
+ instance namespace.
If there are nested namespaces, these steps are repeated for each part of the
namespace until only the view name is unresolved. The view name will then be
@@ -780,31 +780,31 @@ of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main
index page with a URL named `index`. Using this setup, the following lookups are
possible:
- * If one of the instances is current - say, if we were rendering a utility page
- in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
- the instance ``bar``.
+* If one of the instances is current - say, if we were rendering a utility page
+ in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
+ the instance ``bar``.
- * If there is no current instance - say, if we were rendering a page
- somewhere else on the site - ``myapp:index`` will resolve to the last
- registered instance of ``myapp``. Since there is no default instance,
- the last instance of ``myapp`` that is registered will be used. This could
- be ``foo`` or ``bar``, depending on the order they are introduced into the
- urlpatterns of the project.
+* If there is no current instance - say, if we were rendering a page
+ somewhere else on the site - ``myapp:index`` will resolve to the last
+ registered instance of ``myapp``. Since there is no default instance,
+ the last instance of ``myapp`` that is registered will be used. This could
+ be ``foo`` or ``bar``, depending on the order they are introduced into the
+ urlpatterns of the project.
- * ``foo:index`` will always resolve to the index page of the instance ``foo``.
+* ``foo:index`` will always resolve to the index page of the instance ``foo``.
If there was also a default instance - i.e., an instance named `myapp` - the
following would happen:
- * If one of the instances is current - say, if we were rendering a utility page
- in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
- the instance ``bar``.
+* If one of the instances is current - say, if we were rendering a utility page
+ in the instance ``bar`` - ``myapp:index`` will resolve to the index page of
+ the instance ``bar``.
- * If there is no current instance - say, if we were rendering a page somewhere
- else on the site - ``myapp:index`` will resolve to the index page of the
- default instance.
+* If there is no current instance - say, if we were rendering a page somewhere
+ else on the site - ``myapp:index`` will resolve to the index page of the
+ default instance.
- * ``foo:index`` will again resolve to the index page of the instance ``foo``.
+* ``foo:index`` will again resolve to the index page of the instance ``foo``.
``django.core.urlresolvers`` utility functions
diff --git a/docs/topics/http/views.txt b/docs/topics/http/views.txt
index 247669d9ea..a8c85ddf6e 100644
--- a/docs/topics/http/views.txt
+++ b/docs/topics/http/views.txt
@@ -29,22 +29,22 @@ Here's a view that returns the current date and time, as an HTML document:
Let's step through this code one line at a time:
- * First, we import the class :class:`~django.http.HttpResponse` from the
- :mod:`django.http` module, along with Python's ``datetime`` library.
+* First, we import the class :class:`~django.http.HttpResponse` from the
+ :mod:`django.http` module, along with Python's ``datetime`` library.
- * Next, we define a function called ``current_datetime``. This is the view
- function. Each view function takes an :class:`~django.http.HttpRequest`
- object as its first parameter, which is typically named ``request``.
+* Next, we define a function called ``current_datetime``. This is the view
+ function. Each view function takes an :class:`~django.http.HttpRequest`
+ object as its first parameter, which is typically named ``request``.
- Note that the name of the view function doesn't matter; it doesn't have to
- be named in a certain way in order for Django to recognize it. We're
- calling it ``current_datetime`` here, because that name clearly indicates
- what it does.
+ Note that the name of the view function doesn't matter; it doesn't have to
+ be named in a certain way in order for Django to recognize it. We're
+ calling it ``current_datetime`` here, because that name clearly indicates
+ what it does.
- * The view returns an :class:`~django.http.HttpResponse` object that
- contains the generated response. Each view function is responsible for
- returning an :class:`~django.http.HttpResponse` object. (There are
- exceptions, but we'll get to those later.)
+* The view returns an :class:`~django.http.HttpResponse` object that
+ contains the generated response. Each view function is responsible for
+ returning an :class:`~django.http.HttpResponse` object. (There are
+ exceptions, but we'll get to those later.)
.. admonition:: Django's Time Zone
@@ -152,20 +152,20 @@ Behind the scenes, Django determines the 404 view by looking for
Four things to note about 404 views:
- * The 404 view is also called if Django doesn't find a match after
- checking every regular expression in the URLconf.
+* The 404 view is also called if Django doesn't find a match after
+ checking every regular expression in the URLconf.
- * If you don't define your own 404 view — and simply use the default,
- which is recommended — you still have one obligation: you must create a
- ``404.html`` template in the root of your template directory.
+* If you don't define your own 404 view — and simply use the default,
+ which is recommended — you still have one obligation: you must create a
+ ``404.html`` template in the root of your template directory.
- * The 404 view is passed a :class:`~django.template.RequestContext` and
- will have access to variables supplied by your
- :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting (e.g., ``MEDIA_URL``).
+* The 404 view is passed a :class:`~django.template.RequestContext` and
+ will have access to variables supplied by your
+ :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting (e.g., ``MEDIA_URL``).
- * If :setting:`DEBUG` is set to ``True`` (in your settings module), then
- your 404 view will never be used, and your URLconf will be displayed
- instead, with some debug information.
+* If :setting:`DEBUG` is set to ``True`` (in your settings module), then
+ your 404 view will never be used, and your URLconf will be displayed
+ instead, with some debug information.
The 500 (server error) view
----------------------------
@@ -192,13 +192,13 @@ Behind the scenes, Django determines the 500 view by looking for
Two things to note about 500 views:
- * If you don't define your own 500 view — and simply use the default,
- which is recommended — you still have one obligation: you must create a
- ``500.html`` template in the root of your template directory.
+* If you don't define your own 500 view — and simply use the default,
+ which is recommended — you still have one obligation: you must create a
+ ``500.html`` template in the root of your template directory.
- * If :setting:`DEBUG` is set to ``True`` (in your settings module), then
- your 500 view will never be used, and the traceback will be displayed
- instead, with some debug information.
+* If :setting:`DEBUG` is set to ``True`` (in your settings module), then
+ your 500 view will never be used, and the traceback will be displayed
+ instead, with some debug information.
.. _http_forbidden_view:
diff --git a/docs/topics/i18n/deployment.txt b/docs/topics/i18n/deployment.txt
index 641deae939..eed5c96af7 100644
--- a/docs/topics/i18n/deployment.txt
+++ b/docs/topics/i18n/deployment.txt
@@ -57,12 +57,12 @@ To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
to your :setting:`MIDDLEWARE_CLASSES` setting. Because middleware order
matters, you should follow these guidelines:
- * Make sure it's one of the first middlewares installed.
- * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
- makes use of session data. And it should come before ``CommonMiddleware``
- because ``CommonMiddleware`` needs an activated language in order
- to resolve the requested URL.
- * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
+* Make sure it's one of the first middlewares installed.
+* It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
+ makes use of session data. And it should come before ``CommonMiddleware``
+ because ``CommonMiddleware`` needs an activated language in order
+ to resolve the requested URL.
+* If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
For example, your :setting:`MIDDLEWARE_CLASSES` might look like this::
@@ -80,83 +80,83 @@ following this algorithm:
.. versionchanged:: 1.4
- * First, it looks for the language prefix in the requested URL. This is
- only performed when you are using the ``i18n_patterns`` function in your
- root URLconf. See :ref:`url-internationalization` for more information
- about the language prefix and how to internationalize URL patterns.
+* First, it looks for the language prefix in the requested URL. This is
+ only performed when you are using the ``i18n_patterns`` function in your
+ root URLconf. See :ref:`url-internationalization` for more information
+ about the language prefix and how to internationalize URL patterns.
- * Failing that, it looks for a ``django_language`` key in the current
- user's session.
+* Failing that, it looks for a ``django_language`` key in the current
+ user's session.
- * Failing that, it looks for a cookie.
+* Failing that, it looks for a cookie.
- The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
- setting. (The default name is ``django_language``.)
+ The name of the cookie used is set by the :setting:`LANGUAGE_COOKIE_NAME`
+ setting. (The default name is ``django_language``.)
- * Failing that, it looks at the ``Accept-Language`` HTTP header. This
- header is sent by your browser and tells the server which language(s) you
- prefer, in order by priority. Django tries each language in the header
- until it finds one with available translations.
+* Failing that, it looks at the ``Accept-Language`` HTTP header. This
+ header is sent by your browser and tells the server which language(s) you
+ prefer, in order by priority. Django tries each language in the header
+ until it finds one with available translations.
- * Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
+* Failing that, it uses the global :setting:`LANGUAGE_CODE` setting.
.. _locale-middleware-notes:
Notes:
- * In each of these places, the language preference is expected to be in the
- standard :term:`language format<language code>`, as a string. For example,
- Brazilian Portuguese is ``pt-br``.
+* In each of these places, the language preference is expected to be in the
+ standard :term:`language format<language code>`, as a string. For example,
+ Brazilian Portuguese is ``pt-br``.
- * If a base language is available but the sublanguage specified is not,
- Django uses the base language. For example, if a user specifies ``de-at``
- (Austrian German) but Django only has ``de`` available, Django uses
- ``de``.
+* If a base language is available but the sublanguage specified is not,
+ Django uses the base language. For example, if a user specifies ``de-at``
+ (Austrian German) but Django only has ``de`` available, Django uses
+ ``de``.
- * Only languages listed in the :setting:`LANGUAGES` setting can be selected.
- If you want to restrict the language selection to a subset of provided
- languages (because your application doesn't provide all those languages),
- set :setting:`LANGUAGES` to a list of languages. For example::
+* Only languages listed in the :setting:`LANGUAGES` setting can be selected.
+ If you want to restrict the language selection to a subset of provided
+ languages (because your application doesn't provide all those languages),
+ set :setting:`LANGUAGES` to a list of languages. For example::
- LANGUAGES = (
- ('de', _('German')),
- ('en', _('English')),
- )
+ LANGUAGES = (
+ ('de', _('German')),
+ ('en', _('English')),
+ )
- This example restricts languages that are available for automatic
- selection to German and English (and any sublanguage, like de-ch or
- en-us).
+ This example restricts languages that are available for automatic
+ selection to German and English (and any sublanguage, like de-ch or
+ en-us).
- * If you define a custom :setting:`LANGUAGES` setting, as explained in the
- previous bullet, it's OK to mark the languages as translation strings
- -- but use a "dummy" ``ugettext()`` function, not the one in
- ``django.utils.translation``. You should *never* import
- ``django.utils.translation`` from within your settings file, because that
- module in itself depends on the settings, and that would cause a circular
- import.
+* If you define a custom :setting:`LANGUAGES` setting, as explained in the
+ previous bullet, it's OK to mark the languages as translation strings
+ -- but use a "dummy" ``ugettext()`` function, not the one in
+ ``django.utils.translation``. You should *never* import
+ ``django.utils.translation`` from within your settings file, because that
+ module in itself depends on the settings, and that would cause a circular
+ import.
- The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
- settings file::
+ The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
+ settings file::
- ugettext = lambda s: s
+ ugettext = lambda s: s
- LANGUAGES = (
- ('de', ugettext('German')),
- ('en', ugettext('English')),
- )
+ LANGUAGES = (
+ ('de', ugettext('German')),
+ ('en', ugettext('English')),
+ )
- With this arrangement, ``django-admin.py makemessages`` will still find
- and mark these strings for translation, but the translation won't happen
- at runtime -- so you'll have to remember to wrap the languages in the
- *real* ``ugettext()`` in any code that uses :setting:`LANGUAGES` at
- runtime.
+ With this arrangement, ``django-admin.py makemessages`` will still find
+ and mark these strings for translation, but the translation won't happen
+ at runtime -- so you'll have to remember to wrap the languages in the
+ *real* ``ugettext()`` in any code that uses :setting:`LANGUAGES` at
+ runtime.
- * The ``LocaleMiddleware`` can only select languages for which there is a
- Django-provided base translation. If you want to provide translations
- for your application that aren't already in the set of translations
- in Django's source tree, you'll want to provide at least a basic
- one as described in the :ref:`Locale restrictions<locale-restrictions>`
- note.
+* The ``LocaleMiddleware`` can only select languages for which there is a
+ Django-provided base translation. If you want to provide translations
+ for your application that aren't already in the set of translations
+ in Django's source tree, you'll want to provide at least a basic
+ one as described in the :ref:`Locale restrictions<locale-restrictions>`
+ note.
Once ``LocaleMiddleware`` determines the user's preference, it makes this
preference available as ``request.LANGUAGE_CODE`` for each
@@ -187,16 +187,16 @@ examines the different file paths to load the compiled :term:`message files
<message file>` (``.mo``) and the precedence of multiple translations for the
same literal:
- 1. The directories listed in :setting:`LOCALE_PATHS` have the highest
- precedence, with the ones appearing first having higher precedence than
- the ones appearing later.
- 2. Then, it looks for and uses if it exists a ``locale`` directory in each
- of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
- appearing first have higher precedence than the ones appearing later.
- 3. Then, it looks for a ``locale`` directory in the project directory, or
- more accurately, in the directory containing your settings file.
- 4. Finally, the Django-provided base translation in ``django/conf/locale``
- is used as a fallback.
+1. The directories listed in :setting:`LOCALE_PATHS` have the highest
+ precedence, with the ones appearing first having higher precedence than
+ the ones appearing later.
+2. Then, it looks for and uses if it exists a ``locale`` directory in each
+ of the installed apps listed in :setting:`INSTALLED_APPS`. The ones
+ appearing first have higher precedence than the ones appearing later.
+3. Then, it looks for a ``locale`` directory in the project directory, or
+ more accurately, in the directory containing your settings file.
+4. Finally, the Django-provided base translation in ``django/conf/locale``
+ is used as a fallback.
.. deprecated:: 1.3
Lookup in the ``locale`` subdirectory of the directory containing your
diff --git a/docs/topics/i18n/index.txt b/docs/topics/i18n/index.txt
index 95e2063c81..e499fecb0f 100644
--- a/docs/topics/i18n/index.txt
+++ b/docs/topics/i18n/index.txt
@@ -10,21 +10,21 @@ templates, and format localization of dates and numbers. Here's how it works.
Essentially, Django does two things:
- * It allows developers and template authors to specify which parts of
- their apps should be translatable.
- * It uses these hooks to translate Web apps for particular users according
- to their language preferences.
+* It allows developers and template authors to specify which parts of
+ their apps should be translatable.
+* It uses these hooks to translate Web apps for particular users according
+ to their language preferences.
The complete process can be seen as divided in three stages. It is also possible
to identify an identical number of roles with very well defined responsibilities
associated with each of these tasks (although it's perfectly normal if you
find yourself performing more than one of these roles):
- * For application authors wishing to make sure their Django apps can be
- used in different locales: :doc:`/topics/i18n/internationalization`.
- * For translators wanting to translate Django apps: :doc:`/topics/i18n/localization`.
- * For system administrators/final users setting up internationalized apps or
- developers integrating third party apps: :doc:`/topics/i18n/deployment`.
+* For application authors wishing to make sure their Django apps can be
+ used in different locales: :doc:`/topics/i18n/internationalization`.
+* For translators wanting to translate Django apps: :doc:`/topics/i18n/localization`.
+* For system administrators/final users setting up internationalized apps or
+ developers integrating third party apps: :doc:`/topics/i18n/deployment`.
.. toctree::
:hidden:
@@ -79,12 +79,12 @@ Django's translation machinery uses the standard ``gettext`` module that comes
with Python. If you know ``gettext``, you might note these specialties in the
way Django does translation:
- * The string domain is ``django`` or ``djangojs``. This string domain is
- used to differentiate between different programs that store their data
- in a common message-file library (usually ``/usr/share/locale/``). The
- ``django`` domain is used for python and template translation strings
- and is loaded into the global translation catalogs. The ``djangojs``
- domain is only used for JavaScript translation catalogs to make sure
- that those are as small as possible.
- * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
- ``xgettext`` and ``msgfmt``. This is mostly for convenience.
+* The string domain is ``django`` or ``djangojs``. This string domain is
+ used to differentiate between different programs that store their data
+ in a common message-file library (usually ``/usr/share/locale/``). The
+ ``django`` domain is used for python and template translation strings
+ and is loaded into the global translation catalogs. The ``djangojs``
+ domain is only used for JavaScript translation catalogs to make sure
+ that those are as small as possible.
+* Django doesn't use ``xgettext`` alone. It uses Python wrappers around
+ ``xgettext`` and ``msgfmt``. This is mostly for convenience.
diff --git a/docs/topics/i18n/internationalization.txt b/docs/topics/i18n/internationalization.txt
index 4756b2448d..b06c9bdfdb 100644
--- a/docs/topics/i18n/internationalization.txt
+++ b/docs/topics/i18n/internationalization.txt
@@ -35,18 +35,18 @@ as a shorter alias, ``_``, to save typing.
global namespace, as an alias for ``gettext()``. In Django, we have chosen
not to follow this practice, for a couple of reasons:
- 1. For international character set (Unicode) support,
- :func:`~django.utils.translation.ugettext` is more useful than
- ``gettext()``. Sometimes, you should be using
- :func:`~django.utils.translation.ugettext_lazy` as the default
- translation method for a particular file. Without ``_()`` in the
- global namespace, the developer has to think about which is the
- most appropriate translation function.
+ 1. For international character set (Unicode) support,
+ :func:`~django.utils.translation.ugettext` is more useful than
+ ``gettext()``. Sometimes, you should be using
+ :func:`~django.utils.translation.ugettext_lazy` as the default
+ translation method for a particular file. Without ``_()`` in the
+ global namespace, the developer has to think about which is the
+ most appropriate translation function.
- 2. The underscore character (``_``) is used to represent "the previous
- result" in Python's interactive shell and doctest tests. Installing a
- global ``_()`` function causes interference. Explicitly importing
- ``ugettext()`` as ``_()`` avoids this problem.
+ 2. The underscore character (``_``) is used to represent "the previous
+ result" in Python's interactive shell and doctest tests. Installing a
+ global ``_()`` function causes interference. Explicitly importing
+ ``ugettext()`` as ``_()`` avoids this problem.
.. highlightlang:: python
@@ -523,12 +523,12 @@ function.
This tag also provides for pluralization. To use it:
- * Designate and bind a counter value with the name ``count``. This value will
- be the one used to select the right plural form.
+* Designate and bind a counter value with the name ``count``. This value will
+ be the one used to select the right plural form.
- * Specify both the singular and plural forms separating them with the
- ``{% plural %}`` tag within the ``{% blocktrans %}`` and
- ``{% endblocktrans %}`` tags.
+* Specify both the singular and plural forms separating them with the
+ ``{% plural %}`` tag within the ``{% blocktrans %}`` and
+ ``{% endblocktrans %}`` tags.
An example::
@@ -567,16 +567,16 @@ Other tags
Each ``RequestContext`` has access to three translation-specific variables:
- * ``LANGUAGES`` is a list of tuples in which the first element is the
- :term:`language code` and the second is the language name (translated into
- the currently active locale).
+* ``LANGUAGES`` is a list of tuples in which the first element is the
+ :term:`language code` and the second is the language name (translated into
+ the currently active locale).
- * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
- Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`.)
+* ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
+ Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`.)
- * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
- right-to-left language, e.g.: Hebrew, Arabic. If False it's a
- left-to-right language, e.g.: English, French, German etc.
+* ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
+ right-to-left language, e.g.: Hebrew, Arabic. If False it's a
+ left-to-right language, e.g.: English, French, German etc.
If you don't use the ``RequestContext`` extension, you can get those values with
three tags::
@@ -643,9 +643,9 @@ you can iterate over those languages in the template::
There are also simple filters available for convenience:
- * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
- * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
- * ``{{ LANGUAGE_CODE|bidi }}`` (False)
+* ``{{ LANGUAGE_CODE|language_name }}`` ("German")
+* ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
+* ``{{ LANGUAGE_CODE|bidi }}`` (False)
.. _Django templates: ../templates_python/
@@ -656,13 +656,13 @@ Specifying translation strings: In JavaScript code
Adding translations to JavaScript poses some problems:
- * JavaScript code doesn't have access to a ``gettext`` implementation.
+* JavaScript code doesn't have access to a ``gettext`` implementation.
- * JavaScript code doesn't have access to .po or .mo files; they need to be
- delivered by the server.
+* JavaScript code doesn't have access to .po or .mo files; they need to be
+ delivered by the server.
- * The translation catalogs for JavaScript should be kept as small as
- possible.
+* The translation catalogs for JavaScript should be kept as small as
+ possible.
Django provides an integrated solution for these problems: It passes the
translations into JavaScript, so you can call ``gettext``, etc., from within
@@ -761,28 +761,28 @@ and even a string interpolation function::
The interpolation syntax is borrowed from Python, so the ``interpolate``
function supports both positional and named interpolation:
- * Positional interpolation: ``obj`` contains a JavaScript Array object
- whose elements values are then sequentially interpolated in their
- corresponding ``fmt`` placeholders in the same order they appear.
- For example::
+* Positional interpolation: ``obj`` contains a JavaScript Array object
+ whose elements values are then sequentially interpolated in their
+ corresponding ``fmt`` placeholders in the same order they appear.
+ For example::
- fmts = ngettext('There is %s object. Remaining: %s',
- 'There are %s objects. Remaining: %s', 11);
- s = interpolate(fmts, [11, 20]);
- // s is 'There are 11 objects. Remaining: 20'
+ fmts = ngettext('There is %s object. Remaining: %s',
+ 'There are %s objects. Remaining: %s', 11);
+ s = interpolate(fmts, [11, 20]);
+ // s is 'There are 11 objects. Remaining: 20'
- * Named interpolation: This mode is selected by passing the optional
- boolean ``named`` parameter as true. ``obj`` contains a JavaScript
- object or associative array. For example::
+* Named interpolation: This mode is selected by passing the optional
+ boolean ``named`` parameter as true. ``obj`` contains a JavaScript
+ object or associative array. For example::
- d = {
- count: 10,
- total: 50
- };
+ d = {
+ count: 10,
+ total: 50
+ };
- fmts = ngettext('Total: %(total)s, there is %(count)s object',
- 'there are %(count)s of a total of %(total)s objects', d.count);
- s = interpolate(fmts, d, true);
+ fmts = ngettext('Total: %(total)s, there is %(count)s object',
+ 'there are %(count)s of a total of %(total)s objects', d.count);
+ s = interpolate(fmts, d, true);
You shouldn't go over the top with string interpolation, though: this is still
JavaScript, so the code has to make repeated regular-expression substitutions.
@@ -975,11 +975,11 @@ language choice in a cookie that is by default named ``django_language``.
After setting the language choice, Django redirects the user, following this
algorithm:
- * Django looks for a ``next`` parameter in the ``POST`` data.
- * If that doesn't exist, or is empty, Django tries the URL in the
- ``Referrer`` header.
- * If that's empty -- say, if a user's browser suppresses that header --
- then the user will be redirected to ``/`` (the site root) as a fallback.
+* Django looks for a ``next`` parameter in the ``POST`` data.
+* If that doesn't exist, or is empty, Django tries the URL in the
+ ``Referrer`` header.
+* If that's empty -- say, if a user's browser suppresses that header --
+ then the user will be redirected to ``/`` (the site root) as a fallback.
Here's example HTML template code:
diff --git a/docs/topics/i18n/localization.txt b/docs/topics/i18n/localization.txt
index 88d74bd1e0..13a970f02f 100644
--- a/docs/topics/i18n/localization.txt
+++ b/docs/topics/i18n/localization.txt
@@ -70,8 +70,8 @@ German.
The script should be run from one of two places:
- * The root directory of your Django project.
- * The root directory of your Django app.
+* The root directory of your Django project.
+* The root directory of your Django app.
The script runs over your project source tree or your application source tree
and pulls out all strings marked for translation. It creates (or updates) a
@@ -128,14 +128,14 @@ containing the following snippet -- a message::
A quick explanation:
- * ``msgid`` is the translation string, which appears in the source. Don't
- change it.
- * ``msgstr`` is where you put the language-specific translation. It starts
- out empty, so it's your responsibility to change it. Make sure you keep
- the quotes around your translation.
- * As a convenience, each message includes, in the form of a comment line
- prefixed with ``#`` and located above the ``msgid`` line, the filename and
- line number from which the translation string was gleaned.
+* ``msgid`` is the translation string, which appears in the source. Don't
+ change it.
+* ``msgstr`` is where you put the language-specific translation. It starts
+ out empty, so it's your responsibility to change it. Make sure you keep
+ the quotes around your translation.
+* As a convenience, each message includes, in the form of a comment line
+ prefixed with ``#`` and located above the ``msgid`` line, the filename and
+ line number from which the translation string was gleaned.
Long messages are a special case. There, the first string directly after the
``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
@@ -213,24 +213,24 @@ message files (``.po``). Translation work itself just involves editing existing
files of this type, but if you want to create your own message files, or want to
test or compile a changed message file, you will need the ``gettext`` utilities:
- * Download the following zip files from the GNOME servers
- http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ or from one
- of its mirrors_
+* Download the following zip files from the GNOME servers
+ http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/ or from one
+ of its mirrors_
- * ``gettext-runtime-X.zip``
- * ``gettext-tools-X.zip``
+ * ``gettext-runtime-X.zip``
+ * ``gettext-tools-X.zip``
- ``X`` is the version number, we are requiring ``0.15`` or higher.
+ ``X`` is the version number, we are requiring ``0.15`` or higher.
- * Extract the contents of the ``bin\`` directories in both files to the
- same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
+* Extract the contents of the ``bin\`` directories in both files to the
+ same folder on your system (i.e. ``C:\Program Files\gettext-utils``)
- * Update the system PATH:
+* Update the system PATH:
- * ``Control Panel > System > Advanced > Environment Variables``.
- * In the ``System variables`` list, click ``Path``, click ``Edit``.
- * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
- ``Variable value`` field.
+ * ``Control Panel > System > Advanced > Environment Variables``.
+ * In the ``System variables`` list, click ``Path``, click ``Edit``.
+ * Add ``;C:\Program Files\gettext-utils\bin`` at the end of the
+ ``Variable value`` field.
.. _mirrors: http://ftp.gnome.org/pub/GNOME/MIRRORS
diff --git a/docs/topics/install.txt b/docs/topics/install.txt
index 70b0783957..089e1d3781 100644
--- a/docs/topics/install.txt
+++ b/docs/topics/install.txt
@@ -198,19 +198,19 @@ of dependencies and easy upgrade paths.
Installing an official release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 1. Download the latest release from our `download page`_.
+1. Download the latest release from our `download page`_.
- 2. Untar the downloaded file (e.g. ``tar xzvf Django-NNN.tar.gz``,
- where ``NNN`` is the version number of the latest release).
- If you're using Windows, you can download the command-line tool
- bsdtar_ to do this, or you can use a GUI-based tool such as 7-zip_.
+2. Untar the downloaded file (e.g. ``tar xzvf Django-NNN.tar.gz``,
+ where ``NNN`` is the version number of the latest release).
+ If you're using Windows, you can download the command-line tool
+ bsdtar_ to do this, or you can use a GUI-based tool such as 7-zip_.
- 3. Change into the directory created in step 2 (e.g. ``cd Django-NNN``).
+3. Change into the directory created in step 2 (e.g. ``cd Django-NNN``).
- 4. If you're using Linux, Mac OS X or some other flavor of Unix, enter
- the command ``sudo python setup.py install`` at the shell prompt.
- If you're using Windows, start up a command shell with administrator
- privileges and run the command ``setup.py install``.
+4. If you're using Linux, Mac OS X or some other flavor of Unix, enter
+ the command ``sudo python setup.py install`` at the shell prompt.
+ If you're using Windows, start up a command shell with administrator
+ privileges and run the command ``setup.py install``.
These commands will install Django in your Python installation's
``site-packages`` directory.
diff --git a/docs/topics/logging.txt b/docs/topics/logging.txt
index 0175e8576f..c468b31778 100644
--- a/docs/topics/logging.txt
+++ b/docs/topics/logging.txt
@@ -20,10 +20,10 @@ The cast of players
A Python logging configuration consists of four parts:
- * :ref:`topic-logging-parts-loggers`
- * :ref:`topic-logging-parts-handlers`
- * :ref:`topic-logging-parts-filters`
- * :ref:`topic-logging-parts-formatters`
+* :ref:`topic-logging-parts-loggers`
+* :ref:`topic-logging-parts-handlers`
+* :ref:`topic-logging-parts-filters`
+* :ref:`topic-logging-parts-formatters`
.. _topic-logging-parts-loggers:
@@ -37,18 +37,18 @@ A logger is configured to have a *log level*. This log level describes
the severity of the messages that the logger will handle. Python
defines the following log levels:
- * ``DEBUG``: Low level system information for debugging purposes
+* ``DEBUG``: Low level system information for debugging purposes
- * ``INFO``: General system information
+* ``INFO``: General system information
- * ``WARNING``: Information describing a minor problem that has
- occurred.
+* ``WARNING``: Information describing a minor problem that has
+ occurred.
- * ``ERROR``: Information describing a major problem that has
- occurred.
+* ``ERROR``: Information describing a major problem that has
+ occurred.
- * ``CRITICAL``: Information describing a critical problem that has
- occurred.
+* ``CRITICAL``: Information describing a critical problem that has
+ occurred.
Each message that is written to the logger is a *Log Record*. Each log
record also has a *log level* indicating the severity of that specific
@@ -180,19 +180,19 @@ Making logging calls
The logger instance contains an entry method for each of the default
log levels:
- * ``logger.critical()``
- * ``logger.error()``
- * ``logger.warning()``
- * ``logger.info()``
- * ``logger.debug()``
+* ``logger.critical()``
+* ``logger.error()``
+* ``logger.warning()``
+* ``logger.info()``
+* ``logger.debug()``
There are two other logging calls available:
- * ``logger.log()``: Manually emits a logging message with a
- specific log level.
+* ``logger.log()``: Manually emits a logging message with a
+ specific log level.
- * ``logger.exception()``: Creates an ``ERROR`` level logging
- message wrapping the current exception stack frame.
+* ``logger.exception()``: Creates an ``ERROR`` level logging
+ message wrapping the current exception stack frame.
Configuring logging
===================
@@ -289,63 +289,62 @@ complex logging setup, configured using :meth:`logging.dictConfig`::
This logging configuration does the following things:
- * Identifies the configuration as being in 'dictConfig version 1'
- format. At present, this is the only dictConfig format version.
+* Identifies the configuration as being in 'dictConfig version 1'
+ format. At present, this is the only dictConfig format version.
- * Disables all existing logging configurations.
+* Disables all existing logging configurations.
- * Defines two formatters:
+* Defines two formatters:
- * ``simple``, that just outputs the log level name (e.g.,
- ``DEBUG``) and the log message.
+ * ``simple``, that just outputs the log level name (e.g.,
+ ``DEBUG``) and the log message.
- The `format` string is a normal Python formatting string
- describing the details that are to be output on each logging
- line. The full list of detail that can be output can be
- found in the `formatter documentation`_.
+ The `format` string is a normal Python formatting string
+ describing the details that are to be output on each logging
+ line. The full list of detail that can be output can be
+ found in the `formatter documentation`_.
- * ``verbose``, that outputs the log level name, the log
- message, plus the time, process, thread and module that
- generate the log message.
+ * ``verbose``, that outputs the log level name, the log
+ message, plus the time, process, thread and module that
+ generate the log message.
+* Defines one filter -- :class:`project.logging.SpecialFilter`,
+ using the alias ``special``. If this filter required additional
+ arguments at time of construction, they can be provided as
+ additional keys in the filter configuration dictionary. In this
+ case, the argument ``foo`` will be given a value of ``bar`` when
+ instantiating the :class:`SpecialFilter`.
- * Defines one filter -- :class:`project.logging.SpecialFilter`,
- using the alias ``special``. If this filter required additional
- arguments at time of construction, they can be provided as
- additional keys in the filter configuration dictionary. In this
- case, the argument ``foo`` will be given a value of ``bar`` when
- instantiating the :class:`SpecialFilter`.
+* Defines three handlers:
- * Defines three handlers:
+ * ``null``, a NullHandler, which will pass any ``DEBUG`` or
+ higher message to ``/dev/null``.
- * ``null``, a NullHandler, which will pass any ``DEBUG`` or
- higher message to ``/dev/null``.
+ * ``console``, a StreamHandler, which will print any ``DEBUG``
+ message to stdout. This handler uses the `simple` output
+ format.
- * ``console``, a StreamHandler, which will print any ``DEBUG``
- message to stdout. This handler uses the `simple` output
- format.
+ * ``mail_admins``, an AdminEmailHandler, which will email any
+ ``ERROR`` level message to the site admins. This handler uses
+ the ``special`` filter.
- * ``mail_admins``, an AdminEmailHandler, which will email any
- ``ERROR`` level message to the site admins. This handler uses
- the ``special`` filter.
+* Configures three loggers:
- * Configures three loggers:
+ * ``django``, which passes all messages at ``INFO`` or higher
+ to the ``null`` handler.
- * ``django``, which passes all messages at ``INFO`` or higher
- to the ``null`` handler.
+ * ``django.request``, which passes all ``ERROR`` messages to
+ the ``mail_admins`` handler. In addition, this logger is
+ marked to *not* propagate messages. This means that log
+ messages written to ``django.request`` will not be handled
+ by the ``django`` logger.
- * ``django.request``, which passes all ``ERROR`` messages to
- the ``mail_admins`` handler. In addition, this logger is
- marked to *not* propagate messages. This means that log
- messages written to ``django.request`` will not be handled
- by the ``django`` logger.
-
- * ``myproject.custom``, which passes all messages at ``INFO``
- or higher that also pass the ``special`` filter to two
- handlers -- the ``console``, and ``mail_admins``. This
- means that all ``INFO`` level messages (or higher) will be
- printed to the console; ``ERROR`` and ``CRITICAL``
- messages will also be output via email.
+ * ``myproject.custom``, which passes all messages at ``INFO``
+ or higher that also pass the ``special`` filter to two
+ handlers -- the ``console``, and ``mail_admins``. This
+ means that all ``INFO`` level messages (or higher) will be
+ printed to the console; ``ERROR`` and ``CRITICAL``
+ messages will also be output via email.
.. admonition:: Custom handlers and circular imports
@@ -433,11 +432,11 @@ messages.
Messages to this logger have the following extra context:
- * ``status_code``: The HTTP response code associated with the
- request.
+* ``status_code``: The HTTP response code associated with the
+ request.
- * ``request``: The request object that generated the logging
- message.
+* ``request``: The request object that generated the logging
+ message.
``django.db.backends``
~~~~~~~~~~~~~~~~~~~~~~
@@ -448,9 +447,9 @@ at the ``DEBUG`` level to this logger.
Messages to this logger have the following extra context:
- * ``duration``: The time taken to execute the SQL statement.
- * ``sql``: The SQL statement that was executed.
- * ``params``: The parameters that were used in the SQL call.
+* ``duration``: The time taken to execute the SQL statement.
+* ``sql``: The SQL statement that was executed.
+* ``params``: The parameters that were used in the SQL call.
For performance reasons, SQL logging is only enabled when
``settings.DEBUG`` is set to ``True``, regardless of the logging
diff --git a/docs/topics/serialization.txt b/docs/topics/serialization.txt
index b23fd7f94e..1ec76941cc 100644
--- a/docs/topics/serialization.txt
+++ b/docs/topics/serialization.txt
@@ -138,17 +138,17 @@ Serialization formats
Django supports a number of serialization formats, some of which require you
to install third-party Python modules:
- ========== ==============================================================
- Identifier Information
- ========== ==============================================================
- ``xml`` Serializes to and from a simple XML dialect.
+========== ==============================================================
+Identifier Information
+========== ==============================================================
+``xml`` Serializes to and from a simple XML dialect.
- ``json`` Serializes to and from JSON_ (using a version of simplejson_
- bundled with Django).
+``json`` Serializes to and from JSON_ (using a version of simplejson_
+ bundled with Django).
- ``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
- serializer is only available if PyYAML_ is installed.
- ========== ==============================================================
+``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
+ serializer is only available if PyYAML_ is installed.
+========== ==============================================================
.. _json: http://json.org/
.. _simplejson: http://undefined.org/python/#simplejson
diff --git a/docs/topics/settings.txt b/docs/topics/settings.txt
index 61ddf8cf32..8e4f1dfe57 100644
--- a/docs/topics/settings.txt
+++ b/docs/topics/settings.txt
@@ -19,13 +19,13 @@ Here are a couple of example settings::
Because a settings file is a Python module, the following apply:
- * It doesn't allow for Python syntax errors.
- * It can assign settings dynamically using normal Python syntax.
- For example::
+* It doesn't allow for Python syntax errors.
+* It can assign settings dynamically using normal Python syntax.
+ For example::
- MY_SETTING = [str(i) for i in range(30)]
+ MY_SETTING = [str(i) for i in range(30)]
- * It can import values from other settings files.
+* It can import values from other settings files.
.. _django-settings-module:
@@ -87,9 +87,9 @@ module :file:`django/conf/global_settings.py`.
Here's the algorithm Django uses in compiling settings:
- * Load settings from ``global_settings.py``.
- * Load settings from the specified settings file, overriding the global
- settings as necessary.
+* Load settings from ``global_settings.py``.
+* Load settings from the specified settings file, overriding the global
+ settings as necessary.
Note that a settings file should *not* import from ``global_settings``, because
that's redundant.
@@ -156,8 +156,8 @@ Creating your own settings
There's nothing stopping you from creating your own settings, for your own
Django apps. Just follow these conventions:
- * Setting names are in all uppercase.
- * Don't reinvent an already-existing setting.
+* Setting names are in all uppercase.
+* Don't reinvent an already-existing setting.
For settings that are sequences, Django itself uses tuples, rather than lists,
but this is only a convention.
diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt
index df4b58b7be..b4f70cf9e1 100644
--- a/docs/topics/signals.txt
+++ b/docs/topics/signals.txt
@@ -15,27 +15,27 @@ Django provides a :doc:`set of built-in signals </ref/signals>` that let user
code get notified by Django itself of certain actions. These include some useful
notifications:
- * :data:`django.db.models.signals.pre_save` &
- :data:`django.db.models.signals.post_save`
+* :data:`django.db.models.signals.pre_save` &
+ :data:`django.db.models.signals.post_save`
- Sent before or after a model's :meth:`~django.db.models.Model.save` method
- is called.
+ Sent before or after a model's :meth:`~django.db.models.Model.save` method
+ is called.
- * :data:`django.db.models.signals.pre_delete` &
- :data:`django.db.models.signals.post_delete`
+* :data:`django.db.models.signals.pre_delete` &
+ :data:`django.db.models.signals.post_delete`
- Sent before or after a model's :meth:`~django.db.models.Model.delete`
- method or queryset's :meth:`~django.db.models.query.QuerySet.delete`
- method is called.
+ Sent before or after a model's :meth:`~django.db.models.Model.delete`
+ method or queryset's :meth:`~django.db.models.query.QuerySet.delete`
+ method is called.
- * :data:`django.db.models.signals.m2m_changed`
+* :data:`django.db.models.signals.m2m_changed`
- Sent when a :class:`ManyToManyField` on a model is changed.
+ Sent when a :class:`ManyToManyField` on a model is changed.
- * :data:`django.core.signals.request_started` &
- :data:`django.core.signals.request_finished`
+* :data:`django.core.signals.request_started` &
+ :data:`django.core.signals.request_finished`
- Sent when Django starts or finishes an HTTP request.
+ Sent when Django starts or finishes an HTTP request.
See the :doc:`built-in signal documentation </ref/signals>` for a complete list,
and a complete explanation of each signal.
diff --git a/docs/topics/signing.txt b/docs/topics/signing.txt
index 9e3cb7a4c1..f2ffd8a20c 100644
--- a/docs/topics/signing.txt
+++ b/docs/topics/signing.txt
@@ -18,14 +18,14 @@ signing in Web applications.
You may also find signing useful for the following:
- * Generating "recover my account" URLs for sending to users who have
- lost their password.
+* Generating "recover my account" URLs for sending to users who have
+ lost their password.
- * Ensuring data stored in hidden form fields has not been tampered with.
+* Ensuring data stored in hidden form fields has not been tampered with.
- * Generating one-time secret URLs for allowing temporary access to a
- protected resource, for example a downloadable file that a user has
- paid for.
+* Generating one-time secret URLs for allowing temporary access to a
+ protected resource, for example a downloadable file that a user has
+ paid for.
Protecting the SECRET_KEY
=========================
diff --git a/docs/topics/testing.txt b/docs/topics/testing.txt
index 1a4515673a..dc5bf7e7f5 100644
--- a/docs/topics/testing.txt
+++ b/docs/topics/testing.txt
@@ -9,12 +9,12 @@ Automated testing is an extremely useful bug-killing tool for the modern
Web developer. You can use a collection of tests -- a **test suite** -- to
solve, or avoid, a number of problems:
- * When you're writing new code, you can use tests to validate your code
- works as expected.
+* When you're writing new code, you can use tests to validate your code
+ works as expected.
- * When you're refactoring or modifying old code, you can use tests to
- ensure your changes haven't affected your application's behavior
- unexpectedly.
+* When you're refactoring or modifying old code, you can use tests to
+ ensure your changes haven't affected your application's behavior
+ unexpectedly.
Testing a Web application is a complex task, because a Web application is made
of several layers of logic -- from HTTP-level request handling, to form
@@ -35,31 +35,31 @@ There are two primary ways to write tests with Django, corresponding to the
two test frameworks that ship in the Python standard library. The two
frameworks are:
- * **Unit tests** -- tests that are expressed as methods on a Python class
- that subclasses :class:`unittest.TestCase` or Django's customized
- :class:`TestCase`. For example::
+* **Unit tests** -- tests that are expressed as methods on a Python class
+ that subclasses :class:`unittest.TestCase` or Django's customized
+ :class:`TestCase`. For example::
- import unittest
+ import unittest
- class MyFuncTestCase(unittest.TestCase):
- def testBasic(self):
- a = ['larry', 'curly', 'moe']
- self.assertEqual(my_func(a, 0), 'larry')
- self.assertEqual(my_func(a, 1), 'curly')
+ class MyFuncTestCase(unittest.TestCase):
+ def testBasic(self):
+ a = ['larry', 'curly', 'moe']
+ self.assertEqual(my_func(a, 0), 'larry')
+ self.assertEqual(my_func(a, 1), 'curly')
- * **Doctests** -- tests that are embedded in your functions' docstrings and
- are written in a way that emulates a session of the Python interactive
- interpreter. For example::
+* **Doctests** -- tests that are embedded in your functions' docstrings and
+ are written in a way that emulates a session of the Python interactive
+ interpreter. For example::
- def my_func(a_list, idx):
- """
- >>> a = ['larry', 'curly', 'moe']
- >>> my_func(a, 0)
- 'larry'
- >>> my_func(a, 1)
- 'curly'
- """
- return a_list[idx]
+ def my_func(a_list, idx):
+ """
+ >>> a = ['larry', 'curly', 'moe']
+ >>> my_func(a, 0)
+ 'larry'
+ >>> my_func(a, 1)
+ 'curly'
+ """
+ return a_list[idx]
We'll discuss choosing the appropriate test framework later, however, most
experienced developers prefer unit tests. You can also use any *other* Python
@@ -103,12 +103,12 @@ module defines tests in class-based approach.
For a given Django application, the test runner looks for unit tests in two
places:
- * The ``models.py`` file. The test runner looks for any subclass of
- :class:`unittest.TestCase` in this module.
+* The ``models.py`` file. The test runner looks for any subclass of
+ :class:`unittest.TestCase` in this module.
- * A file called ``tests.py`` in the application directory -- i.e., the
- directory that holds ``models.py``. Again, the test runner looks for any
- subclass of :class:`unittest.TestCase` in this module.
+* A file called ``tests.py`` in the application directory -- i.e., the
+ directory that holds ``models.py``. Again, the test runner looks for any
+ subclass of :class:`unittest.TestCase` in this module.
Here is an example :class:`unittest.TestCase` subclass::
@@ -169,14 +169,14 @@ of this document; read Python's official documentation for the details.
As with unit tests, for a given Django application, the test runner looks for
doctests in two places:
- * The ``models.py`` file. You can define module-level doctests and/or a
- doctest for individual models. It's common practice to put
- application-level doctests in the module docstring and model-level
- doctests in the model docstrings.
+* The ``models.py`` file. You can define module-level doctests and/or a
+ doctest for individual models. It's common practice to put
+ application-level doctests in the module docstring and model-level
+ doctests in the model docstrings.
- * A file called ``tests.py`` in the application directory -- i.e., the
- directory that holds ``models.py``. This file is a hook for any and all
- doctests you want to write that aren't necessarily related to models.
+* A file called ``tests.py`` in the application directory -- i.e., the
+ directory that holds ``models.py``. This file is a hook for any and all
+ doctests you want to write that aren't necessarily related to models.
This example doctest is equivalent to the example given in the unittest section
above::
@@ -231,30 +231,30 @@ For developers new to testing, however, this choice can seem confusing. Here,
then, are a few key differences to help you decide which approach is right for
you:
- * If you've been using Python for a while, :mod:`doctest` will probably feel
- more "pythonic". It's designed to make writing tests as easy as possible,
- so it requires no overhead of writing classes or methods. You simply put
- tests in docstrings. This has the added advantage of serving as
- documentation (and correct documentation, at that!). However, while
- doctests are good for some simple example code, they are not very good if
- you want to produce either high quality, comprehensive tests or high
- quality documentation. Test failures are often difficult to debug
- as it can be unclear exactly why the test failed. Thus, doctests should
- generally be avoided and used primarily for documentation examples only.
+* If you've been using Python for a while, :mod:`doctest` will probably feel
+ more "pythonic". It's designed to make writing tests as easy as possible,
+ so it requires no overhead of writing classes or methods. You simply put
+ tests in docstrings. This has the added advantage of serving as
+ documentation (and correct documentation, at that!). However, while
+ doctests are good for some simple example code, they are not very good if
+ you want to produce either high quality, comprehensive tests or high
+ quality documentation. Test failures are often difficult to debug
+ as it can be unclear exactly why the test failed. Thus, doctests should
+ generally be avoided and used primarily for documentation examples only.
- * The :mod:`unittest` framework will probably feel very familiar to
- developers coming from Java. :mod:`unittest` is inspired by Java's JUnit,
- so you'll feel at home with this method if you've used JUnit or any test
- framework inspired by JUnit.
+* The :mod:`unittest` framework will probably feel very familiar to
+ developers coming from Java. :mod:`unittest` is inspired by Java's JUnit,
+ so you'll feel at home with this method if you've used JUnit or any test
+ framework inspired by JUnit.
- * If you need to write a bunch of tests that share similar code, then
- you'll appreciate the :mod:`unittest` framework's organization around
- classes and methods. This makes it easy to abstract common tasks into
- common methods. The framework also supports explicit setup and/or cleanup
- routines, which give you a high level of control over the environment
- in which your test cases are run.
+* If you need to write a bunch of tests that share similar code, then
+ you'll appreciate the :mod:`unittest` framework's organization around
+ classes and methods. This makes it easy to abstract common tasks into
+ common methods. The framework also supports explicit setup and/or cleanup
+ routines, which give you a high level of control over the environment
+ in which your test cases are run.
- * If you're writing tests for Django itself, you should use :mod:`unittest`.
+* If you're writing tests for Django itself, you should use :mod:`unittest`.
.. _running-tests:
@@ -571,24 +571,24 @@ programmatically.
Some of the things you can do with the test client are:
- * Simulate GET and POST requests on a URL and observe the response --
- everything from low-level HTTP (result headers and status codes) to
- page content.
+* Simulate GET and POST requests on a URL and observe the response --
+ everything from low-level HTTP (result headers and status codes) to
+ page content.
- * Test that the correct view is executed for a given URL.
+* Test that the correct view is executed for a given URL.
- * Test that a given request is rendered by a given Django template, with
- a template context that contains certain values.
+* Test that a given request is rendered by a given Django template, with
+ a template context that contains certain values.
Note that the test client is not intended to be a replacement for Twill_,
Selenium_, or other "in-browser" frameworks. Django's test client has
a different focus. In short:
- * Use Django's test client to establish that the correct view is being
- called and that the view is collecting the correct context data.
+* Use Django's test client to establish that the correct view is being
+ called and that the view is collecting the correct context data.
- * Use in-browser frameworks such as Twill and Selenium to test *rendered*
- HTML and the *behavior* of Web pages, namely JavaScript functionality.
+* Use in-browser frameworks such as Twill and Selenium to test *rendered*
+ HTML and the *behavior* of Web pages, namely JavaScript functionality.
A comprehensive test suite should use a combination of both test types.
@@ -615,51 +615,51 @@ of the Python interactive interpreter.
Note a few important things about how the test client works:
- * The test client does *not* require the Web server to be running. In fact,
- it will run just fine with no Web server running at all! That's because
- it avoids the overhead of HTTP and deals directly with the Django
- framework. This helps make the unit tests run quickly.
+* The test client does *not* require the Web server to be running. In fact,
+ it will run just fine with no Web server running at all! That's because
+ it avoids the overhead of HTTP and deals directly with the Django
+ framework. This helps make the unit tests run quickly.
- * When retrieving pages, remember to specify the *path* of the URL, not the
- whole domain. For example, this is correct::
+* When retrieving pages, remember to specify the *path* of the URL, not the
+ whole domain. For example, this is correct::
- >>> c.get('/login/')
+ >>> c.get('/login/')
- This is incorrect::
+ This is incorrect::
- >>> c.get('http://www.example.com/login/')
+ >>> c.get('http://www.example.com/login/')
- The test client is not capable of retrieving Web pages that are not
- powered by your Django project. If you need to retrieve other Web pages,
- use a Python standard library module such as :mod:`urllib` or
- :mod:`urllib2`.
+ The test client is not capable of retrieving Web pages that are not
+ powered by your Django project. If you need to retrieve other Web pages,
+ use a Python standard library module such as :mod:`urllib` or
+ :mod:`urllib2`.
- * To resolve URLs, the test client uses whatever URLconf is pointed-to by
- your :setting:`ROOT_URLCONF` setting.
+* To resolve URLs, the test client uses whatever URLconf is pointed-to by
+ your :setting:`ROOT_URLCONF` setting.
- * Although the above example would work in the Python interactive
- interpreter, some of the test client's functionality, notably the
- template-related functionality, is only available *while tests are
- running*.
+* Although the above example would work in the Python interactive
+ interpreter, some of the test client's functionality, notably the
+ template-related functionality, is only available *while tests are
+ running*.
- The reason for this is that Django's test runner performs a bit of black
- magic in order to determine which template was loaded by a given view.
- This black magic (essentially a patching of Django's template system in
- memory) only happens during test running.
+ The reason for this is that Django's test runner performs a bit of black
+ magic in order to determine which template was loaded by a given view.
+ This black magic (essentially a patching of Django's template system in
+ memory) only happens during test running.
- * By default, the test client will disable any CSRF checks
- performed by your site.
+* By default, the test client will disable any CSRF checks
+ performed by your site.
- .. versionadded:: 1.2.2
+ .. versionadded:: 1.2.2
- If, for some reason, you *want* the test client to perform CSRF
- checks, you can create an instance of the test client that
- enforces CSRF checks. To do this, pass in the
- ``enforce_csrf_checks`` argument when you construct your
- client::
+ If, for some reason, you *want* the test client to perform CSRF
+ checks, you can create an instance of the test client that
+ enforces CSRF checks. To do this, pass in the
+ ``enforce_csrf_checks`` argument when you construct your
+ client::
- >>> from django.test import Client
- >>> csrf_client = Client(enforce_csrf_checks=True)
+ >>> from django.test import Client
+ >>> csrf_client = Client(enforce_csrf_checks=True)
Making requests
~~~~~~~~~~~~~~~
@@ -1047,18 +1047,18 @@ a black box, with exactly known inputs, testing for specific outputs.
The API for the :class:`~django.test.client.RequestFactory` is a slightly
restricted subset of the test client API:
- * It only has access to the HTTP methods :meth:`~Client.get()`,
- :meth:`~Client.post()`, :meth:`~Client.put()`,
- :meth:`~Client.delete()`, :meth:`~Client.head()` and
- :meth:`~Client.options()`.
+* It only has access to the HTTP methods :meth:`~Client.get()`,
+ :meth:`~Client.post()`, :meth:`~Client.put()`,
+ :meth:`~Client.delete()`, :meth:`~Client.head()` and
+ :meth:`~Client.options()`.
- * These methods accept all the same arguments *except* for
- ``follows``. Since this is just a factory for producing
- requests, it's up to you to handle the response.
+* These methods accept all the same arguments *except* for
+ ``follows``. Since this is just a factory for producing
+ requests, it's up to you to handle the response.
- * It does not support middleware. Session and authentication
- attributes must be supplied by the test itself if required
- for the view to function properly.
+* It does not support middleware. Session and authentication
+ attributes must be supplied by the test itself if required
+ for the view to function properly.
Example
~~~~~~~
@@ -1100,14 +1100,14 @@ easy: just change the base class of your test from :class:`unittest.TestCase` to
functionality will continue to be available, but it will be augmented with some
useful additions, including:
- * Automatic loading of fixtures.
+* Automatic loading of fixtures.
- * Wraps each test in a transaction.
+* Wraps each test in a transaction.
- * Creates a TestClient instance.
+* Creates a TestClient instance.
- * Django-specific assertions for testing for things
- like redirection and form errors.
+* Django-specific assertions for testing for things
+ like redirection and form errors.
``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
@@ -1162,20 +1162,20 @@ by truncating tables and reloading initial data.
A very thin subclass of :class:`unittest.TestCase`, it extends it with some
basic functionality like:
- * Saving and restoring the Python warning machinery state.
- * Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`.
- * :meth:`Testing form field rendering <assertFieldOutput>`.
+* Saving and restoring the Python warning machinery state.
+* Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`.
+* :meth:`Testing form field rendering <assertFieldOutput>`.
If you need any of the other more complex and heavyweight Django-specific
features like:
- * The ability to run tests with :ref:`modified settings <overriding-settings>`
- * Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
- * Testing or using the ORM.
- * Database :attr:`~TestCase.fixtures`.
- * Custom test-time :attr:`URL maps <TestCase.urls>`.
- * Test :ref:`skipping based on database backend features <skipping-tests>`.
- * Our specialized :ref:`assert* <assertions>` metods.
+* The ability to run tests with :ref:`modified settings <overriding-settings>`
+* Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
+* Testing or using the ORM.
+* Database :attr:`~TestCase.fixtures`.
+* Custom test-time :attr:`URL maps <TestCase.urls>`.
+* Test :ref:`skipping based on database backend features <skipping-tests>`.
+* Our specialized :ref:`assert* <assertions>` metods.
then you should use :class:`~django.test.TransactionTestCase` or
:class:`~django.test.TestCase` instead.
@@ -1306,14 +1306,14 @@ subclass::
Here's specifically what will happen:
- * At the start of each test case, before ``setUp()`` is run, Django will
- flush the database, returning the database to the state it was in
- directly after :djadmin:`syncdb` was called.
+* At the start of each test case, before ``setUp()`` is run, Django will
+ flush the database, returning the database to the state it was in
+ directly after :djadmin:`syncdb` was called.
- * Then, all the named fixtures are installed. In this example, Django will
- install any JSON fixture named ``mammals``, followed by any fixture named
- ``birds``. See the :djadmin:`loaddata` documentation for more
- details on defining and installing fixtures.
+* Then, all the named fixtures are installed. In this example, Django will
+ install any JSON fixture named ``mammals``, followed by any fixture named
+ ``birds``. See the :djadmin:`loaddata` documentation for more
+ details on defining and installing fixtures.
This flush/load procedure is repeated for each test in the test case, so you
can be certain that the outcome of a test will not be affected by another test,
@@ -1762,21 +1762,21 @@ setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
``'django.test.simple.DjangoTestSuiteRunner'``. This class defines the default Django
testing behavior. This behavior involves:
- #. Performing global pre-test setup.
+#. Performing global pre-test setup.
- #. Looking for unit tests and doctests in the ``models.py`` and
- ``tests.py`` files in each installed application.
+#. Looking for unit tests and doctests in the ``models.py`` and
+ ``tests.py`` files in each installed application.
- #. Creating the test databases.
+#. Creating the test databases.
- #. Running ``syncdb`` to install models and initial data into the test
- databases.
+#. Running ``syncdb`` to install models and initial data into the test
+ databases.
- #. Running the unit tests and doctests that are found.
+#. Running the unit tests and doctests that are found.
- #. Destroying the test databases.
+#. Destroying the test databases.
- #. Performing global post-test teardown.
+#. Performing global post-test teardown.
If you define your own test runner class and point :setting:`TEST_RUNNER` at
that class, Django will execute your test runner whenever you run
@@ -1851,10 +1851,10 @@ Methods
``test_labels`` is a list of strings describing the tests to be run. A test
label can take one of three forms:
- * ``app.TestCase.test_method`` -- Run a single test method in a test
- case.
- * ``app.TestCase`` -- Run all the test methods in a test case.
- * ``app`` -- Search for and run all tests in the named application.
+ * ``app.TestCase.test_method`` -- Run a single test method in a test
+ case.
+ * ``app.TestCase`` -- Run all the test methods in a test case.
+ * ``app`` -- Search for and run all tests in the named application.
If ``test_labels`` has a value of ``None``, the test runner should run
search for tests in all the applications in :setting:`INSTALLED_APPS`.
@@ -1876,10 +1876,10 @@ Methods
``test_labels`` is a list of strings describing the tests to be run. A test
label can take one of three forms:
- * ``app.TestCase.test_method`` -- Run a single test method in a test
- case.
- * ``app.TestCase`` -- Run all the test methods in a test case.
- * ``app`` -- Search for and run all tests in the named application.
+ * ``app.TestCase.test_method`` -- Run a single test method in a test
+ case.
+ * ``app.TestCase`` -- Run all the test methods in a test case.
+ * ``app`` -- Search for and run all tests in the named application.
If ``test_labels`` has a value of ``None``, the test runner should run
search for tests in all the applications in :setting:`INSTALLED_APPS`.
@@ -1957,12 +1957,12 @@ also provides some utilities that can be useful during testing.
``autoclobber`` describes the behavior that will occur if a
database with the same name as the test database is discovered:
- * If ``autoclobber`` is ``False``, the user will be asked to
- approve destroying the existing database. ``sys.exit`` is
- called if the user does not approve.
+ * If ``autoclobber`` is ``False``, the user will be asked to
+ approve destroying the existing database. ``sys.exit`` is
+ called if the user does not approve.
- * If autoclobber is ``True``, the database will be destroyed
- without consulting the user.
+ * If autoclobber is ``True``, the database will be destroyed
+ without consulting the user.
Returns the name of the test database that it created.